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/other/action/state/ActionSetCounter.java | package other.action.state;
import java.util.BitSet;
import game.rules.play.moves.Moves;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.concept.Concept;
import other.context.Context;
/**
* Sets the counter of the state.
*
* @author Eric.Piette
*/
public final class ActionSetCounter extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The new counter. */
private final int counter;
//-------------------------------------------------------------------------
/**
* @param counter The new counter.
*/
public ActionSetCounter
(
final int counter
)
{
this.counter = counter;
}
/**
* Reconstructs an ActionSetCounter object from a detailed String
* (generated using toDetailedString())
* @param detailedString
*/
public ActionSetCounter(final String detailedString)
{
assert (detailedString.startsWith("[SetCounter:"));
final String strCounter = Action.extractData(detailedString, "counter");
counter = Integer.parseInt(strCounter);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
context.state().setCounter(counter);
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
// No need going to be reset in game.undo(...)
return this;
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetCounter:");
sb.append("counter=" + counter);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (decision ? 1231 : 1237);
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetCounter))
return false;
final ActionSetCounter other = (ActionSetCounter) obj;
return (decision == other.decision && counter == other.counter);
}
@Override
public String getDescription()
{
return "SetCounter";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
return "Counter=" + counter;
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
return "(Counter = " + counter + ")";
}
@Override
public ActionType actionType()
{
return ActionType.SetCounter;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Context context, final Moves movesLudeme)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.SetInternalCounter.id(), true);
return concepts;
}
}
| 3,226 | 21.10274 | 81 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionSetNextPlayer.java | package other.action.state;
import java.util.BitSet;
import game.rules.play.moves.Moves;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.concept.Concept;
import other.context.Context;
/**
* Sets the next player.
*
* @author Eric.Piette
*/
public final class ActionSetNextPlayer extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Index of player. */
private final int player;
//-------------------------------------------------------------------------
/** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */
private boolean alreadyApplied = false;
/** The previous value. */
private int previousValue;
//-------------------------------------------------------------------------
/**
* @param player The new next player.
*/
public ActionSetNextPlayer
(
final int player
)
{
this.player = player;
}
/**
* Reconstructs a ActionSetNextPlayer object from a detailed String (generated
* using toDetailedString())
*
* @param detailedString
*/
public ActionSetNextPlayer(final String detailedString)
{
assert (detailedString.startsWith("[SetNextPlayer:"));
final String strPlayer = Action.extractData(detailedString, "player");
player = Integer.parseInt(strPlayer);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
if(!alreadyApplied)
{
previousValue = context.state().next();
alreadyApplied = true;
}
context.state().setNext(player);
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
context.state().setNext(previousValue);
return this;
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetNextPlayer:");
sb.append("player=" + player);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (decision ? 1231 : 1237);
result = prime * result + player;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetNextPlayer))
return false;
final ActionSetNextPlayer other = (ActionSetNextPlayer) obj;
return (decision == other.decision &&
player == other.player);
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "SetNextPlayer";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
return "Next P" + player;
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
return "(Next Player = P" + player + ")";
}
//-------------------------------------------------------------------------
@Override
public boolean isOtherMove()
{
return true;
}
@Override
public int who()
{
return player;
}
@Override
public int what()
{
return player;
}
@Override
public int playerSelected()
{
return player;
}
@Override
public ActionType actionType()
{
return ActionType.SetNextPlayer;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Context context, final Moves movesLudeme)
{
final int mover = context.state().mover();
final BitSet concepts = new BitSet();
concepts.set(Concept.SetNextPlayer.id(), true);
if (mover == player)
concepts.set(Concept.MoveAgain.id(), true);
return concepts;
}
}
| 4,182 | 20.786458 | 123 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionSetPending.java | package other.action.state;
import java.util.BitSet;
import game.rules.play.moves.Moves;
import main.Constants;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.concept.Concept;
import other.context.Context;
/**
* Sets a value to be in pending in the state.
*
* @author Eric.Piette
*/
public final class ActionSetPending extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The potential pending value. */
final int value;
//-------------------------------------------------------------------------
/**
* @param value The value.
*/
public ActionSetPending
(
final int value
)
{
this.value = value;
}
/**
* Reconstructs an ActionPending object from a detailed String
* (generated using toDetailedString())
* @param detailedString
*/
public ActionSetPending(final String detailedString)
{
assert (detailedString.startsWith("[SetPending:"));
final String strValue = Action.extractData(detailedString, "value");
value = (strValue.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strValue);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
context.state().setPending(value);
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
// No need going to be reset in game.undo(...)
return this;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (decision ? 1231 : 1237);
result = prime * result + value;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetPending))
return false;
final ActionSetPending other = (ActionSetPending) obj;
return (decision == other.decision && value == other.value);
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetPending:");
if (value != Constants.UNDEFINED)
sb.append("value=" + value);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "SetPending";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
if(value != Constants.UNDEFINED)
return "Pending=" + value;
return "Set Pending";
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
if (value != Constants.UNDEFINED)
return "(Pending = " + value + ")";
return "(Pending)";
}
@Override
public ActionType actionType()
{
return ActionType.SetPending;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Context context, final Moves movesLudeme)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.SetPending.id(), true);
return concepts;
}
}
| 3,616 | 21.748428 | 82 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionSetPot.java | package other.action.state;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.context.Context;
/**
* Sets the pot.
*
* @author Eric.Piette
*/
public final class ActionSetPot extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The pot. */
private final int pot;
//-------------------------------------------------------------------------
/** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */
private boolean alreadyApplied = false;
/** The previous pot. */
private int previousPot;
//-------------------------------------------------------------------------
/**
* @param pot The new value of the pot.
*/
public ActionSetPot
(
final int pot
)
{
this.pot = pot;
}
/**
* Reconstructs an ActionSetPot object from a detailed String (generated using
* toDetailedString())
*
* @param detailedString
*/
public ActionSetPot(final String detailedString)
{
assert (detailedString.startsWith("[SetPot:"));
final String strBet = Action.extractData(detailedString, "pot");
pot = Integer.parseInt(strBet);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
if(!alreadyApplied)
{
previousPot = context.state().pot();
alreadyApplied = true;
}
context.state().setPot(pot);
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
context.state().setPot(previousPot);
return this;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (decision ? 1231 : 1237);
result = prime * result + pot;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetPot))
return false;
final ActionSetPot other = (ActionSetPot) obj;
return (decision == other.decision && pot == other.pot);
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetPot:");
sb.append("pot=" + pot);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "Pot";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
return "Pot " + " $" + pot;
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
return "(Pot = " + pot + ")";
}
//-------------------------------------------------------------------------
@Override
public boolean isOtherMove()
{
return true;
}
@Override
public int count()
{
return pot;
}
@Override
public ActionType actionType()
{
return ActionType.SetPot;
}
}
| 3,492 | 20.169697 | 123 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionSetRotation.java | package other.action.state;
import java.util.BitSet;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import main.Constants;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Sets the rotation value of a site.
*
* @author Eric.Piette
*/
public final class ActionSetRotation extends BaseAction
{
//-------------------------------------------------------------------------
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Loc index. */
private final int to;
/** The new rotation value. */
private final int rotation;
/** The graph element type. */
private SiteType type;
//-------------------------------------------------------------------------
/** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */
private boolean alreadyApplied = false;
/** The previous rotation. */
private int previousRotation;
/** The previous site type. */
private SiteType previousType;
//-------------------------------------------------------------------------
/**
* @param type The graph element type.
* @param to The index of the site.
* @param rotation The new rotation.
*/
public ActionSetRotation
(
final SiteType type,
final int to,
final int rotation
)
{
this.to = to;
this.rotation = rotation;
this.type = type;
}
/**
* Reconstructs an ActionSetRotation object from a detailed String (generated
* using toDetailedString())
*
* @param detailedString
*/
public ActionSetRotation(final String detailedString)
{
assert (detailedString.startsWith("[SetRotation:"));
final String strType = Action.extractData(detailedString, "type");
type = (strType.isEmpty()) ? null : SiteType.valueOf(strType);
final String strTo = Action.extractData(detailedString, "to");
to = Integer.parseInt(strTo);
final String strRotation = Action.extractData(detailedString, "rotation");
rotation = Integer.parseInt(strRotation);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
type = (type == null) ? context.board().defaultSite() : type;
final int cid = to >= context.containerId().length ? 0 : context.containerId()[to];
final ContainerState cs = context.state().containerStates()[cid];
// if (context.game().isStacking()) // Level has to be implemented
// {
// if (level != Constants.UNDEFINED)
// {
// final int stackSize = cs.sizeStack(to, type);
// if (level < stackSize)
// {
// if(!alreadyApplied)
// {
// previousValue = cs.value(to, level, type);
// previousType = type;
// alreadyApplied = true;
// }
//
// final int what = cs.what(to, level, type);
// final int who = cs.who(to, level, type);
// final int value = cs.value(to, level, type);
// final int state = cs.state(to, level, type);
// cs.remove(context.state(), to, level);
// cs.insert(context.state(), type, to, level, what, who, state, rotation, value, context.game());
// }
// }
// else
// {
// if(!alreadyApplied)
// {
// previousValue = cs.value(to, type);
// previousType = type;
// alreadyApplied = true;
// }
//
// context.containerState(context.containerId()[to]).setSite(context.state(), to, Constants.UNDEFINED,
// Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, rotation, Constants.UNDEFINED,
// type);
// }
// }
// else
// {
if(!alreadyApplied)
{
previousRotation = cs.rotation(to, type);
previousType = type;
alreadyApplied = true;
}
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, rotation, Constants.UNDEFINED, type);
//}
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
final int cid = to >= context.containerId().length ? 0 : context.containerId()[to];
final ContainerState cs = context.state().containerStates()[cid];
// if (context.game().isStacking()) // Level has to be implemented
// {
// final int stackSize = cs.sizeStack(to, type);
//
// if (level != Constants.UNDEFINED)
// {
// if (level < stackSize)
// {
// final int what = cs.what(to, level, type);
// final int who = cs.who(to, level, type);
// final int value = cs.value(to, level, type);
// final int state = cs.state(to, level, type);
// cs.remove(context.state(), to, level);
// cs.insert(context.state(), previousType, to, level, what, who, state, previousValue, value, context.game());
// }
// }
// else
// {
// cs.setSite(context.state(), to, Constants.UNDEFINED,
// Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, previousValue, Constants.UNDEFINED,
// previousType);
// }
// }
// else
// {
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, previousRotation, Constants.UNDEFINED, previousType);
// }
return this;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (decision ? 1231 : 1237);
result = prime * result + to;
result = prime * result + rotation;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetRotation))
return false;
final ActionSetRotation other = (ActionSetRotation) obj;
return (decision == other.decision && to == other.to && rotation == other.rotation
&& type == other.type);
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetRotation:");
if (type != null || (context != null && type != context.board().defaultSite()))
{
sb.append("type=" + type);
sb.append(",to=" + to);
}
else
sb.append("to=" + to);
sb.append(",rotation=" + rotation);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "SetRotation";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
final StringBuilder sb = new StringBuilder();
String newTo = to + "";
if (useCoords)
{
final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell)
? context.containerId()[to]
: 0;
if (cid == 0)
{
final SiteType realType = (type != null) ? type : context.board().defaultSite();
newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to)
.label();
}
}
if (type != null && !type.equals(context.board().defaultSite()))
sb.append(type + " " + newTo);
else
sb.append(newTo);
sb.append(" r" + rotation);
return sb.toString();
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
final StringBuilder sb = new StringBuilder();
sb.append("(Rotation ");
String newTo = to + "";
if (useCoords)
{
final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell)
? context.containerId()[to]
: 0;
if (cid == 0)
{
final SiteType realType = (type != null) ? type : context.board().defaultSite();
newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to)
.label();
}
}
if (type != null && !type.equals(context.board().defaultSite()))
sb.append(type + " " + newTo);
else
sb.append(newTo);
sb.append(" = " + rotation);
sb.append(')');
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public SiteType fromType()
{
return type;
}
@Override
public SiteType toType()
{
return type;
}
@Override
public int rotation()
{
return rotation;
}
@Override
public int from()
{
return to;
}
@Override
public int to()
{
return to;
}
@Override
public int state()
{
return rotation;
}
@Override
public int who()
{
return rotation;
}
@Override
public ActionType actionType()
{
return ActionType.SetRotation;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Context context, final Moves movesLudeme)
{
final BitSet concepts = new BitSet();
if(decision)
concepts.set(Concept.RotationDecision.id(), true);
else
concepts.set(Concept.SetRotation.id(), true);
return concepts;
}
}
| 9,466 | 23.978892 | 123 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionSetScore.java | package other.action.state;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.context.Context;
/**
* Sets the score of a player.
*
* @author Eric.Piette
*/
public final class ActionSetScore extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The score's player to update. */
private final int player;
/** The new score. */
private final int score;
/** True if the score has to be add to the current score. */
private final boolean add;
//-------------------------------------------------------------------------
/** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */
private boolean alreadyApplied = false;
/** The previous score. */
private int previousScore;
//-------------------------------------------------------------------------
/**
* @param player The index of the player.
* @param score The score.
* @param add True if the score has to be added.
*/
public ActionSetScore
(
final int player,
final int score,
final Boolean add
)
{
this.player = player;
this.score = score;
this.add = (add == null) ? false : add.booleanValue();
}
/**
* Reconstructs an ActionSetScore object from a detailed String (generated using
* toDetailedString())
*
* @param detailedString
*/
public ActionSetScore(final String detailedString)
{
assert (detailedString.startsWith("[SetScore:"));
final String strPlayer = Action.extractData(detailedString, "player");
player = Integer.parseInt(strPlayer);
final String strScore = Action.extractData(detailedString, "score");
score = Integer.parseInt(strScore);
final String strAddScore = Action.extractData(detailedString, "add");
add = (strAddScore.isEmpty()) ? false : Boolean.parseBoolean(strAddScore);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
if(!alreadyApplied)
{
previousScore = context.score(player);
alreadyApplied = true;
}
if (add)
context.setScore(player, context.score(player) + score);
else
context.setScore(player, score);
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
context.setScore(player, previousScore);
return this;
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetScore:");
sb.append("player=" + player);
sb.append(",score=" + score);
if (add)
sb.append(",add=" + add);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (decision ? 1231 : 1237);
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetScore))
return false;
final ActionSetScore other = (ActionSetScore) obj;
return (decision == other.decision && score == other.score && player == other.player);
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "SetScore";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
if (!add)
return "P" + player + "=" + score;
return "P" + player + "+=" + score;
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
if (!add)
return "(Score P" + player + " = " + score + ")";
return "(Score P" + player + " += " + score + ")";
}
//-------------------------------------------------------------------------
@Override
public int who()
{
return player;
}
@Override
public ActionType actionType()
{
return ActionType.SetScore;
}
}
| 4,363 | 22.336898 | 123 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionSetState.java | package other.action.state;
import java.util.BitSet;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import main.Constants;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Sets the state of a site.
*
* @author Eric.Piette
*/
public class ActionSetState extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Loc index. */
private final int to;
/** Level index. */
private final int level;
/** Local state. */
private final int state;
/** The graph element type. */
private SiteType type;
//-------------------------------------------------------------------------
/** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */
private boolean alreadyApplied = false;
/** The previous state of the site before to be removed. */
private int previousState;
//-------------------------------------------------------------------------
/**
* @param type The graph element type.
* @param to The site.
* @param level The level.
* @param state The state value.
*/
public ActionSetState
(
final SiteType type,
final int to,
final int level,
final int state
)
{
this.to = to;
this.level = level;
this.state = state;
this.type = type;
}
/**
* Reconstructs an ActionSetState object from a detailed String (generated using
* toDetailedString())
*
* @param detailedString
*/
public ActionSetState(final String detailedString)
{
assert (detailedString.startsWith("[SetState:"));
final String strType = Action.extractData(detailedString, "type");
type = (strType.isEmpty()) ? null : SiteType.valueOf(strType);
final String strTo = Action.extractData(detailedString, "to");
to = Integer.parseInt(strTo);
final String strLevel = Action.extractData(detailedString, "level");
level = (strLevel.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevel);
final String strState = Action.extractData(detailedString, "state");
state = Integer.parseInt(strState);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
type = (type == null) ? context.board().defaultSite() : type;
final int cid = type.equals(SiteType.Cell) ? context.containerId()[to] : 0;
final ContainerState cs = context.state().containerStates()[cid];
if (context.game().isStacking())
{
if (level != Constants.UNDEFINED)
{
final int stackSize = cs.sizeStack(to, type);
if (level < stackSize)
{
if(!alreadyApplied)
{
previousState = cs.state(to, level, type);
alreadyApplied = true;
}
final int what = cs.what(to, level, type);
final int who = cs.who(to, level, type);
final int rotation = cs.rotation(to, level, type);
final int value = cs.value(to, level, type);
cs.remove(context.state(), to, level, type);
cs.insert(context.state(), type, to, level, what, who, state, rotation, value, context.game());
}
}
else
{
if(!alreadyApplied)
{
previousState = cs.state(to, type);
alreadyApplied = true;
}
if(cid == 0)
{
if(to < context.containers()[0].topology().getGraphElements(type).size())
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, state, Constants.UNDEFINED, Constants.UNDEFINED, type);
}
else
{
if((to - context.sitesFrom()[cid]) < context.containers()[cid].topology().getGraphElements(type).size())
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, state, Constants.UNDEFINED, Constants.UNDEFINED, type);
}
}
}
else
{
if(!alreadyApplied)
{
previousState = cs.state(to, type);
alreadyApplied = true;
}
if(cid == 0)
{
if(to < context.containers()[0].topology().getGraphElements(type).size())
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, state, Constants.UNDEFINED, Constants.UNDEFINED, type);
}
else
{
if((to - context.sitesFrom()[cid]) < context.containers()[cid].topology().getGraphElements(type).size())
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, state, Constants.UNDEFINED, Constants.UNDEFINED, type);
}
}
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
type = (type == null) ? context.board().defaultSite() : type;
final int cid = type.equals(SiteType.Cell) ? context.containerId()[to] : 0;
final ContainerState cs = context.state().containerStates()[cid];
if (context.game().isStacking())
{
if (level != Constants.UNDEFINED)
{
final int stackSize = cs.sizeStack(to, type);
if (level < stackSize)
{
final int what = cs.what(to, level, type);
final int who = cs.who(to, level, type);
final int rotation = cs.rotation(to, level, type);
final int value = cs.value(to, level, type);
cs.remove(context.state(), to, level, type);
cs.insert(context.state(), type, to, level, what, who, previousState, rotation, value, context.game());
}
}
else
{
if(to < context.containers()[cid].topology().getGraphElements(type).size())
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, previousState, Constants.UNDEFINED, Constants.UNDEFINED, type);
}
}
else
{
if(to < context.containers()[cid].topology().getGraphElements(type).size())
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, previousState, Constants.UNDEFINED, Constants.UNDEFINED, type);
}
return this;
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetState:");
if (type != null || (context != null && type != context.board().defaultSite()))
{
sb.append("type=" + type);
sb.append(",to=" + to);
}
else
sb.append("to=" + to);
if (level != Constants.UNDEFINED)
sb.append(",level=" + level);
sb.append(",state=" + state);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + to;
if (level != Constants.UNDEFINED)
result = prime * result + level;
result = prime * result + state;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetState))
return false;
final ActionSetState other = (ActionSetState) obj;
return (to == other.to && level == other.level &&
state == other.state && type == other.type);
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "SetState";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
final StringBuilder sb = new StringBuilder();
String newTo = to + "";
if (useCoords)
{
final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell)
? context.containerId()[to]
: 0;
if (cid == 0)
{
final SiteType realType = (type != null) ? type : context.board().defaultSite();
newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to)
.label();
}
}
if (type != null && !type.equals(context.board().defaultSite()))
sb.append(type + " " + newTo);
else
sb.append(newTo);
if (level != Constants.UNDEFINED)
sb.append("/" + level);
sb.append("=" + state);
return sb.toString();
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
final StringBuilder sb = new StringBuilder();
sb.append("(State ");
String newTo = to + "";
if (useCoords)
{
final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell)
? context.containerId()[to]
: 0;
if (cid == 0)
{
final SiteType realType = (type != null) ? type : context.board().defaultSite();
newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to)
.label();
}
}
if (type != null && !type.equals(context.board().defaultSite()))
sb.append(type + " " + newTo);
else
sb.append(newTo);
if (level != Constants.UNDEFINED && context.game().isStacking())
sb.append("/" + level);
sb.append("=" + state);
sb.append(')');
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public SiteType fromType()
{
return type;
}
@Override
public SiteType toType()
{
return type;
}
@Override
public int from()
{
return to;
}
@Override
public int to()
{
return to;
}
@Override
public int state()
{
return state;
}
@Override
public int levelFrom()
{
return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level;
}
@Override
public int levelTo()
{
return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level;
}
@Override
public ActionType actionType()
{
return ActionType.SetState;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Context context, final Moves movesLudeme)
{
final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet();
final BitSet concepts = new BitSet();
concepts.set(Concept.SetSiteState.id(), true);
if (ludemeConcept.get(Concept.Flip.id()))
concepts.set(Concept.Flip.id(), true);
return concepts;
}
}
| 10,556 | 24.623786 | 123 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionSetTemp.java | package other.action.state;
import java.util.BitSet;
import game.rules.play.moves.Moves;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.concept.Concept;
import other.context.Context;
/**
* Sets the temporary value of the state.
*
* @author Eric.Piette
*/
public final class ActionSetTemp extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The new temporary value. */
private final int temp;
//-------------------------------------------------------------------------
/** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */
private boolean alreadyApplied = false;
/** The previous value. */
private int previousValue;
//-------------------------------------------------------------------------
/**
* @param temp The temporary value.
*/
public ActionSetTemp(final int temp)
{
this.temp = temp;
}
/**
* Reconstructs an ActionSetTemp object from a detailed String (generated using
* toDetailedString())
*
* @param detailedString
*/
public ActionSetTemp(final String detailedString)
{
assert (detailedString.startsWith("[SetTemp:"));
final String strTemp = Action.extractData(detailedString, "temp");
temp = Integer.parseInt(strTemp);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
if(!alreadyApplied)
{
previousValue = context.state().temp();
alreadyApplied = true;
}
context.state().setTemp(temp);
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
context.state().setTemp(previousValue);
return this;
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetTemp:");
sb.append("temp=" + temp);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (decision ? 1231 : 1237);
result = prime * result + temp;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetTemp))
return false;
final ActionSetTemp other = (ActionSetTemp) obj;
return (decision == other.decision && temp == other.temp);
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "SetTemp";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
return "Temp=" + temp;
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
return "(Temp = " + temp + ")";
}
@Override
public ActionType actionType()
{
return ActionType.SetTemp;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Context context, final Moves movesLudeme)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.SetVar.id(), true);
return concepts;
}
}
| 3,655 | 21.708075 | 123 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionSetValue.java | package other.action.state;
import java.util.BitSet;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import main.Constants;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Sets the piece value of a site.
*
* @author Eric.Piette
*/
public class ActionSetValue extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Loc index. */
private final int to;
/** Level index. */
private final int level;
/** Piece value. */
private final int value;
/** The graph element type. */
private SiteType type;
//-------------------------------------------------------------------------
/** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */
private boolean alreadyApplied = false;
/** The previous value. */
private int previousValue;
/** The previous site type. */
private SiteType previousType;
//-------------------------------------------------------------------------
/**
* @param type The graph element type.
* @param to The site.
* @param level The level.
* @param value The piece value.
*/
public ActionSetValue
(
final SiteType type,
final int to,
final int level,
final int value
)
{
this.to = to;
this.level = level;
this.value = value;
this.type = type;
}
/**
* Reconstructs an ActionSetValue object from a detailed String (generated using
* toDetailedString())
*
* @param detailedString
*/
public ActionSetValue(final String detailedString)
{
assert (detailedString.startsWith("[SetValue:"));
final String strType = Action.extractData(detailedString, "type");
type = (strType.isEmpty()) ? null : SiteType.valueOf(strType);
final String strTo = Action.extractData(detailedString, "to");
to = Integer.parseInt(strTo);
final String strLevel = Action.extractData(detailedString, "level");
level = (strLevel.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevel);
final String strValue = Action.extractData(detailedString, "value");
value = Integer.parseInt(strValue);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
if(to < 0)
return this;
type = (type == null) ? context.board().defaultSite() : type;
final int cid = to >= context.containerId().length ? 0 : context.containerId()[to];
final ContainerState cs = context.state().containerStates()[cid];
if (context.game().isStacking())
{
if (level != Constants.UNDEFINED)
{
final int stackSize = cs.sizeStack(to, type);
if (level < stackSize)
{
if(!alreadyApplied)
{
previousValue = cs.value(to, level, type);
previousType = type;
alreadyApplied = true;
}
final int what = cs.what(to, level, type);
final int who = cs.who(to, level, type);
final int rotation = cs.rotation(to, level, type);
final int state = cs.state(to, level, type);
cs.remove(context.state(), to, level);
cs.insert(context.state(), type, to, level, what, who, state, rotation, value, context.game());
}
}
else
{
if(!alreadyApplied)
{
previousValue = cs.value(to, type);
previousType = type;
alreadyApplied = true;
}
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, value,
type);
}
}
else
{
if(!alreadyApplied)
{
previousValue = cs.value(to, type);
previousType = type;
alreadyApplied = true;
}
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, value, type);
}
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
if(to < 0)
return this;
final int cid = to >= context.containerId().length ? 0 : context.containerId()[to];
final ContainerState cs = context.state().containerStates()[cid];
if (context.game().isStacking())
{
final int stackSize = cs.sizeStack(to, type);
if (level != Constants.UNDEFINED)
{
if (level < stackSize)
{
final int what = cs.what(to, level, type);
final int who = cs.who(to, level, type);
final int rotation = cs.rotation(to, level, type);
final int state = cs.state(to, level, type);
cs.remove(context.state(), to, level);
cs.insert(context.state(), previousType, to, level, what, who, state, rotation, previousValue, context.game());
}
}
else
{
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, previousValue,
previousType);
}
}
else
{
cs.setSite(context.state(), to, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, previousValue, previousType);
}
return this;
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetValue:");
if (type != null || (context != null && type != context.board().defaultSite()))
{
sb.append("type=" + type);
sb.append(",to=" + to);
}
else
sb.append("to=" + to);
if (level != Constants.UNDEFINED)
sb.append(",level=" + level);
sb.append(",value=" + value);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + to;
if (level != Constants.UNDEFINED)
result = prime * result + level;
result = prime * result + value;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetValue))
return false;
final ActionSetValue other = (ActionSetValue) obj;
return (to == other.to && level == other.level &&
value == other.value && type == other.type);
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "SetValue";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
final StringBuilder sb = new StringBuilder();
String newTo = to + "";
if (useCoords)
{
final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell)
? context.containerId()[to]
: 0;
if (cid == 0)
{
final SiteType realType = (type != null) ? type : context.board().defaultSite();
newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to)
.label();
}
}
if (type != null && !type.equals(context.board().defaultSite()))
sb.append(type + " " + newTo);
else
sb.append(newTo);
if (level != Constants.UNDEFINED)
sb.append("/" + level);
sb.append("=" + value);
return sb.toString();
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
final StringBuilder sb = new StringBuilder();
sb.append("(Value ");
String newTo = to + "";
if (useCoords)
{
final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell)
? context.containerId()[to]
: 0;
if (cid == 0)
{
final SiteType realType = (type != null) ? type : context.board().defaultSite();
newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to)
.label();
}
}
if (type != null && !type.equals(context.board().defaultSite()))
sb.append(type + " " + newTo);
else
sb.append(newTo);
if (level != Constants.UNDEFINED && context.game().isStacking())
sb.append("/" + level);
sb.append("=" + value);
sb.append(')');
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public SiteType fromType()
{
return type;
}
@Override
public SiteType toType()
{
return type;
}
@Override
public int from()
{
return to;
}
@Override
public int to()
{
return to;
}
@Override
public int value()
{
return value;
}
@Override
public int levelFrom()
{
return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level;
}
@Override
public int levelTo()
{
return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level;
}
@Override
public ActionType actionType()
{
return ActionType.SetValue;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Context context, final Moves movesLudeme)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.SetValue.id(), true);
return concepts;
}
}
| 9,540 | 23.093434 | 123 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionSetVar.java | package other.action.state;
import java.util.BitSet;
import game.rules.play.moves.Moves;
import main.Constants;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.concept.Concept;
import other.context.Context;
/**
* Sets the temporary value of the state.
*
* @author Eric.Piette
*/
public final class ActionSetVar extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The name of the var */
private final String name;
/** The new value. */
private final int value;
//-------------------------------------------------------------------------
/** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */
private boolean alreadyApplied = false;
/** The previous value. */
private int previousValue;
//-------------------------------------------------------------------------
/**
* @param name The name of the var.
* @param value The value.
*/
public ActionSetVar(final String name, final int value)
{
this.name = name;
this.value = value;
}
/**
* Reconstructs an ActionSetTemp object from a detailed String (generated using
* toDetailedString())
*
* @param detailedString
*/
public ActionSetVar(final String detailedString)
{
assert (detailedString.startsWith("[SetVar:"));
final String strName = Action.extractData(detailedString, "name");
name = strName;
final String strValue = Action.extractData(detailedString, "value");
value = Integer.parseInt(strValue);
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
if(!alreadyApplied)
{
previousValue = context.state().getValue(name);
alreadyApplied = true;
}
context.state().setValue(name, value);
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
if(previousValue == Constants.UNDEFINED)
context.state().removeKeyValue(name);
else
context.state().setValue(name, previousValue);
return this;
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[SetVar:");
sb.append("name=" + name);
sb.append(",value=" + value);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (decision ? 1231 : 1237);
result = prime * result + value;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionSetVar))
return false;
final ActionSetVar other = (ActionSetVar) obj;
return (decision == other.decision && value == other.value && name.equals(other.name));
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "SetVar";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
return name + "=" + value;
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
return "(" + name + "= " + value + ")";
}
@Override
public ActionType actionType()
{
return ActionType.SetVar;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Context context, final Moves movesLudeme)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.SetVar.id(), true);
return concepts;
}
}
| 4,065 | 22.367816 | 123 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionStoreStateInContext.java | package other.action.state;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.context.Context;
/**
* Stores the current state of the game.
*
* @author Eric.Piette
*/
public class ActionStoreStateInContext extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */
private boolean alreadyApplied = false;
/** The previous value. */
private long previousValue;
//-------------------------------------------------------------------------
/**
*
*/
public ActionStoreStateInContext()
{
// Do nothing
}
/**
* Reconstructs an ActionState object from a detailed String (generated using
* toDetailedString())
*
* @param detailedString
*/
public ActionStoreStateInContext(final String detailedString)
{
assert (detailedString.startsWith("[StoreStateInContext:"));
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
if(!alreadyApplied)
{
previousValue = context.state().storedState();
alreadyApplied = true;
}
context.state().storeCurrentState(context.state());
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
context.state().restoreCurrentState(previousValue);
return this;
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[StoreStateInContext:");
if (decision)
sb.append("decision=" + decision);
sb.append(']');
return sb.toString();
}
@Override
public int hashCode()
{
final int result = 1;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionStoreStateInContext))
return false;
return true;
}
@Override
public ActionType actionType()
{
return ActionType.StoreState;
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "StoreStateInContext";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
return "Store State";
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
return "(Store State)";
}
}
| 2,875 | 20.462687 | 123 | java |
Ludii | Ludii-master/Core/src/other/action/state/ActionTrigger.java | package other.action.state;
import java.util.BitSet;
import game.rules.play.moves.Moves;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.concept.Concept;
import other.context.Context;
/**
* Triggers an event for a player.
*
* @author Eric.Piette
*/
public final class ActionTrigger extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Index of the player. */
private final int player;
/** The event to trigger. */
private final String event;
//-------------------------------------------------------------------------
/**
* @param player The player related to the event.
* @param event The event to trigger.
*/
public ActionTrigger
(
final String event,
final int player
)
{
this.player = player;
this.event = event;
}
/**
* Reconstructs a ActionTrigger object from a detailed String (generated using
* toDetailedString())
*
* @param detailedString
*/
public ActionTrigger(final String detailedString)
{
assert (detailedString.startsWith("[Trigger:"));
final String strPlayer = Action.extractData(detailedString, "player");
player = Integer.parseInt(strPlayer);
final String strEvent = Action.extractData(detailedString, "event");
event = strEvent;
final String strDecision = Action.extractData(detailedString, "decision");
decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision);
}
//-------------------------------------------------------------------------
@Override
public Action apply(final Context context, final boolean store)
{
// Event to add.
context.state().triggers(player, true);
return this;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
context.state().triggers(player, false);
return this;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (decision ? 1231 : 1237);
result = prime * result + player;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof ActionTrigger))
return false;
final ActionTrigger other = (ActionTrigger) obj;
return (decision == other.decision &&
player == other.player && event.equals(other.event));
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[Trigger:");
sb.append("event=" + event);
sb.append(",player=" + player);
if (decision)
sb.append(",decision=" + decision);
sb.append(']');
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String getDescription()
{
return "Trigger";
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
return "Trigger " + event + " P" + player;
}
@Override
public String toMoveFormat(final Context context, final boolean useCoords)
{
return "(Trigger " + event + " P" + player + ")";
}
//-------------------------------------------------------------------------
@Override
public int who()
{
return player;
}
@Override
public int what()
{
return player;
}
@Override
public ActionType actionType()
{
return ActionType.Trigger;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Context context, final Moves movesLudeme)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Trigger.id(), true);
return concepts;
}
}
| 3,920 | 21.02809 | 81 | java |
Ludii | Ludii-master/Core/src/other/concept/Concept.java | package other.concept;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Map;
import compiler.Compiler;
import game.Game;
import main.grammar.Description;
/**
* Defines known concepts used in a game.
*
* Remarks: The documentation on top of each concept explains how the concept is
* computed if that's leaf. If that's not a leaf, the concept is true if any
* child is true.
*
* Remarks: The next id in case of a new concept is the id 810.
*
* @author Eric.Piette
*/
public enum Concept
{
//-------------------------------------------------------------------------
// Properties
//-------------------------------------------------------------------------
/** */
Properties
(
"1",
1,
"General properties of the game.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
null
),
/** */
Format
(
"1.1",
2,
"Format of the game.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.Properties
),
/** */
Time
(
"1.1.1",
3,
"Time model.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.Format
),
/** True if the mode is not realtime (which is all games which are not simulation). */
Discrete
(
"1.1.1.1",
4,
"Players move at discrete intervals.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.Time
),
/** True if the mode is realtime (which is only the simulation for now). */
Realtime
(
"1.1.1.2",
5,
"Moves not discrete.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.Time
),
/** */
Turns
(
"1.1.2",
6,
"Player turns.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.Format
),
/** True if the mode is Alternating. */
Alternating
(
"1.1.2.1",
7,
"Players take turns moving.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.Turns
),
/** True if the mode is Simultaneous. */
Simultaneous
(
"1.1.2.2",
8,
"Players can move at the same time.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.Turns
),
/** All games involving Dice (to throw), cards or dominoes. */
Stochastic
(
"1.1.3",
9,
"Game involves chance elements.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Format
),
/** Use hidden information. */
HiddenInformation
(
"1.1.4",
10,
"Game involves hidden information.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Format
),
/** All games with subgames. */
Match
(
"1.1.5",
11,
"Match game.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Format
),
/** */
Asymmetric
(
"1.1.6",
12,
"Asymmetry in rules and/or forces.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.Format
),
/** */
AsymmetricRules
(
"1.1.6.1",
13,
"Players have different rules.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Asymmetric
),
/** TO DO */
AsymmetricPlayRules
(
"1.1.6.1.1",
14,
"Players have different play rules.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AsymmetricRules
),
/** TO DO */
AsymmetricEndRules
(
"1.1.6.1.2",
15,
"Players have different end rules.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AsymmetricRules
),
/** */
AsymmetricForces
(
"1.1.6.2",
16,
"Players have different forces.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Asymmetric
),
/** TO DO. */
AsymmetricSetup
(
"1.1.6.2.1",
17,
"Different starting positions for each player.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AsymmetricForces
),
/** True if any piece type is owned by a player and not all the others. */
AsymmetricPiecesType
(
"1.1.6.2.2",
18,
"Different piece types owned by each player.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AsymmetricForces
),
/** */
Players
(
"1.2",
19,
"Players of the game.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Properties
),
/** Number of players. */
NumPlayers
(
"1.2.1",
20,
"Number of players.",
ConceptType.Properties,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Players
),
/** The mode is simulation. */
Simulation
(
"1.2.1.1",
21,
"No players (environment runs the game).",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.NumPlayers
),
/** Number of players = 1. */
Solitaire
(
"1.2.1.2",
22,
"Single player.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.NumPlayers
),
/** Number of players = 2. */
TwoPlayer
(
"1.2.1.3",
23,
"Two players.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.NumPlayers
),
/** Number of players > 2. */
Multiplayer
(
"1.2.1.4",
24,
"More than two players.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.NumPlayers
),
/** Players are using directions in their definitions. */
PlayersWithDirections
(
"1.2.2",
797,
"Players are using directions.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Players
),
/** */
Cooperation
(
"1.3",
25,
"Players have to cooperate.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Properties
),
/** A (set Team ...) ludeme is used. */
Team
(
"1.3.1",
26,
"Game involves teams of players.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Cooperation
),
/** A (set Team ...) ludeme is used in the play rules. */
Coalition
(
"1.3.2",
27,
"Players may form coalitions.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Cooperation
),
/** */
Puzzle
(
"1.4",
28,
"Type of puzzle.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Properties
),
/** True if any ludeme used only for deduction puzzle is used. */
DeductionPuzzle
(
"1.4.1",
29,
"Solution can be deduced.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Puzzle
),
/** All the 1 player game which are not deduction puzzles. */
PlanningPuzzle
(
"1.4.2",
30,
"Solution is reached in moving pieces.",
ConceptType.Properties,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[]{ ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Puzzle
),
//-------------------------------------------------------------------------
// Equipment
//-------------------------------------------------------------------------
/** */
Equipment
(
"2",
31,
"Equipment for playing the game.",
ConceptType.Equipment,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
null
),
/** */
Container
(
"2.1",
32,
"Containers that hold components.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Equipment
),
/** */
Board
(
"2.1.1",
33,
"Board shared by player for playing the game.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Container
),
/** */
Shape
(
"2.1.1.1",
34,
"The shape of the board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Board
),
/** True if a sub ludeme correspond to a square shape. */
SquareShape
(
"2.1.1.1.1",
35,
"Square shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a hexagonal shape. */
HexShape
(
"2.1.1.1.2",
36,
"Hexagonal shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a triangle shape. */
TriangleShape
(
"2.1.1.1.3",
37,
"Triangle shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a diamond shape. */
DiamondShape
(
"2.1.1.1.4",
38,
"Diamond shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a rectangle shape. */
RectangleShape
(
"2.1.1.1.5",
39,
"Rectangle shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a spiral shape. */
SpiralShape
(
"2.1.1.1.6",
40,
"Spirale shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a circle shape. */
CircleShape
(
"2.1.1.1.7",
41,
"Circle shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a prism shape. */
PrismShape
(
"2.1.1.1.8",
42,
"Prism shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a star shape. */
StarShape(
"2.1.1.1.9",
43,
"Star shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a parallelogram shape. */
ParallelogramShape(
"2.1.1.1.10",
44,
"Parallelogram shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a square shape with pyramidal at true. */
SquarePyramidalShape(
"2.1.1.1.11",
45,
"Square Pyramidal shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** True if a sub ludeme correspond to a rectangle shape with pyramidal at true. */
RectanglePyramidalShape
(
"2.1.1.1.12",
46,
"Rectangle Pyramidal shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** Board shape is based on a regular polygon. */
RegularShape
(
"2.1.1.1.13",
47,
"Regular shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** Board shape is based on a general polygon. */
PolygonShape
(
"2.1.1.1.14",
48,
"General polygonal shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** Board shape is concentric set of rings like a target. */
TargetShape
(
"2.1.1.1.15",
49,
"Target shape.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction },
true,
Concept.Shape
),
/** */
Tiling
(
"2.1.1.2",
50,
"The tiling of the board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Board
),
/** True if any ludeme uses a square tiling. */
SquareTiling
(
"2.1.1.2.1",
51,
"Square tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses a hexagonal tiling. */
HexTiling
(
"2.1.1.2.2",
52,
"Hexagonal tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses a triangle tiling. */
TriangleTiling
(
"2.1.1.2.3",
53,
"Triangle tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses a brick tiling. */
BrickTiling
(
"2.1.1.2.4",
54,
"Brick tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if a Semi regular tiling is used. */
SemiRegularTiling
(
"2.1.1.2.5",
55,
"Semi regular tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses a celtic tiling. */
CelticTiling
(
"2.1.1.2.6",
56,
"Celtic tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses a morris tiling. */
MorrisTiling
(
"2.1.1.2.7",
57,
"Morris tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses a quadHex tiling. */
QuadHexTiling
(
"2.1.1.2.8",
58,
"QuadHex tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses a circle tiling. */
CircleTiling
(
"2.1.1.2.9",
59,
"Circle tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses a concentric tiling. */
ConcentricTiling
(
"2.1.1.2.10",
60,
"Concentric tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses a spiral tiling. */
SpiralTiling
(
"2.1.1.2.11",
61,
"Spiral tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** True if any ludeme uses an alquerque tiling. */
AlquerqueTiling
(
"2.1.1.2.12",
62,
"Alquerque tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Tiling
),
/** (mancalaBoard ...) is used. */
MancalaBoard
(
"2.1.1.3",
63,
"Mancala board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Board
),
/** (mancalaBoard ...) is used with stores not None. */
MancalaStores
(
"2.1.1.3.1",
64,
"Mancala board with stores.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MancalaBoard
),
/** (mancalaBoard ...) is used using 2 rows. */
MancalaTwoRows
(
"2.1.1.3.2",
65,
"Mancala board with 2 rows.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MancalaBoard
),
/** (mancalaBoard ...) is used using 3 rows. */
MancalaThreeRows
(
"2.1.1.3.3",
66,
"Mancala board with 3 rows.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MancalaBoard
),
/** (mancalaBoard ...) is used using 4 rows. */
MancalaFourRows
(
"2.1.1.3.4",
67,
"Mancala board with 4 rows.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MancalaBoard
),
/** (mancalaBoard ...) is used using 6 rows. */
MancalaSixRows
(
"2.1.1.3.5",
68,
"Mancala board with 6 rows.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MancalaBoard
),
/** (mancalaBoard ...) is used using with a circular tiling */
MancalaCircular
(
"2.1.1.3.6",
69,
"Mancala board with circular tiling.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MancalaBoard
),
/** "AlquerqueBoard" ludemeplex (or a similar one) is used. */
AlquerqueBoard
(
"2.1.1.4",
780,
"Alquerque board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Board
),
/** "AlquerqueBoardWithBottomTriangle" ludemeplex is used. */
AlquerqueBoardWithOneTriangle
(
"2.1.1.4.1",
781,
"Alquerque board with one triangle extension.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AlquerqueBoard
),
/** "AlquerqueBoardWithBottomAndTopTriangles" ludemeplex is used. */
AlquerqueBoardWithTwoTriangles
(
"2.1.1.4.2",
782,
"Alquerque board with two triangle extensions.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AlquerqueBoard
),
/** "AlquerqueBoardWithFourTriangles" ludemeplex is used. */
AlquerqueBoardWithFourTriangles
(
"2.1.1.4.3",
783,
"Alquerque board with four triangle extensions.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AlquerqueBoard
),
/** "AlquerqueBoardWithEightTriangles" ludemeplex is used. */
AlquerqueBoardWithEightTriangles
(
"2.1.1.4.4",
784,
"Alquerque board with eight triangle extensions.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AlquerqueBoard
),
/** "ThreeMenMorrisBoard" ludemeplex is used. */
ThreeMensMorrisBoard
(
"2.1.1.5",
786,
"Three Men's Morris Board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Board
),
/** "ThreeMenMorrisBoardWithTwoTriangles" ludemeplex is used. */
ThreeMensMorrisBoardWithTwoTriangles
(
"2.1.1.5.1",
787,
"Three Men's Morris Board with two triangle extensions.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ThreeMensMorrisBoard
),
/** "NineMensMorrisBoard" ludemeplex is used. */
NineMensMorrisBoard
(
"2.1.1.6",
785,
"Nine Men's Morris board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Board
),
/** "StarBoard" ludemeplex is used. */
StarBoard
(
"2.1.1.7",
788,
"Star board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Board
),
/** "CrossBoard" ludemeplex is used. */
CrossBoard
(
"2.1.1.8",
789,
"Cross board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Board
),
/** "KintsBoard" ludemeplex is used. */
KintsBoard
(
"2.1.1.9",
790,
"Kints board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Board
),
/** "PachisiBoard" ludemeplex is used. */
PachisiBoard
(
"2.1.1.10",
791,
"Pachisi board.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Board
),
/** "FortyStonesWithFourGapsBoard" ludemeplex is used. */
FortyStonesWithFourGapsBoard
(
"2.1.1.11",
792,
"Forty Stones in a circle with four gaps after each 10 stones.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Board
),
/** The track list of the board is not empty. */
Track
(
"2.1.1.12",
70,
"The board has a track.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Board
),
/** One track uses a loop. */
TrackLoop
(
"2.1.1.12.1",
71,
"A track is a loop.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Track
),
/** One track uses a loop. */
TrackOwned
(
"2.1.1.12.2",
72,
"A track is owned.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Track
),
/** The ludeme (hints ...) is used. */
Hints
(
"2.1.1.13",
73,
"The board has some hints.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** The list of regions is not empty. */
Region
(
"2.1.1.14",
74,
"The board has regions.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Board
),
/** The ludeme (boardless ...) is used. */
Boardless
(
"2.1.1.15",
75,
"Game is played on an implied grid.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Board
),
/** */
PlayableSites
(
"2.1.1.16",
76,
"Playable sites.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Board
),
/** SiteType = Vertex in at least a ludeme. */
Vertex
(
"2.1.1.16.1",
77,
"Use Vertices.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI, },
true,
Concept.PlayableSites
),
/** SiteType = Cell in at least a ludeme. */
Cell
(
"2.1.1.16.2",
78,
"Use cells.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI, },
true,
Concept.PlayableSites
),
/** SiteType = Edge in at least a ludeme. */
Edge
(
"2.1.1.16.3",
79,
"Use edges.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI, },
true,
Concept.PlayableSites
),
/** Number of playables sites on the board. */
NumPlayableSitesOnBoard
(
"2.1.1.16.4",
80,
"Number of playables sites on the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PlayableSites
),
/** Number of columns of the board. */
NumColumns
(
"2.1.1.17",
81,
"Number of columns of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of rows of the board. */
NumRows
(
"2.1.1.18",
82,
"Number of rows of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[]{ ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of corners of the board. */
NumCorners
(
"2.1.1.19",
83,
"Number of corners of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Average number of directions of each playable site on the board. */
NumDirections
(
"2.1.1.20",
84,
"Average number of directions of each playable site on the board.",
ConceptType.Container,
ConceptDataType.DoubleData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/**
* Average number of orthogonal directions of each playable site on the board.
*/
NumOrthogonalDirections
(
"2.1.1.21",
85,
"Average number of orthogonal directions of each playable site on the board.",
ConceptType.Container,
ConceptDataType.DoubleData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Average number of diagonal directions of each playable site on the board. */
NumDiagonalDirections
(
"2.1.1.22",
86,
"Average number of diagonal directions of each playable site on the board.",
ConceptType.Container,
ConceptDataType.DoubleData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Average number of adjacent directions of each playable site on the board. */
NumAdjacentDirections
(
"2.1.1.23",
87,
"Average number of adjacent directions of each playable site on the board.",
ConceptType.Container,
ConceptDataType.DoubleData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Average number of off diagonal directions of each playable site on the board. */
NumOffDiagonalDirections
(
"2.1.1.24",
88,
"Average number of off diagonal directions of each playable site on the board.",
ConceptType.Container,
ConceptDataType.DoubleData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of outer sites of the board. */
NumOuterSites
(
"2.1.1.25",
89,
"Number of outer sites of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of inner sites of the board. */
NumInnerSites
(
"2.1.1.26",
90,
"Number of inner sites of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of layers of the board. */
NumLayers
(
"2.1.1.27",
91,
"Number of layers of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of edges of the board. */
NumEdges
(
"2.1.1.28",
92,
"Number of edges of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of cells of the board. */
NumCells
(
"2.1.1.29",
93,
"Number of cells of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of vertices of the board. */
NumVertices
(
"2.1.1.30",
94,
"Number of vertices of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of perimeter sites of the board. */
NumPerimeterSites
(
"2.1.1.31",
95,
"Number of perimeter sites of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of top sites of the board. */
NumTopSites
(
"2.1.1.32",
96,
"Number of top sites of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of bottom sites of the board. */
NumBottomSites
(
"2.1.1.33",
97,
"Number of bottom sites of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of right sites of the board. */
NumRightSites
(
"2.1.1.34",
98,
"Number of right sites of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of left sites of the board. */
NumLeftSites
(
"2.1.1.35",
99,
"Number of left sites of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of centre sites of the board. */
NumCentreSites
(
"2.1.1.36",
100,
"Number of centre sites of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of convex corners of the board. */
NumConvexCorners
(
"2.1.1.37",
101,
"Number of convex corners of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of concave corners of the board. */
NumConcaveCorners
(
"2.1.1.38",
102,
"Number of concave corners of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** Number of phases of the board. */
NumPhasesBoard
(
"2.1.1.39",
103,
"Number of phases of the board.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Board
),
/** The ludeme (hand ...) is used. */
Hand
(
"2.1.2",
104,
"Player hands for storing own pieces.",
ConceptType.Container,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Container
),
/** Number of containers. */
NumContainers
(
"2.1.3",
105,
"Number of containers.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Container
),
/** Sum of all the playable sites across all the containers */
NumPlayableSites
(
"2.1.4",
106,
"Number of playables sites in total.",
ConceptType.Container,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Container
),
/** */
Component
(
"2.2",
107,
"Components manipulated by the players.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Equipment
),
/** The ludeme (piece ...) is used. */
Piece
(
"2.2.1",
108,
"Game is played with pieces.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Component
),
/** A ludeme (set Value ...) is used. */
PieceValue
(
"2.2.2",
109,
"Pieces have value.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Component
),
/** A rotation state is set */
PieceRotation
(
"2.2.3",
110,
"Pieces have rotations.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Component
),
/** A direction is not null in at least a piece. */
PieceDirection
(
"2.2.4",
111,
"Pieces have forward direction.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Component
),
/** A die is included in the components. */
Dice
(
"2.2.5",
112,
"Game is played with dice.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Component
),
/** A D2 is included in the components. */
DiceD2
(
"2.2.5.1",
793,
"Game is played with D2 dice.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Dice
),
/** A D3 is included in the components. */
DiceD3
(
"2.2.5.2",
794,
"Game is played with D3 dice.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Dice
),
/** A D4 is included in the components. */
DiceD4
(
"2.2.5.3",
795,
"Game is played with D4 dice.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Dice
),
/** A D6 is included in the components. */
DiceD6
(
"2.2.5.4",
796,
"Game is played with D6 dice.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Dice
),
/** Use biased dice. */
BiasedDice
(
"2.2.5.5",
113,
"Game is played with biased dice.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Dice
),
/** A card is included in the components. */
Card
(
"2.2.6",
114,
"Game is played with cards.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Component
),
/** A domino is included in the components. */
Domino
(
"2.2.7",
115,
"Game is played with dominoes.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Component
),
/** A large piece is included in the components. */
LargePiece
(
"2.2.8",
116,
"Game is played with large pieces.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Component
),
/** Use tiles. */
Tile
(
"2.2.9",
117,
"Game is played with tiles.",
ConceptType.Component,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Component
),
/** Number of component types. */
NumComponentsType
(
"2.2.10",
118,
"Number of component types.",
ConceptType.Component,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Component
),
/** Average number of component types per player. */
NumComponentsTypePerPlayer
(
"2.2.11",
119,
"Average number of component types per player.",
ConceptType.Component,
ConceptDataType.DoubleData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Component
),
/** Number of dice. */
NumDice
(
"2.2.12",
120,
"Number of dice.",
ConceptType.Component,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Component
),
//-------------------------------------------------------------------------
// Rules
//-------------------------------------------------------------------------
/** */
Rules
(
"3",
121,
"Rules of the game.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
null
),
//-------------------------------------------------------------------------
// MetaRules
//-------------------------------------------------------------------------
/** */
Meta
(
"3.1",
122,
"Global metarules that override all other rules.",
ConceptType.Meta,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Rules
),
/** */
OpeningContract
(
"3.1.1",
123,
"Game involves an opening round equaliser.",
ConceptType.Meta,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Meta
),
/** (swap) metarule is used. */
SwapOption
(
"3.1.1.1",
124,
"Second player may swap colours.",
ConceptType.Meta,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.OpeningContract
),
/** */
Repetition
(
"3.1.2",
125,
"Game has repetition checks.",
ConceptType.Meta,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Meta
),
/** (no Repeat PositionalInTurn) is used. */
TurnKo
(
"3.1.2.1",
126,
"No repeated piece positions within a single turn.",
ConceptType.Meta,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Repetition
),
/** (no Repeat SituationalInTurn) is used. */
SituationalTurnKo
(
"3.1.2.2",
127,
"No repeated states withing a single turn.",
ConceptType.Meta,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Repetition
),
/** (no Repeat Positional) is used. */
PositionalSuperko
(
"3.1.2.3",
128,
"No repeated piece positions.",
ConceptType.Meta,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Repetition
),
/** (no Repeat Situational) is used. */
SituationalSuperko
(
"3.1.2.4",
129,
"No repeated states.",
ConceptType.Meta,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Repetition
),
/** */
AutoMove
(
"3.1.3",
130,
"Apply all legal moves related to one single site.",
ConceptType.Meta,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Meta
),
//-------------------------------------------------------------------------
// Start Rules
//-------------------------------------------------------------------------
/** */
Start
(
"3.2",
131,
"Start rules.",
ConceptType.Start,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Rules
),
/**
* Places initially some pieces on the board.
*/
PiecesPlacedOnBoard
(
"3.2.1",
132,
"Places initially some pieces on the board.",
ConceptType.Start,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/**
* Places initially some pieces (different of shared dice) outside of the board.
*/
PiecesPlacedOutsideBoard
(
"3.2.2",
133,
"Places initially some pieces (different of shared dice) outside of the board.",
ConceptType.Start,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Places initially randomly some pieces. */
InitialRandomPlacement
(
"3.2.3",
134,
"Places initially randomly some pieces.",
ConceptType.Start,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Sets initial score. */
InitialScore
(
"3.2.4",
135,
"Sets initial score.",
ConceptType.Start,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Sets initial amount. */
InitialAmount
(
"3.2.5",
136,
"Sets initial amount.",
ConceptType.Start,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Sets initial pot. */
InitialPot
(
"3.2.6",
137,
"Sets initial pot.",
ConceptType.Start,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Sets initially some costs on graph elements. */
InitialCost
(
"3.2.7",
138,
"Sets initially some costs on graph elements.",
ConceptType.Start,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Compute the number of pieces on the board at the start. */
NumStartComponentsBoard
(
"3.2.8",
139,
"Number of components on board at start.",
ConceptType.Start,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Compute the number of pieces in the player hands at the start. */
NumStartComponentsHand
(
"3.2.9",
140,
"Number of components in player hands at start.",
ConceptType.Start,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Compute the number of pieces at the start. */
NumStartComponents
(
"3.2.10",
141,
"Number of components at start.",
ConceptType.Start,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[]{ ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Compute the average of number of pieces at the start per player. */
NumStartComponentsBoardPerPlayer
(
"3.2.11",
800,
"Average number of components on board at start per player.",
ConceptType.Start,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[]{ ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Compute the average of number of pieces in the players hand at the start per player. */
NumStartComponentsHandPerPlayer
(
"3.2.12",
801,
"Average number of components in player hands at start per player.",
ConceptType.Start,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[]{ ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
/** Compute the average of number of pieces on board at the start per player. */
NumStartComponentsPerPlayer
(
"3.2.13",
802,
"Average number of components at start per player.",
ConceptType.Start,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[]{ ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Start
),
//-------------------------------------------------------------------------
// Play Rules
//-------------------------------------------------------------------------
/** */
Play
(
"3.3",
142,
"Rules of general play.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Rules
),
/** */
Moves
(
"3.3.1",
143,
"Moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Play
),
/** */
MovesDecision
(
"3.3.1.1",
144,
"Moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Moves
),
/** */
NoSiteMoves
(
"3.3.1.1.1",
145,
"Moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesDecision
),
/** Decide to bet. */
BetDecision
(
"3.3.1.1.1.1",
146,
"Decide to bet.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.NoSiteMoves
),
/** Frequency of BetDecision. */
BetDecisionFrequency
(
"3.3.1.1.1.1.1",
147,
"Frequency of \"Bet Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.BetDecision
),
/** Decide to vote. */
VoteDecision
(
"3.3.1.1.1.2",
148,
"Decide to vote.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.NoSiteMoves
),
/** Frequency of VoteDecision. */
VoteDecisionFrequency
(
"3.3.1.1.1.2.1",
149,
"Frequency of \"Vote Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.VoteDecision
),
/** Decide to swap players. */
SwapPlayersDecision
(
"3.3.1.1.1.3",
150,
"Decide to swap players.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.NoSiteMoves
),
/** Frequency of SwapPiecesDecision. */
SwapPlayersDecisionFrequency
(
"3.3.1.1.1.3.1",
151,
"Frequency of \"Swap Players Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SwapPlayersDecision
),
/** (move Set TrumpSuit ..). */
ChooseTrumpSuitDecision
(
"3.3.1.1.1.4",
152,
"Choose the trump suit.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.NoSiteMoves
),
/** Frequency of ChooseTrumpSuit. */
ChooseTrumpSuitDecisionFrequency
(
"3.3.1.1.1.4.1",
153,
"Frequency of \"Choose Trump Suit Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ChooseTrumpSuitDecision
),
/** (move Pass ...) is used. */
PassDecision
(
"3.3.1.1.1.5",
154,
"Decide to pass a turn.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.NoSiteMoves
),
/** Frequency of PassDecision. */
PassDecisionFrequency
(
"3.3.1.1.1.5.1",
155,
"Frequency of \"Pass Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PassDecision
),
/** Decide to propose. */
ProposeDecision
(
"3.3.1.1.1.6",
156,
"Decide to propose.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.NoSiteMoves
),
/** Frequency of ProposeDecision. */
ProposeDecisionFrequency
(
"3.3.1.1.1.6.1",
157,
"Frequency of \"Propose Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ProposeDecision
),
/** */
SingleSiteMoves
(
"3.3.1.1.2",
158,
"Moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesDecision
),
/** (move Add ...) is used. */
AddDecision
(
"3.3.1.1.2.1",
159,
"Decide to add pieces.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SingleSiteMoves
),
/** Frequency of AddDecision. */
AddDecisionFrequency
(
"3.3.1.1.2.1.1",
160,
"Frequency of \"Add Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AddDecision
),
/** (move Promote ...) is used. */
PromotionDecision
(
"3.3.1.1.2.2",
161,
"Promote move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SingleSiteMoves
),
/** Frequency of Promotion. */
PromotionDecisionFrequency
(
"3.3.1.1.2.2.1",
162,
"Frequency of \"Promotion Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PromotionDecision
),
/** (move Remove ...) is used. */
RemoveDecision
(
"3.3.1.1.2.3",
163,
"Decide to remove pieces.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SingleSiteMoves
),
/** Frequency of RemoveDecision. */
RemoveDecisionFrequency
(
"3.3.1.1.2.3.1",
164,
"Frequency of \"Remove Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.RemoveDecision
),
/** (set Direction ...) is used. */
RotationDecision
(
"3.3.1.1.2.4",
165,
"Rotation move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SingleSiteMoves
),
/** Frequency of Rotation Decision. */
RotationDecisionFrequency
(
"3.3.1.1.2.4.1",
166,
"Frequency of \"Rotation Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.RotationDecision
),
/** */
TwoSitesMoves
(
"3.3.1.1.3",
167,
"Moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesDecision
),
/** (Move Step ...) is used. */
StepDecision
(
"3.3.1.1.3.1",
168,
"Decide to step.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.TwoSitesMoves
),
/** Frequency of StepDecision. */
StepDecisionFrequency
(
"3.3.1.1.3.1.1",
169,
"Frequency of \"Step Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.StepDecision
),
/** (is Empty ...) condition on (to...) of a step move. */
StepDecisionToEmpty
(
"3.3.1.1.3.1.2",
170,
"Decide to step to an empty site.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.StepDecision
),
/** Frequency of StepToEmpty. */
StepDecisionToEmptyFrequency
(
"3.3.1.1.3.1.2.1",
171,
"Frequency of \"Step Decision To Empty\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.StepDecisionToEmpty
),
/** (is Friend ...) condition on (to...) of a step move. */
StepDecisionToFriend
(
"3.3.1.1.3.1.3",
172,
"Decide to step to a friend piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.StepDecision
),
/** Frequency of StepToEmpty. */
StepDecisionToFriendFrequency
(
"3.3.1.1.3.1.3.1",
173,
"Frequency of \"Step Decision To Friend\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.StepDecisionToFriend
),
/** (is Enemy ...) condition on (to...) of a step move. */
StepDecisionToEnemy
(
"3.3.1.1.3.1.4",
174,
"Decide to step to an enemy piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.StepDecision
),
/** Frequency of StepToEnemy. */
StepDecisionToEnemyFrequency
(
"3.3.1.1.3.1.4.1",
175,
"Frequency of \"Step Decision To Enemy\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.StepDecisionToEnemy
),
/** (move Slide ...) is used */
SlideDecision
(
"3.3.1.1.3.2",
176,
"Decide to slide.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.TwoSitesMoves
),
/** Frequency of StepToEnemy. */
SlideDecisionFrequency
(
"3.3.1.1.3.2.1",
177,
"Frequency of \"Slide Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SlideDecision
),
/** (move Slide ...) is used to move to empty sites. */
SlideDecisionToEmpty
(
"3.3.1.1.3.2.2",
178,
"Slide move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SlideDecision
),
/** Frequency of SlideToEmpty. */
SlideDecisionToEmptyFrequency
(
"3.3.1.1.3.2.2.1",
179,
"Frequency of \"Slide Decision To Empty\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SlideDecisionToEmpty
),
/**(move Slide ...) is used to move to enemy sites. */
SlideDecisionToEnemy
(
"3.3.1.1.3.2.3",
180,
"Slide move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SlideDecision
),
/** Frequency of SlideToEnemy. */
SlideDecisionToEnemyFrequency
(
"3.3.1.1.3.2.3.1",
181,
"Frequency of \"Slide Decision To Enemy\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SlideDecisionToEnemy
),
/**(move Slide ...) is used to move to friend sites. */
SlideDecisionToFriend
(
"3.3.1.1.3.2.4",
182,
"Slide move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SlideDecision
),
/** Frequency of SlideToFriend. */
SlideDecisionToFriendFrequency
(
"3.3.1.1.3.2.4.1",
183,
"Frequency of \"Slide Decision To Friend\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SlideDecisionToFriend
),
/** (move Leap ...) is used. */
LeapDecision
(
"3.3.1.1.3.3",
184,
"Decide to leap.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.TwoSitesMoves
),
/** Frequency of LeapDecision. */
LeapDecisionFrequency
(
"3.3.1.1.3.3.1",
185,
"Frequency of \"Leap Decision Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LeapDecision
),
/** (is Empty ...) condition on (to...) of a leap move. */
LeapDecisionToEmpty
(
"3.3.1.1.3.3.2",
186,
"Decide to leap to an empty site.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.LeapDecision
),
/** Frequency of LeapToEmpty. */
LeapDecisionToEmptyFrequency
(
"3.3.1.1.3.3.2.1",
187,
"Frequency of \"Leap Decision To Empty\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LeapDecisionToEmpty
),
/** (is Friend ...) condition on (to...) of a leap move. */
LeapDecisionToFriend
(
"3.3.1.1.3.3.3",
188,
"Decide to leap to a friend piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.LeapDecision
),
/** Frequency of LeapToFriend. */
LeapDecisionToFriendFrequency
(
"3.3.1.1.3.3.3.1",
189,
"Frequency of \"Leap Decision To Friend\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LeapDecisionToFriend
),
/** (is Enemy ...) condition on (to...) of a leap move. */
LeapDecisionToEnemy
(
"3.3.1.1.3.3.4",
190,
"Decide to leap to an enemy piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.LeapDecision
),
/** Frequency of LeapToEnemy. */
LeapDecisionToEnemyFrequency
(
"3.3.1.1.3.3.4.1",
191,
"Frequency of \"Leap Decision To Enemy\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LeapDecisionToEnemy
),
/** True if a (move Hop ...) is used. */
HopDecision
(
"3.3.1.1.3.4",
192,
"Decide to hop.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.TwoSitesMoves
),
/** Frequency of HopDecision. */
HopDecisionFrequency
(
"3.3.1.1.3.4.1",
193,
"Frequency of \"Hop Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopDecision
),
/** True if min range is greater than 1 in any hop decision move. */
HopDecisionMoreThanOne
(
"3.3.1.1.3.4.2",
194,
"Hop more than one site.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.HopDecision
),
/** Frequency of HopMoreThanOne. */
HopDecisionMoreThanOneFrequency
(
"3.3.1.1.3.4.2.1",
195,
"Frequency of \"Hop Decision More Than One\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopDecisionMoreThanOne
),
/** Hop move with (is Enemy ...) condition in the between and (is Empty ...) in the to. */
HopDecisionEnemyToEmpty
(
"3.3.1.1.3.4.3",
196,
"Hop an enemy to an empty site.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.HopDecision
),
/** Frequency of HopDecisionEnemyToEmpty. */
HopDecisionEnemyToEmptyFrequency
(
"3.3.1.1.3.4.3.1",
197,
"Frequency of \"Hop Decision Enemy To Empty\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopDecisionEnemyToEmpty
),
/** Decide to hop a friend piece to an empty site. */
HopDecisionFriendToEmpty
(
"3.3.1.1.3.4.4",
198,
"Hop a friend to an empty site.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.HopDecision
),
/** Frequency of HopDecisionFriendToEmpty. */
HopDecisionFriendToEmptyFrequency
(
"3.3.1.1.3.4.4.1",
199,
"Frequency of \"Hop DecisionFriend To Empty\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopDecisionFriendToEmpty
),
/** Decide to hop an enemy piece to a friend piece. */
HopDecisionEnemyToFriend
(
"3.3.1.1.3.4.5",
200,
"Hop an enemy to a friend piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.HopDecision
),
/** Frequency of HopDecisionEnemyToFriend. */
HopDecisionEnemyToFriendFrequency
(
"3.3.1.1.3.4.5.1",
201,
"Frequency of \"Hop Decision Enemy To Friend\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopDecisionEnemyToFriend
),
/** Decide to hop a friend piece to a friend piece. */
HopDecisionFriendToFriend
(
"3.3.1.1.3.4.6",
202,
"Hop a friend to a friend piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[]{ ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.HopDecision
),
/** Frequency of HopDecisionFriendToFriend. */
HopDecisionFriendToFriendFrequency
(
"3.3.1.1.3.4.6.1",
203,
"Frequency of \"Hop Decision Friend To Friend\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopDecisionFriendToFriend
),
/** Decide to hop an enemy piece to an enemy piece. */
HopDecisionEnemyToEnemy
(
"3.3.1.1.3.4.7",
204,
"Hop an enemy to a enemy piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.HopDecision
),
/** Frequency of HopDecisionEnemyToEnemy. */
HopDecisionEnemyToEnemyFrequency
(
"3.3.1.1.3.4.7.1",
205,
"Frequency of \"Hop Decision Enemy To Enemy\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopDecisionEnemyToEnemy
),
/** Decide to hop a friend piece to an enemy piece. */
HopDecisionFriendToEnemy
(
"3.3.1.1.3.4.8",
206,
"Hop a friend to an enemy piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.HopDecision
),
/** Frequency of HopDecisionFriendToEnemy. */
HopDecisionFriendToEnemyFrequency
(
"3.3.1.1.3.4.8.1",
207,
"Frequency of \"Hop Decision Friend To Enemy\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopDecisionFriendToEnemy
),
/** (move (from ...) (to....)). */
FromToDecision
(
"3.3.1.1.3.5",
208,
"Decide to move a piece from a site to another.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.TwoSitesMoves
),
/** Frequency of FromToDecision. */
FromToDecisionFrequency
(
"3.3.1.1.3.5.1",
209,
"Frequency of \"FromTo Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FromToDecision
),
/** Moves concepts. */
FromToDecisionWithinBoard
(
"3.3.1.1.3.5.2",
210,
"Move a piece from a site to another withing the board.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.FromToDecision
),
/** Frequency of FromToDecisionWithinBoard. */
FromToDecisionWithinBoardFrequency
(
"3.3.1.1.3.5.2.1",
211,
"Frequency of \"FromTo Decision Within Board\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FromToDecisionWithinBoard
),
/** Moves concepts. */
FromToDecisionBetweenContainers
(
"3.3.1.1.3.5.3",
212,
"Move a piece from a site to another between 2 different containers.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.FromToDecision
),
/** Frequency of FromToDecisionBetweenContainers. */
FromToDecisionBetweenContainersFrequency
(
"3.3.1.1.3.5.3.1",
213,
"Frequency of \"FromTo Decision Between Containers\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FromToDecisionBetweenContainers
),
/** Moves concepts. */
FromToDecisionEmpty
(
"3.3.1.1.3.5.4",
214,
"Move a piece to an empty site.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.FromToDecision
),
/** Frequency of FromToDecisionEmpty. */
FromToDecisionEmptyFrequency
(
"3.3.1.1.3.5.4.1",
215,
"Frequency of \"FromTo Decision Empty\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FromToDecisionEmpty
),
/** Moves concepts. */
FromToDecisionEnemy
(
"3.3.1.1.3.5.5",
216,
"Move a piece to an enemy site.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.FromToDecision
),
/** Frequency of FromToDecisionEnemy. */
FromToDecisionEnemyFrequency
(
"3.3.1.1.3.5.5.1",
217,
"Frequency of \"FromTo Decision Enemy\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FromToDecisionEnemy
),
/** Moves concepts. */
FromToDecisionFriend
(
"3.3.1.1.3.5.6",
218,
"Move a piece to a friend site.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.FromToDecision
),
/** Frequency of FromToFriend. */
FromToDecisionFriendFrequency
(
"3.3.1.1.3.5.6.1",
219,
"Frequency of \"FromTo Decision Friend\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FromToDecisionFriend
),
/** (move Swap Piece ...) is used. */
SwapPiecesDecision
(
"3.3.1.1.3.6",
220,
"Decide to swap pieces.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.TwoSitesMoves
),
/** Frequency of SwapPiecesDecision. */
SwapPiecesDecisionFrequency
(
"3.3.1.1.3.6.1",
221,
"Frequency of \"Swap Pieces Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SwapPiecesDecision
),
/** (move Shoot .... is used). */
ShootDecision
(
"3.3.1.1.3.7",
222,
"Decide to shoot.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.TwoSitesMoves
),
/** Frequency of ShootDecision. */
ShootDecisionFrequency
(
"3.3.1.1.3.7.1",
223,
"Frequency of \"Shoot Decision\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ShootDecision
),
/** */
MovesNonDecision
(
"3.3.1.2",
224,
"Moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Moves
),
/** */
MovesEffects
(
"3.3.1.2.1",
225,
"Moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesNonDecision
),
/** (bet ...) */
BetEffect
(
"3.3.1.2.1.1",
226,
"Bet effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.MovesEffects
),
/** Computed with playouts. */
BetEffectFrequency
(
"3.3.1.2.1.1.1",
227,
"Frequency of \"Bet Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.BetEffect
),
/** (vote ...) */
VoteEffect
(
"3.3.1.2.1.2",
228,
"Vote effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.MovesEffects
),
/** Computed with playouts. */
VoteEffectFrequency
(
"3.3.1.2.1.2.1",
229,
"Frequency of \"Vote Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.VoteEffect
),
/** (swap Players ...). */
SwapPlayersEffect
(
"3.3.1.2.1.3",
230,
"Swap players effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesEffects
),
/** Computed with playouts. */
SwapPlayersEffectFrequency
(
"3.3.1.2.1.3.1",
231,
"Frequency of \"Swap Players Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.SwapPlayersEffect
),
/** Take control of enemy pieces. */
TakeControl
(
"3.3.1.2.1.4",
232,
"Take control of enemy pieces.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesEffects
),
/** Computed with playouts. */
TakeControlFrequency
(
"3.3.1.2.1.4.1",
233,
"Frequency of \"Take Control\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.TakeControl
),
/** (pass ...) is used. */
PassEffect
(
"3.3.1.2.1.5",
234,
"Pass a turn.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesEffects
),
/** Computed with playouts. */
PassEffectFrequency
(
"3.3.1.2.1.5.1",
235,
"Frequency of \"Pass Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PassEffect
),
/** (roll ...) is used. */
Roll
(
"3.3.1.2.1.6",
236,
"Roll at least a die.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesEffects
),
/** Computed with playouts. */
RollFrequency
(
"3.3.1.2.1.6.1",
237,
"Frequency of \"Roll\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Roll
),
/** */
ProposeEffect
(
"3.3.1.2.1.7",
238,
"Propose a vote effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.MovesEffects
),
/** Computed with playouts. */
ProposeEffectFrequency
(
"3.3.1.2.1.7.1",
239,
"Frequency of \"Propose Effect\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ProposeEffect
),
/** */
AddEffect
(
"3.3.1.2.1.8",
240,
"Add effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MovesEffects
),
/** Computed with playouts. */
AddEffectFrequency
(
"3.3.1.2.1.8.1",
241,
"Frequency of \"Add Effect\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.AddEffect
),
/** The ludeme (sow ...) is used. */
Sow
(
"3.3.1.2.1.9",
242,
"Sowing stones.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MovesEffects
),
/** Computed with playouts. */
SowFrequency
(
"3.3.1.2.1.9.1",
243,
"Frequency of \"Sow\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Sow
),
/** The ludeme (sow ...) is used with an effect. */
SowWithEffect
(
"3.3.1.2.1.9.2",
244,
"Sowing moves with effect on final hole.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Sow
),
/** The effect of the sow move is to move the captured stones to a store or an hand. */
SowCapture
(
"3.3.1.2.1.9.2.1",
245,
"Sowing with capture.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SowWithEffect
),
/** Frequency of SowCapture. */
SowCaptureFrequency
(
"3.3.1.2.1.9.2.1.1",
246,
"Frequency of \"Sow Capture\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SowCapture
),
/** The ludeme (sow ...) is used. */
SowRemove
(
"3.3.1.2.1.9.2.2",
247,
"Sowing with seeds removed.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SowWithEffect
),
/** Frequency of SowRemove. */
SowRemoveFrequency
(
"3.3.1.2.1.9.2.2.1",
248,
"Frequency of \"Sow Remove\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SowRemove
),
/** The ludeme (sow ...) is used with backtracking at true. */
SowBacktracking
(
"3.3.1.2.1.9.2.3",
249,
"Sowing uses backtracking captures.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SowWithEffect
),
/** Frequency of SowRemove. */
SowBacktrackingFrequency
(
"3.3.1.2.1.9.2.3.1",
250,
"Frequency of \"Sow Backtracking\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SowBacktracking
),
/** Properties of the sow moves (origin, skip, etc...) . */
SowProperties
(
"3.3.1.2.1.9.3",
251,
"Sowing properties.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Sow
),
/** The ludeme (sow ...) is used but skip some holes. */
SowSkip
(
"3.3.1.2.1.9.3.1",
252,
"Sowing in skipping some holes.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SowProperties
),
/** The ludeme (sow ...) sow first in the origin. */
SowOriginFirst
(
"3.3.1.2.1.9.3.2",
253,
"Sowing in the origin hole first.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.SowProperties
),
/** The track used to sow is CW. */
SowCW
(
"3.3.1.2.1.9.3.3",
254,
"Sowing is performed CW.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.SowProperties
),
/** The track used to sow is CCW. */
SowCCW
(
"3.3.1.2.1.9.3.4",
255,
"Sowing is performed CCW.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.SowProperties
),
/** (promote ...) is used. */
PromotionEffect
(
"3.3.1.2.1.10",
256,
"Promote effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MovesEffects
),
/** Computed with playouts. */
PromotionEffectFrequency
(
"3.3.1.2.1.10.1",
257,
"Frequency of \"Promote Effect\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PromotionEffect
),
/** (remove ...) is used. */
RemoveEffect
(
"3.3.1.2.1.11",
258,
"Remove effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MovesEffects
),
/** Computed with playouts. */
RemoveEffectFrequency
(
"3.3.1.2.1.11.1",
259,
"Frequency of \"Remove Effect\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.RemoveEffect
),
/** (push ...) is used. */
PushEffect
(
"3.3.1.2.1.12",
260,
"Push move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MovesEffects
),
/** Frequency of Push. */
PushEffectFrequency
(
"3.3.1.2.1.12.1",
261,
"Frequency of \"Push Effect\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PushEffect
),
/** (flip ...) is used. */
Flip
(
"3.3.1.2.1.13",
262,
"Flip move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesEffects
),
/** Frequency of Flip. */
FlipFrequency
(
"3.3.1.2.1.13.1",
263,
"Frequency of \"Flip Effect\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Flip
),
/** */
SetMove
(
"3.3.1.2.1.14",
264,
"Set Moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesEffects
),
/** (move Set NextPlayer ..). */
SetNextPlayer
(
"3.3.1.2.1.14.1",
265,
"Decide who is the next player.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.SetMove
),
/** Frequency of SetNextPlayer. */
SetNextPlayerFrequency
(
"3.3.1.2.1.14.1.1",
266,
"Frequency of \"Set Next Player\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SetNextPlayer
),
/** (moveAgain). */
MoveAgain
(
"3.3.1.2.1.14.2",
267,
"Set the next player to the mover.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.SetMove
),
/** Frequency of MoveAgain. */
MoveAgainFrequency
(
"3.3.1.2.1.14.2.1",
268,
"Frequency of \"Move Again\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MoveAgain
),
/** (set Value ..). */
SetValue
(
"3.3.1.2.1.14.3",
269,
"Set the value of a piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.SetMove
),
/** Frequency of SetValue. */
SetValueFrequency
(
"3.3.1.2.1.14.3.1",
270,
"Frequency of \"Set Value\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SetValue
),
/** (set Count ..). */
SetCount
(
"3.3.1.2.1.14.4",
271,
"Set the count of a piece.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.SetMove
),
/** Frequency of SetCount. */
SetCountFrequency
(
"3.3.1.2.1.14.4.1",
272,
"Frequency of \"Set Count\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SetCount
),
/** (set Cost ...). */
SetCost
(
"3.3.1.2.1.14.5",
273,
"Set the cost of a graph element.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.SetMove
),
/** Frequency of SetCost. */
SetCostFrequency
(
"3.3.1.2.1.14.5.1",
274,
"Frequency of \"Set Cost\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SetCost
),
/** (set Phase ...). */
SetPhase
(
"3.3.1.2.1.14.6",
275,
"Set the phase of a graph element.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.SetMove
),
/** Frequency of SetPhase. */
SetPhaseFrequency
(
"3.3.1.2.1.14.6.1",
276,
"Frequency of \"Set Phase\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SetPhase
),
/** (set TrumpSuit ..). */
SetTrumpSuit
(
"3.3.1.2.1.14.7",
277,
"Set the trump suit.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.SetMove
),
/** Frequency of SetTrumpSuit. */
SetTrumpSuitFrequency
(
"3.3.1.2.1.14.7.1",
278,
"Frequency of \"Set Trump Suit\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SetTrumpSuit
),
/** (set Direction ...) is used. */
SetRotation
(
"3.3.1.2.1.14.8",
279,
"Rotation move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SetMove
),
/** Frequency of Rotation. */
SetRotationFrequency
(
"3.3.1.2.1.14.8.1",
280,
"Frequency of \"Set Rotation\".",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SetRotation
),
/** */
StepEffect
(
"3.3.1.2.1.15",
281,
"Step effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
false,
Concept.MovesEffects
),
/** */
StepEffectFrequency
(
"3.3.1.2.1.15.1",
282,
"Frequency of \"Step Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.StepEffect
),
/**. */
SlideEffect
(
"3.3.1.2.1.16",
283,
"Slide effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MovesEffects
),
/** */
SlideEffectFrequency
(
"3.3.1.2.1.16.1",
284,
"Frequency of \"Slide Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.SlideEffect
),
/** */
LeapEffect
(
"3.3.1.2.1.17",
285,
"Leap effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MovesEffects
),
/** */
LeapEffectFrequency
(
"3.3.1.2.1.17.1",
286,
"Frequency of \"Leap Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.LeapEffect
),
/** */
HopEffect
(
"3.3.1.2.1.18",
287,
"Hop effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MovesEffects
),
/** */
HopEffectFrequency
(
"3.3.1.2.1.18.1",
288,
"Frequency of \"Hop Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.HopEffect
),
/** (move (from ...) (to....)) or (fromTo ...) is used. */
FromToEffect
(
"3.3.1.2.1.19",
289,
"Effect to move a piece from a site to another.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MovesEffects
),
/** */
FromToEffectFrequency
(
"3.3.1.2.1.19.1",
290,
"Frequency of \"FromTo Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.FromToEffect
),
/** */
SwapPiecesEffect
(
"3.3.1.2.1.20",
291,
"Swap pieces effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesEffects
),
/** */
SwapPiecesEffectFrequency
(
"3.3.1.2.1.20.1",
292,
"Frequency of \"Swap Pieces Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.SwapPiecesEffect
),
/** */
ShootEffect(
"3.3.1.2.1.21",
293,
"Shoot effect.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesEffects
),
/** */
ShootEffectFrequency
(
"3.3.1.2.1.21.1",
294,
"Frequency of \"Shoot Effect\".",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.ShootEffect
),
/** */
MovesOperators
(
"3.3.1.2.2",
295,
"Moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.MovesNonDecision
),
/** (priority ...) is used. */
Priority
(
"3.3.1.2.2.1",
296,
"Some moves are priority.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MovesOperators
),
/** (forEach Die ...) is used. */
ByDieMove
(
"3.3.1.2.2.2",
297,
"Each die can correspond to a different move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MovesOperators
),
/** (max Moves ...). */
MaxMovesInTurn
(
"3.3.1.2.2.3",
298,
"Maximise the number of moves in a turn.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MovesOperators
),
/** (max Distance ..). */
MaxDistance
(
"3.3.1.2.2.4",
299,
"Maximise the distance to move.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MovesOperators
),
/** */
Capture
(
"3.3.2",
300,
"Game involved captures.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Play
),
/** Replacement captures. */
ReplacementCapture
(
"3.3.2.1",
301,
"Capture in replacing.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Capture
),
/** Frequency of ReplacementCapture. */
ReplacementCaptureFrequency
(
"3.3.2.1.1",
302,
"Frequency of \"Replacement Capture\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ReplacementCapture
),
/** True if a Remove move is done in the effect of a hop move. */
HopCapture
(
"3.3.2.2",
303,
"Capture in hopping.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Capture
),
/** Frequency of HopCapture. */
HopCaptureFrequency
(
"3.3.2.2.1",
304,
"Frequency of \"Hop Capture\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopCapture
),
/** True if a Remove move is done in the effect of a hop move and if the min range is greater than one. */
HopCaptureMoreThanOne
(
"3.3.2.3",
305,
"Capture in hopping many sites.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Capture
),
/** Frequency of HopCaptureMoreThanOne. */
HopCaptureMoreThanOneFrequency
(
"3.3.2.3.1",
306,
"Frequency of \"Hop Capture More Than One\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.HopCaptureMoreThanOne
),
/** (directionCapture ...) is used. */
DirectionCapture
(
"3.3.2.4",
307,
"Capture pieces in a direction.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Capture
),
/** Frequency of DirectionCapture. */
DirectionCaptureFrequency
(
"3.3.2.4.1",
308,
"Frequency of \"Direction Capture\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.DirectionCapture
),
/** (enclose ...) is used. */
EncloseCapture
(
"3.3.2.5",
309,
"Capture in enclosing.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Capture
),
/** Frequency of EncloseCapture. */
EncloseCaptureFrequency
(
"3.3.2.5.1",
310,
"Frequency of \"Enclose Capture\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.EncloseCapture
),
/** (custodial ...) is used. */
CustodialCapture
(
"3.3.2.6",
311,
"Capture in custodial.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Capture
),
/** Frequency of CustodialCapture. */
CustodialCaptureFrequency
(
"3.3.2.6.1",
312,
"Frequency of \"Custodial Capture\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.CustodialCapture
),
/** (intervene ...) is used. */
InterveneCapture
(
"3.3.2.7",
313,
"Intervene capture.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Capture
),
/** Frequency of InterveneCapture. */
InterveneCaptureFrequency
(
"3.3.2.7.1",
314,
"Frequency of \"Intervene Capture\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.InterveneCapture
),
/** (surround ...) is used. */
SurroundCapture
(
"3.3.2.8",
315,
"Capture in surrounding.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Capture
),
/** Frequency of SurroundCapture. */
SurroundCaptureFrequency
(
"3.3.2.8.1",
316,
"Frequency of \"Surround Capture\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SurroundCapture
),
/** when: parameter is not null in (remove ...) */
CaptureSequence
(
"3.3.2.9",
317,
"Capture pieces in a sequence at the end of the turn.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Capture
),
/** Frequency of CaptureSequence. */
CaptureSequenceFrequency
(
"3.3.2.9.1",
318,
"Frequency of \"Capture Sequence\" move.",
ConceptType.Play,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.CaptureSequence
),
/** (max Capture ...) is used. */
MaxCapture
(
"3.3.2.10",
319,
"Maximise the number of captures.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Capture
),
/** */
Conditions
(
"3.3.3",
320,
"Conditions checked.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Play
),
/** */
SpaceConditions
(
"3.3.3.1",
321,
"Space conditions.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Conditions
),
/** (is Line ...) is used. */
Line
(
"3.3.3.1.1",
322,
"Line Detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SpaceConditions
),
/** (is Connected ...) is used. */
Connection
(
"3.3.3.1.2",
323,
"Connected regions detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SpaceConditions
),
/** (is Group ...), (count Group ...), (sites Group) or (forEach Group ...) is used. */
Group
(
"3.3.3.1.3",
324,
"Detect a group.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SpaceConditions
),
/** (is In ...) is used. */
Contains
(
"3.3.3.1.4",
325,
"Detect if a site is in a region.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {ConceptPurpose.AI, ConceptPurpose.Reconstruction},
true,
Concept.SpaceConditions
),
/** (is Loop ...) or (sites Loop ...) is used. */
Loop
(
"3.3.3.1.5",
326,
"Loop detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SpaceConditions
),
/** (sites Pattern ...) or (is Pattern ...) is used. */
Pattern
(
"3.3.3.1.6",
327,
"Pattern detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SpaceConditions
),
/** (pathExtent ...) is used. */
PathExtent
(
"3.3.3.1.7",
328,
"Path extent detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SpaceConditions
),
/** (size Territory ...) is used. */
Territory
(
"3.3.3.1.8",
329,
"Territory detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SpaceConditions
),
/** (= (sites Occupied by:....) <RegionFunction>). */
Fill
(
"3.3.3.1.9",
330,
"Check region filled by pieces.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.SpaceConditions
),
/** (Count Steps ...) is used. */
Distance
(
"3.3.3.1.10",
331,
"Check distance between two sites.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.SpaceConditions
),
/** */
MoveConditions
(
"3.3.3.2",
332,
"Move conditions.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Conditions
),
/** Detect if no move. */
NoMoves
(
"3.3.3.2.1",
333,
"Detect no legal moves.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.MoveConditions
),
/** Detect if no move for the mover. */
NoMovesMover
(
"3.3.3.2.1.1",
334,
"Detect no legal moves for the mover.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoMoves
),
/** Detect if no move for the next player. */
NoMovesNext
(
"3.3.3.2.1.2",
335,
"Detect no legal moves for the next player.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoMoves
),
/** (can Move ...) used. Put to false if CanNotMove is used on the same ludeme. */
CanMove
(
"3.3.3.2.2",
336,
"Check if a piece (or more) can make specific move(s).",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MoveConditions
),
/** (not (can Move ...)) used. */
CanNotMove
(
"3.3.3.2.3",
337,
"Check if a piece (or more) can not make specific move(s).",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.MoveConditions
),
/** */
PieceConditions
(
"3.3.3.3",
338,
"Piece conditions.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Conditions
),
/** (= 0 (count Pieces ...) ...) is used. */
NoPiece
(
"3.3.3.3.1",
339,
"No piece detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.PieceConditions
),
/** (= 0 (count Pieces Mover ...) ...) is used. */
NoPieceMover
(
"3.3.3.3.1.1",
340,
"No piece detection for the pieces of the mover.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoPiece
),
/** (= 0 (count Pieces Next...) ...) is used. */
NoPieceNext
(
"3.3.3.3.1.2",
341,
"No piece detection for the pieces of the next player.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoPiece
),
/** (= Off (where ...) ...) is used. */
NoTargetPiece
(
"3.3.3.3.2",
342,
"No target piece detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PieceConditions
),
/** (is Threatened ...) is used. */
Threat
(
"3.3.3.3.3",
343,
"Piece under threat detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PieceConditions
),
/** (is Empty ...) is used. */
IsEmpty
(
"3.3.3.3.4",
344,
"Empty site detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceConditions
),
/** (is Enemy ...) is used. */
IsEnemy
(
"3.3.3.3.5",
345,
"Occupied site by enemy detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceConditions
),
/** (is Friend ...) is used. */
IsFriend
(
"3.3.3.3.6",
346,
"Occupied site by friend detection.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceConditions
),
/** (= (what ...) (id ...) ...) is used. */
IsPieceAt
(
"3.3.3.3.7",
803,
"Occupied site by a specific piece type.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceConditions
),
/** (sites LineOfSight ...), (slide ...) or (shoot ...) is used.. */
LineOfSight
(
"3.3.3.3.8",
347,
"Line of sight of pieces used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PieceConditions
),
/** (</<=/>/>= <IntFunction> (count Pieces ...)) is used. */
CountPiecesComparison
(
"3.3.3.3.9",
348,
"The number of pieces is compared.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.PieceConditions
),
/** (</<=/>/>= <IntFunction> (count Pieces Mover...)) is used. */
CountPiecesMoverComparison
(
"3.3.3.3.9.1",
349,
"The number of pieces of the mover is compared.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.CountPiecesComparison
),
/** (</<=/>/>= <IntFunction> (count Pieces Next ...)) is used. */
CountPiecesNextComparison
(
"3.3.3.3.9.2",
350,
"The number of pieces of the next player is compared.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.CountPiecesComparison
),
/** True if the counter is used to check the progress of the game. */
ProgressCheck
(
"3.3.3.4",
351,
"Progress condition.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Conditions
),
/** */
Directions
(
"3.3.4",
352,
"Directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[]{ ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Play
),
/** */
AbsoluteDirections
(
"3.3.4.1",
353,
"Absolute directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Directions
),
/** All enum is used in the directions. */
AllDirections
(
"3.3.4.1.1",
354,
"All directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.AbsoluteDirections
),
/** Adjacent enum is used. */
AdjacentDirection
(
"3.3.4.1.2",
355,
"Adjacent directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.AbsoluteDirections
),
/** Orthogonal enum is used. */
OrthogonalDirection
(
"3.3.4.1.3",
356,
"Orthogonal directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.AbsoluteDirections
),
/** Diagonal enum is used. */
DiagonalDirection
(
"3.3.4.1.4",
357,
"Diagonal directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.AbsoluteDirections
),
/** OffDiagonal used. */
OffDiagonalDirection
(
"3.3.4.1.5",
358,
"Off diagonal directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.AbsoluteDirections
),
/** Rotational enum used. */
RotationalDirection
(
"3.3.4.1.6",
359,
"Rotational directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.AbsoluteDirections
),
/** SameLayer enum used. */
SameLayerDirection
(
"3.3.4.1.7",
360,
"Same layer directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.AbsoluteDirections
),
/** */
RelativeDirections
(
"3.3.4.2",
361,
"Directions used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Directions
),
/** Forward enum is used. */
ForwardDirection
(
"3.3.4.2.1",
362,
"Forward direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** Backward enum is used. */
BackwardDirection
(
"3.3.4.2.2",
363,
"Backward direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** Forwards enum is used. */
ForwardsDirection
(
"3.3.4.2.3",
364,
"Forwards direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** Backwards enum is used. */
BackwardsDirection
(
"3.3.4.2.4",
365,
"Backwards direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** Rightward enum is used. */
RightwardDirection
(
"3.3.4.2.5",
366,
"Rightward direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** Leftward enum is used. */
LeftwardDirection
(
"3.3.4.2.6",
367,
"Leftward direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** Rightwards enum is used. */
RightwardsDirection
(
"3.3.4.2.7",
368,
"Rightwards direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** Leftwards enum is used. */
LeftwardsDirection
(
"3.3.4.2.8",
369,
"Leftwards direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** FL enum is used. */
ForwardLeftDirection
(
"3.3.4.2.9",
370,
"Forward left direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** FR enum is used. */
ForwardRightDirection
(
"3.3.4.2.10",
371,
"Forward right direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** BL enum is used. */
BackwardLeftDirection(
"3.3.4.2.11",
372,
"Backward left direction used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** BR enum is used. */
BackwardRightDirection
(
"3.3.4.2.12",
373,
"Use backward right direction.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** SameDirection is used. */
SameDirection
(
"3.3.4.2.13",
374,
"Same direction of the previous move used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** OppositeDirection is used. */
OppositeDirection
(
"3.3.4.2.14",
375,
"Opposite direction of the previous move used.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.RelativeDirections
),
/** */
Information
(
"3.3.5",
376,
"Information.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Play
),
/** Any ludeme hiding the piece type. */
HidePieceType
(
"3.3.5.1",
377,
"Hide piece type.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Information
),
/** Any ludeme hiding the piece owner. */
HidePieceOwner
(
"3.3.5.2",
378,
"Hide piece owner.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Information
),
/** Any ludeme hiding the piece count. */
HidePieceCount
(
"3.3.5.3",
379,
"Hide number of pieces.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Information
),
/** Any ludeme hiding the piece rotation. */
HidePieceRotation
(
"3.3.5.4",
380,
"Hide piece rotation.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Information
),
/** Any ludeme hiding the piece value. */
HidePieceValue
(
"3.3.5.5",
381,
"Hide piece value.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Information
),
/** Any ludeme hiding the piece state. */
HidePieceState
(
"3.3.5.6",
382,
"Hide the site state.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Information
),
/** Any ludeme hiding all the info on a site. */
InvisiblePiece
(
"3.3.5.7",
383,
"Piece can be invisible.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Information
),
/** (phase ...) is used. */
Phase
(
"3.3.6",
384,
"Phases of play.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Play
),
/** Number of play phases. */
NumPlayPhase
(
"3.3.6.1",
385,
"Number of play phases.",
ConceptType.Play,
ConceptDataType.IntegerData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Phase
),
/** (set Score ...) is used. */
Scoring
(
"3.3.7",
386,
"Involve scores.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Play
),
/** If any ludeme can make the count of a site to be bigger than 1 or if a stack of the same piece can be placed. */
PieceCount
(
"3.3.8",
387,
"Many pieces of the same type on a site.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Play
),
/** (count Pips) is used. */
SumDice
(
"3.3.9",
388,
"Use sum of all dice.",
ConceptType.Play,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Play
),
//-------------------------------------------------------------------------
// End
//-------------------------------------------------------------------------
/** */
End
(
"3.4",
389,
"Rules for ending the game.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Rules
),
/** */
SpaceEnd
(
"3.4.1",
390,
"Space ending rules.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.End
),
/** Line concept true in an ending condition. */
LineEnd
(
"3.4.1.1",
391,
"End in making a line.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SpaceEnd
),
/** Frequency of LineEnd. */
LineEndFrequency
(
"3.4.1.1.1",
392,
"Frequency of \"Line End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LineEnd
),
/** Line concept true in an ending condition if a non-next player win. */
LineWin
(
"3.4.1.1.2",
393,
"Win in making a line.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.LineEnd
),
/** Frequency of LineWin. */
LineWinFrequency
(
"3.4.1.1.2.1",
394,
"Frequency of \"Line Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LineWin
),
/** Line concept true in an ending condition if a non-next player loss. */
LineLoss
(
"3.4.1.1.3",
395,
"Loss in making a line.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.LineEnd
),
/** Frequency of LineLoss. */
LineLossFrequency
(
"3.4.1.1.3.1",
396,
"Frequency of \"Line Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LineLoss
),
/** Line concept true in an ending condition is a draw. */
LineDraw
(
"3.4.1.1.4",
397,
"Draw in making a line.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.LineEnd
),
/** Frequency of LineDrawn. */
LineDrawFrequency
(
"3.4.1.1.4.1",
398,
"Frequency of \"Line Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LineDraw
),
/** Connection concept true in an ending condition. */
ConnectionEnd
(
"3.4.1.2",
399,
"End if connected regions.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SpaceEnd
),
/** Frequency of ConnectionEnd. */
ConnectionEndFrequency
(
"3.4.1.2.1",
400,
"Frequency of \"Connection End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ConnectionEnd
),
/** Connection concept true in an ending condition if a non-next player win. */
ConnectionWin
(
"3.4.1.2.2",
401,
"Win in connecting regions.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.ConnectionEnd
),
/** Frequency of ConnectionWin. */
ConnectionWinFrequency
(
"3.4.1.2.2.1",
402,
"Frequency of \"Connection Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ConnectionWin
),
/** Connection concept true in an ending condition if a non-next player loss. */
ConnectionLoss
(
"3.4.1.2.3",
403,
"Loss in connecting regions.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.ConnectionEnd
),
/** Frequency of ConnectionLoss. */
ConnectionLossFrequency
(
"3.4.1.2.3.1",
404,
"Frequency of \"Connection Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ConnectionLoss
),
/** Connection concept true in an ending condition is a draw. */
ConnectionDraw
(
"3.4.1.2.4",
405,
"Draw in connecting regions.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.ConnectionEnd
),
/** Frequency of LineDrawn. */
ConnectionDrawFrequency
(
"3.4.1.2.4.1",
406,
"Frequency of \"Connection Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ConnectionDraw
),
/** Group concept true in an ending condition. */
GroupEnd
(
"3.4.1.3",
407,
"End in making a group.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SpaceEnd
),
/** Frequency of GroupEnd. */
GroupEndFrequency
(
"3.4.1.3.1",
408,
"Frequency of \"Group End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.GroupEnd
),
/** Group concept true in an ending condition if a non-next player win. */
GroupWin
(
"3.4.1.3.2",
409,
"Win in making a group.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.GroupEnd
),
/** Frequency of GroupWin. */
GroupWinFrequency
(
"3.4.1.3.2.1",
410,
"Frequency of \"Group Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.GroupWin
),
/** Group concept true in an ending condition if a non-next player loss. */
GroupLoss
(
"3.4.1.3.3",
411,
"Loss in making a group.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.GroupEnd
),
/** Frequency of ConnectionLoss. */
GroupLossFrequency
(
"3.4.1.3.3.1",
412,
"Frequency of \"Group Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.GroupLoss
),
/** Group concept true in an ending condition is a draw. */
GroupDraw
(
"3.4.1.3.4",
413,
"Draw in making a group.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.GroupEnd
),
/** Frequency of GroupDrawn. */
GroupDrawFrequency
(
"3.4.1.3.4.1",
414,
"Frequency of \"Group Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.GroupDraw
),
/** Loop concept true in an ending condition. */
LoopEnd
(
"3.4.1.4",
415,
"End in making a loop.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SpaceEnd
),
/** Frequency of LoopEnd. */
LoopEndFrequency
(
"3.4.1.4.1",
416,
"Frequency of \"Loop End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LoopEnd
),
/** Loop concept true in an ending condition if a non-next player win. */
LoopWin
(
"3.4.1.4.2",
417,
"Win in making a loop.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.LoopEnd
),
/** Frequency of LoopWin. */
LoopWinFrequency
(
"3.4.1.4.2.1",
418,
"Frequency of \"Loop Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LoopWin
),
/** Loop concept true in an ending condition if a non-next player loss. */
LoopLoss
(
"3.4.1.4.3",
419,
"Loss in making a loop.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.LoopEnd
),
/** Frequency of LoopLoss. */
LoopLossFrequency
(
"3.4.1.4.3.1",
420,
"Frequency of \"Loop Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LoopLoss
),
/** Loop concept true in an ending condition is a draw. */
LoopDraw
(
"3.4.1.4.4",
421,
"Draw in making a loop.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.LoopEnd
),
/** Frequency of LoopDrawn. */
LoopDrawFrequency
(
"3.4.1.4.4.1",
422,
"Frequency of \"Loop Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.LoopDraw
),
/** Pattern concept in an ending condition. */
PatternEnd
(
"3.4.1.5",
423,
"End in making a pattern.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SpaceEnd
),
/** Frequency of PatternEnd. */
PatternEndFrequency
(
"3.4.1.5.1",
424,
"Frequency of \"Pattern End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PatternEnd
),
/** Pattern concept true in an ending condition if a non-next player win. */
PatternWin
(
"3.4.1.5.2",
425,
"Win in making a pattern.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.PatternEnd
),
/** Frequency of PatternWin. */
PatternWinFrequency
(
"3.4.1.5.2.1",
426,
"Frequency of \"Pattern Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PatternWin
),
/** Pattern concept true in an ending condition if a non-next player loss. */
PatternLoss
(
"3.4.1.5.3",
427,
"Loss in making a pattern.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.PatternEnd
),
/** Frequency of PatternLoss. */
PatternLossFrequency
(
"3.4.1.5.3.1",
428,
"Frequency of \"Pattern Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PatternLoss
),
/** Pattern concept true in an ending condition is a draw. */
PatternDraw
(
"3.4.1.5.4",
429,
"Draw in making a Pattern.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.PatternEnd
),
/** Frequency of PatternDrawn. */
PatternDrawFrequency
(
"3.4.1.5.4.1",
430,
"Frequency of \"Pattern Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PatternDraw
),
/** PathExtent concept in an ending condition. */
PathExtentEnd
(
"3.4.1.6",
431,
"End with a path extent.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SpaceEnd
),
/** Frequency of PathExtentEnd. */
PathExtentEndFrequency
(
"3.4.1.6.1",
432,
"Frequency of \"Path Extent End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PathExtentEnd
),
/** PathExtent concept true in an ending condition if a non-next player win. */
PathExtentWin
(
"3.4.1.6.2",
433,
"Win with a path extent.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.PathExtentEnd
),
/** Frequency of PathExtentWin. */
PathExtentWinFrequency
(
"3.4.1.6.2.1",
434,
"Frequency of \"PathExtent Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PathExtentWin
),
/** PathExtent concept true in an ending condition if a non-next player loss. */
PathExtentLoss
(
"3.4.1.6.3",
435,
"Loss with a path extent.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.PathExtentEnd
),
/** Frequency of PathExtentLoss. */
PathExtentLossFrequency
(
"3.4.1.6.3.1",
436,
"Frequency of \"PathExtent Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PathExtentLoss
),
/** PathExtent concept true in an ending condition is a draw. */
PathExtentDraw
(
"3.4.1.6.4",
437,
"Draw with a path extent.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.PathExtentEnd
),
/** Frequency of PathExtentDrawn. */
PathExtentDrawFrequency
(
"3.4.1.6.4.1",
438,
"Frequency of \"PathExtent Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.PathExtentDraw
),
/** Territory concept in an ending condition. */
TerritoryEnd
(
"3.4.1.7",
439,
"End related to a territory.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.SpaceEnd
),
/** Frequency of TerritoryEnd. */
TerritoryEndFrequency
(
"3.4.1.7.1",
440,
"Frequency of \"Territory End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.TerritoryEnd
),
/** TerritoryEnd concept true in an ending condition if a non-next player win. */
TerritoryWin
(
"3.4.1.7.2",
441,
"Win related to a territory.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.TerritoryEnd
),
/** Frequency of TerritoryWin. */
TerritoryWinFrequency
(
"3.4.1.7.2.1",
442,
"Frequency of \"Territory Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.TerritoryWin
),
/** Territory concept true in an ending condition if a non-next player loss. */
TerritoryLoss
(
"3.4.1.7.3",
443,
"Loss related to a territory.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.TerritoryEnd
),
/** Frequency of TerritoryLoss. */
TerritoryLossFrequency
(
"3.4.1.7.3.1",
444,
"Frequency of \"Territory Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.TerritoryLoss
),
/** Territory concept true in an ending condition is a draw. */
TerritoryDraw
(
"3.4.1.7.4",
445,
"Draw related to a territory.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.TerritoryEnd
),
/** Frequency of TerritoryDrawn. */
TerritoryDrawFrequency
(
"3.4.1.7.4.1",
446,
"Frequency of \"Territory Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.TerritoryDraw
),
/** */
CaptureEnd
(
"3.4.2",
447,
"Capture ending rules.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.End
),
/** End with (CanNotMove + Threat). */
Checkmate
(
"3.4.2.1",
448,
"End if checkmate.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.CaptureEnd
),
/** Frequency of Checkmate. */
CheckmateFrequency
(
"3.4.2.1.1",
449,
"Frequency of \"Checkmate\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Checkmate
),
/** Checkmate concept true in an ending condition if a non-next player win. */
CheckmateWin
(
"3.4.2.1.2",
450,
"Win if checkmate.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Checkmate
),
/** Frequency of CheckmateWin. */
CheckmateWinFrequency
(
"3.4.2.1.2.1",
451,
"Frequency of \"Checkmate Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.CheckmateWin
),
/** Checkmate concept true in an ending condition if a non-next player loss. */
CheckmateLoss
(
"3.4.2.1.3",
452,
"Loss if checkmate.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Checkmate
),
/** Frequency of CheckmateLoss. */
CheckmateLossFrequency
(
"3.4.2.1.3.1",
453,
"Frequency of \"Checkmate Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.CheckmateLoss
),
/** Checkmate concept true in an ending condition is a draw. */
CheckmateDraw
(
"3.4.2.1.4",
454,
"Draw if checkmate.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.Checkmate
),
/** Frequency of CheckmateDrawn. */
CheckmateDrawFrequency
(
"3.4.2.1.4.1",
455,
"Frequency of \"Checkmate Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.CheckmateDraw
),
/** End with (NoTargetPiece). */
NoTargetPieceEnd
(
"3.4.2.2",
456,
"End if a target piece is removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.CaptureEnd
),
/** Frequency of NoTargetPieceEnd. */
NoTargetPieceEndFrequency
(
"3.4.2.2.1",
457,
"Frequency of \"No Target Piece End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoTargetPieceEnd
),
/** NoTargetPiece concept true in an ending condition if a non-next player win. */
NoTargetPieceWin
(
"3.4.2.2.2",
458,
"Win if a target piece is removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoTargetPieceEnd
),
/** Frequency of NoTargetPieceWin. */
NoTargetPieceWinFrequency
(
"3.4.2.2.2.1",
459,
"Frequency of \"No Target Piece Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoTargetPieceWin
),
/** NoTargetPiece concept true in an ending condition if a non-next player loss. */
NoTargetPieceLoss
(
"3.4.2.2.3",
460,
"Loss if a target piece is removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoTargetPieceEnd
),
/** Frequency of NoTargetPieceLoss. */
NoTargetPieceLossFrequency
(
"3.4.2.2.3.1",
461,
"Frequency of \"No Target Piece Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoTargetPieceLoss
),
/** NoTargetPiece concept true in an ending condition is a draw. */
NoTargetPieceDraw
(
"3.4.2.2.4",
462,
"Draw if a target piece is removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoTargetPieceEnd
),
/** Frequency of NoTargetPieceDrawn. */
NoTargetPieceDrawFrequency
(
"3.4.2.2.4.1",
463,
"Frequency of \"No Target Piece Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoTargetPieceDraw
),
/** End with (= 0 (count Pieces Next...) .... (result Mover Win)) or equivalent. */
EliminatePiecesEnd
(
"3.4.2.3",
464,
"End if all enemy pieces are removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.CaptureEnd
),
/** Frequency of EliminatePiecesEnd. */
EliminatePiecesEndFrequency
(
"3.4.2.3.1",
465,
"Frequency of \"Eliminate All Pieces End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.EliminatePiecesEnd
),
/** NoPiece concept true in an ending condition if a non-next player win. */
EliminatePiecesWin
(
"3.4.2.3.2",
466,
"Win if all enemy pieces are removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.EliminatePiecesEnd
),
/** Frequency of EliminatePiecesWin. */
EliminatePiecesWinFrequency
(
"3.4.2.3.2.1",
467,
"Frequency of \"Eliminate Pieces Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.EliminatePiecesWin
),
/** NoPiece concept true in an ending condition if a non-next player loss. */
EliminatePiecesLoss
(
"3.4.2.3.3",
468,
"Loss if all enemy pieces are removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.EliminatePiecesEnd
),
/** Frequency of EliminatePiecesLoss. */
EliminatePiecesLossFrequency
(
"3.4.2.3.3.1",
469,
"Frequency of \"Eliminate Pieces Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.EliminatePiecesLoss
),
/** NoPiece concept true in an ending condition is a draw. */
EliminatePiecesDraw
(
"3.4.2.3.4",
470,
"Draw if a target piece is removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.EliminatePiecesEnd
),
/** Frequency of EliminatePiecesDraw. */
EliminatePiecesDrawFrequency
(
"3.4.2.3.4.1",
471,
"Frequency of \"Eliminate Pieces Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.EliminatePiecesDraw
),
/** */
RaceEnd
(
"3.4.3",
472,
"Race ending rules.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.End
),
/** No Piece test in End + Win in result type. */
NoOwnPiecesEnd
(
"3.4.3.1",
473,
"End if all own pieces removed (escape games).",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.RaceEnd
),
/** Frequency of NoOwnPieces. */
NoOwnPiecesEndFrequency
(
"3.4.3.1.1",
474,
"Frequency of \"No Own Pieces End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoOwnPiecesEnd
),
/** NoOwnPieces concept true in an ending condition if a non-next player win. */
NoOwnPiecesWin
(
"3.4.3.1.2",
475,
"Win if all own pieces removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoOwnPiecesEnd
),
/** Frequency of NoOwnPiecesWin. */
NoOwnPiecesWinFrequency
(
"3.4.3.1.2.1",
476,
"Frequency of \"No Own Pieces Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoOwnPiecesWin
),
/** NoOwnPieces concept true in an ending condition if a non-next player loss. */
NoOwnPiecesLoss
(
"3.4.3.1.3",
477,
"Loss if all own pieces are removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoOwnPiecesEnd
),
/** Frequency of NoOwnPiecesLoss. */
NoOwnPiecesLossFrequency
(
"3.4.3.1.3.1",
478,
"Frequency of \"No Own Pieces Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoOwnPiecesLoss
),
/** NoOwnPieces concept true in an ending condition is a draw. */
NoOwnPiecesDraw
(
"3.4.3.1.4",
479,
"Draw if all own pieces are removed.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoOwnPiecesEnd
),
/** Frequency of NoOwnPiecesDraw. */
NoOwnPiecesDrawFrequency
(
"3.4.3.1.4.1",
480,
"Frequency of \"No Own Pieces Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoOwnPiecesDraw
),
/** Fill concept in the ending conditions. */
FillEnd
(
"3.4.3.2",
481,
"End in filling a region.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.RaceEnd
),
/** Frequency of FillEnd. */
FillEndFrequency
(
"3.4.3.2.1",
482,
"Frequency of \"Fill End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FillEnd
),
/** Fill concept true in an ending condition if a non-next player win. */
FillWin
(
"3.4.3.2.2",
483,
"Win in filling a region.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.FillEnd
),
/** Frequency of FillWin. */
FillWinFrequency
(
"3.4.3.2.2.1",
484,
"Frequency of \"Fill Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FillWin
),
/** Fill concept true in an ending condition if a non-next player loss. */
FillLoss
(
"3.4.3.2.3",
485,
"Loss in filling a region.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.FillEnd
),
/** Frequency of FillLoss. */
FillLossFrequency
(
"3.4.3.2.3.1",
486,
"Frequency of \"Fill Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FillLoss
),
/** Fill concept true in an ending condition is a draw. */
FillDraw
(
"3.4.3.2.4",
487,
"Draw in filling a region.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.FillEnd
),
/** Frequency of FillDraw. */
FillDrawFrequency
(
"3.4.3.2.4.1",
488,
"Frequency of \"Fill Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.FillDraw
),
/** Contains concept in the ending condition. */
ReachEnd
(
"3.4.3.3",
489,
"End in reaching a region.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.RaceEnd
),
/** Frequency of ReachEnd. */
ReachEndFrequency
(
"3.4.3.3.1",
490,
"Frequency of \"Reach End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ReachEnd
),
/** Contains concept true in an ending condition if a non-next player win. */
ReachWin
(
"3.4.3.3.2",
491,
"Win in reaching a region.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.ReachEnd
),
/** Frequency of ReachWin. */
ReachWinFrequency
(
"3.4.3.3.2.1",
492,
"Frequency of \"Reach Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ReachWin
),
/** Contains concept true in an ending condition if a non-next player loss. */
ReachLoss
(
"3.4.3.3.3",
493,
"Loss in reaching a region.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.ReachEnd
),
/** Frequency of ReachLoss. */
ReachLossFrequency
(
"3.4.3.3.3.1",
494,
"Frequency of \"Reach Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ReachLoss
),
/** Contains concept true in an ending condition is a draw. */
ReachDraw
(
"3.4.3.3.4",
495,
"Draw in reaching a region.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.ReachEnd
),
/** Frequency of ReachDraw. */
ReachDrawFrequency
(
"3.4.3.3.4.1",
496,
"Frequency of \"Reach Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ReachDraw
),
/** (byScore ...) ending condition. */
ScoringEnd
(
"3.4.4",
497,
"End in comparing scores.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.End
),
/** Frequency of ScoringEnd. */
ScoringEndFrequency
(
"3.4.4.1",
498,
"Frequency of \"Scoring End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ScoringEnd
),
/** Score concept true in an ending condition if a non-next player win. */
ScoringWin
(
"3.4.4.2",
499,
"Win in comparing score.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.ScoringEnd
),
/** Frequency of ScoreWin. */
ScoringWinFrequency
(
"3.4.4.2.1",
500,
"Frequency of \"Score Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ScoringWin
),
/** Score concept true in an ending condition if a non-next player loss. */
ScoringLoss
(
"3.4.4.3",
501,
"Loss in comparing score.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.ScoringEnd
),
/** Frequency of ReachLoss. */
ScoringLossFrequency
(
"3.4.4.3.1",
502,
"Frequency of \"Score Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ScoringLoss
),
/** Contains concept true in an ending condition is a draw. */
ScoringDraw
(
"3.4.4.4",
503,
"Draw in comparing score.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.ScoringEnd
),
/** Frequency of ReachDraw. */
ScoringDrawFrequency
(
"3.4.4.4.1",
504,
"Frequency of \"Reach Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.ScoringDraw
),
/** End if no moves. */
NoMovesEnd
(
"3.4.5",
505,
"End if no legal moves (stalemate).",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.End
),
/** Frequency of StalemateEnd. */
NoMovesEndFrequency
(
"3.4.5.1",
506,
"Frequency of \"No Moves End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoMovesEnd
),
/** NoMoves concept true in an ending condition if a non-next player win. */
NoMovesWin
(
"3.4.5.2",
507,
"Win if no legal moves.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoMovesEnd
),
/** Frequency of NoMovesWin. */
NoMovesWinFrequency
(
"3.4.5.2.1",
508,
"Frequency of \"No Moves Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoMovesWin
),
/** NoMoves concept true in an ending condition if a non-next player loss. */
NoMovesLoss
(
"3.4.5.3",
509,
"Loss if no legal moves.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoMovesEnd
),
/** Frequency of NoMovesLoss. */
NoMovesLossFrequency
(
"3.4.5.3.1",
510,
"Frequency of \"No Moves Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoMovesLoss
),
/** NoMoves concept true in an ending condition is a draw. */
NoMovesDraw
(
"3.4.5.4",
511,
"Draw if no legal moves.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoMovesEnd
),
/** Frequency of NoMovesDraw. */
NoMovesDrawFrequency
(
"3.4.5.4.1",
512,
"Frequency of \"No Moves Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoMovesDraw
),
/** The counter is used in the ending rules. */
NoProgressEnd
(
"3.4.6",
513,
"The game does not progress to an end (e.g. 50 moves rule in Chess).",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.End
),
/** Frequency of NoProgressEnd. */
NoProgressEndFrequency
(
"3.4.6.1",
514,
"Frequency of \"No Progress End\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoProgressEnd
),
/** ProgressCheck concept true in an ending condition if a non-next player win. */
NoProgressWin
(
"3.4.6.2",
515,
"Win if no progress to an end.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoProgressEnd
),
/** Frequency of NoMovesWin. */
NoProgressWinFrequency
(
"3.4.6.2.1",
516,
"Frequency of \"No Progress Win\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoProgressWin
),
/** ProgressCheck concept true in an ending condition if a non-next player loss. */
NoProgressLoss
(
"3.4.6.3",
517,
"Loss if no progress to an end.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoProgressEnd
),
/** Frequency of NoMovesLoss. */
NoProgressLossFrequency
(
"3.4.6.3.1",
518,
"Frequency of \"No Progress Loss\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoProgressLoss
),
/** ProgressCheck concept true in an ending condition is a draw. */
NoProgressDraw
(
"3.4.6.4",
519,
"Draw if no progress to an end.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.NoProgressEnd
),
/** Frequency of NoMovesDraw. */
NoProgressDrawFrequency
(
"3.4.6.4.1",
520,
"Frequency of \"No Progress Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.NoProgressDraw
),
/** A resultType Draw is used . */
Draw
(
"3.4.7",
521,
"The game can ends in a draw.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
false,
Concept.End
),
/** Frequency of Draw. */
DrawFrequency
(
"3.4.7.1",
522,
"Frequency of \"Draw\".",
ConceptType.End,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.Draw
),
/** Solving a deduction puzzle. */
SolvedEnd
(
"3.4.8",
804,
"The game ends in solving the puzzle.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.End
),
/** A misere end rule is detected . */
Misere
(
"3.4.9",
523,
"A two-players game can ends with the mover losing or the next player winning.",
ConceptType.End,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, ConceptPurpose.Reconstruction },
true,
Concept.End
),
//-------------------------------------------------------------------------
// Behaviour
//-------------------------------------------------------------------------
/** */
Behaviour
(
"4",
524,
"Behaviour.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
null
),
/** */
StateRepetition
(
"4.1",
525,
"State repetition.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
PositionalRepetition
(
"4.1.1",
526,
"Average number of repeated positional states.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateRepetition
),
/** Computed with playouts. */
SituationalRepetition
(
"4.1.2",
527,
"Average number of repeated situational states.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateRepetition
),
/** */
Duration
(
"4.2",
528,
"Game duration.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
DurationActions
(
"4.2.1",
529,
"Number of actions in a game.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Duration
),
/** Computed with playouts. */
DurationMoves
(
"4.2.2",
530,
"Number of moves in a game.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Duration
),
/** Computed with playouts. */
DurationTurns
(
"4.2.3",
531,
"Number of turns in a game.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Duration
),
/** Computed with playouts. */
DurationTurnsStdDev
(
"4.2.4",
798,
"Number of turns in a game (std dev).",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Duration
),
/** Computed with playouts. */
DurationTurnsNotTimeouts
(
"4.2.5",
799,
"Duration Turns Not Timeouts.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Duration
),
/** */
Complexity
(
"4.3",
532,
"Game complexity.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
DecisionMoves
(
"4.3.1",
533,
"Percentage of moves where there was more than one possible move.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Complexity
),
/** Computed with playouts. */
GameTreeComplexity
(
"4.3.2",
534,
"Game Tree Complexity Estimate.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Complexity
),
/** Computed with playouts. */
StateTreeComplexity
(
"4.3.3",
535,
"State Space Complexity Upper Bound.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Complexity
),
/** */
BoardCoverage
(
"4.4",
536,
"Board Coverage.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
BoardCoverageDefault
(
"4.4.1",
537,
"Percentage of default board sites which a piece was placed on at some point.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardCoverage
),
/** Computed with playouts. */
BoardCoverageFull
(
"4.4.2",
538,
"Percentage of all board sites which a piece was placed on at some point.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardCoverage
),
/** Computed with playouts. */
BoardCoverageUsed
(
"4.4.3",
539,
"Percentage of used board sites which a piece was placed on at some point.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardCoverage
),
/** */
GameOutcome
(
"4.5",
540,
"Game Outcome.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
AdvantageP1
(
"4.5.1",
541,
"Percentage of games where player 1 won.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.GameOutcome
),
/** Computed with playouts. */
Balance
(
"4.5.2",
542,
"Similarity between player win rates.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.GameOutcome
),
/** Computed with playouts. */
Completion
(
"4.5.3",
543,
"Percentage of games which have a winner (not drawor timeout).",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.GameOutcome
),
/** Computed with playouts. */
Drawishness
(
"4.5.4",
544,
"Percentage of games which end in a draw.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.GameOutcome
),
/** Computed with playouts. */
Timeouts
(
"4.5.5",
545,
"Percentage of games which end via timeout.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.GameOutcome
),
/** Computed with playouts. */
OutcomeUniformity
(
"4.5.6",
779,
"Inverse of average per-player variance in outcomes.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.GameOutcome
),
/** */
StateEvaluation
(
"4.6",
546,
"State Evaluation.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** */
Clarity
(
"4.6.1",
547,
"Clarity.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.StateEvaluation
),
/** Computed with playouts. */
Narrowness
(
"4.6.1.1",
548,
"Narrowness.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Clarity
),
/** Computed with playouts. */
Variance
(
"4.6.1.2",
549,
"Variance.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Clarity
),
/** */
Decisiveness
(
"4.6.2",
550,
"Decisiveness.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.StateEvaluation
),
/** Computed with playouts. */
DecisivenessMoves
(
"4.6.2.1",
551,
"Decisiveness Moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Decisiveness
),
/** Computed with playouts. */
DecisivenessThreshold
(
"4.6.2.2",
552,
"Decisiveness Threshold.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Decisiveness
),
/** Computed with playouts. */
LeadChange
(
"4.6.3",
553,
"LeadChange.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluation
),
/** Computed with playouts. */
Stability
(
"4.6.4",
554,
"Stability.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluation
),
/** */
Drama
(
"4.6.5",
555,
"Drama.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.StateEvaluation
),
/** Computed with playouts. */
DramaAverage
(
"4.6.5.1",
556,
"Drama Average.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaMedian
(
"4.6.5.2",
557,
"Drama Median.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaMaximum
(
"4.6.5.3",
558,
"Drama Maximum.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaMinimum
(
"4.6.5.4",
559,
"Drama Minimum.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaVariance
(
"4.6.5.5",
560,
"Drama Variance.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaChangeAverage
(
"4.6.5.6",
561,
"Drama Change Average.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaChangeSign
(
"4.6.5.7",
562,
"Drama Change Sign.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaChangeLineBestFit
(
"4.6.5.8",
563,
"Drama Change Line Best Fit.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaChangeNumTimes
(
"4.6.5.9",
564,
"Drama Change Num Times.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaMaxIncrease
(
"4.6.5.10",
565,
"Drama Max Increase.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** Computed with playouts. */
DramaMaxDecrease
(
"4.6.5.11",
566,
"Drama Max Decrease.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Drama
),
/** */
MoveEvaluation
(
"4.6.6",
567,
"Drama.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.StateEvaluation
),
/** Computed with playouts. */
MoveEvaluationAverage
(
"4.6.6.1",
568,
"Move Evaluation Average.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationMedian
(
"4.6.6.2",
569,
"Move Evaluation Median.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationMaximum
(
"4.6.6.3",
570,
"Move Evaluation Maximum.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationMinimum
(
"4.6.6.4",
571,
"Move Evaluation Minimum.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationVariance
(
"4.6.6.5",
572,
"Move Evaluation Variance.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationChangeAverage
(
"4.6.6.6",
573,
"Move Evaluation Change Average.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationChangeSign
(
"4.6.6.7",
574,
"Move Evaluation Change Sign.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationChangeLineBestFit
(
"4.6.6.8",
575,
"Move Evaluation Change Line Best Fit.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationChangeNumTimes
(
"4.6.6.9",
576,
"Move Evaluation Change Num Times.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationMaxIncrease
(
"4.6.6.10",
577,
"Move Evaluation Max Increase.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** Computed with playouts. */
MoveEvaluationMaxDecrease
(
"4.6.6.11",
578,
"Move Evaluation Max Decrease.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveEvaluation
),
/** */
StateEvaluationDifference
(
"4.6.7",
579,
"Drama.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.StateEvaluation
),
/** Computed with playouts. */
StateEvaluationDifferenceAverage
(
"4.6.7.1",
580,
"State Evaluation Difference Average.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceMedian
(
"4.6.7.2",
581,
"State Evaluation Difference Median.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceMaximum
(
"4.6.7.3",
582,
"State Evaluation Difference Maximum.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceMinimum
(
"4.6.7.4",
583,
"State Evaluation Difference Minimum.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceVariance
(
"4.6.7.5",
584,
"State Evaluation Difference Variance.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceChangeAverage
(
"4.6.7.6",
585,
"State Evaluation Difference Change Average.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceChangeSign
(
"4.6.7.7",
586,
"State Evaluation Difference Change Sign.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceChangeLineBestFit
(
"4.6.7.8",
587,
"State Evaluation Difference Change Line Best Fit.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceChangeNumTimes
(
"4.6.7.9",
588,
"State Evaluation Difference Change Num Times.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceMaxIncrease
(
"4.6.7.10",
589,
"State Evaluation Difference Max Increase.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** Computed with playouts. */
StateEvaluationDifferenceMaxDecrease
(
"4.6.7.11",
590,
"State Evaluation Difference Max Decrease.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.StateEvaluationDifference
),
/** */
BoardSitesOccupied
(
"4.7",
591,
"Board sites occupied.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
BoardSitesOccupiedAverage
(
"4.7.1",
592,
"Average percentage of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedMedian
(
"4.7.2",
593,
"Median percentage of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedMaximum
(
"4.7.3",
594,
"Maximum percentage of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedMinimum
(
"4.7.4",
595,
"Minimum percentage of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedVariance
(
"4.7.5",
596,
"Variance in percentage of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedChangeAverage
(
"4.7.6",
597,
"Change in percentage of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedChangeSign
(
"4.7.7",
598,
"Sign Change of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedChangeLineBestFit
(
"4.7.8",
599,
"Line Best Fit Change of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedChangeNumTimes
(
"4.7.9",
600,
"Number of times the change of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedMaxIncrease
(
"4.7.10",
601,
"Max Increase of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** Computed with playouts. */
BoardSitesOccupiedMaxDecrease
(
"4.7.11",
602,
"Max Decrease of board sites which have a piece on it in any given turn.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BoardSitesOccupied
),
/** */
BranchingFactor
(
"4.8",
603,
"Branching factor.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
BranchingFactorAverage
(
"4.8.1",
604,
"Average number of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorMedian
(
"4.8.2",
605,
"Median number of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorMaximum
(
"4.8.3",
606,
"Maximum number of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorMinimum
(
"4.8.4",
607,
"Minimum number of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorVariance
(
"4.8.5",
608,
"Variance in number of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorChangeAverage
(
"4.8.6",
609,
"Change in percentage of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorChangeSign
(
"4.8.7",
610,
"Change sign of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorChangeLineBestFit
(
"4.8.8",
611,
"Change line best fit of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorChangeNumTimesn
(
"4.8.9",
612,
"Change num times of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorChangeMaxIncrease
(
"4.8.10",
613,
"Change max increase of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** Computed with playouts. */
BranchingFactorChangeMaxDecrease
(
"4.8.11",
614,
"Change max decrease of possible moves.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.BranchingFactor
),
/** */
DecisionFactor
(
"4.9",
615,
"Decision factor.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
DecisionFactorAverage
(
"4.9.1",
616,
"Average number of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorMedian
(
"4.9.2",
617,
"Median number of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorMaximum
(
"4.9.3",
618,
"Maximum number of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorMinimum
(
"4.9.4",
619,
"Minimum number of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorVariance
(
"4.9.5",
620,
"Variance in number of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorChangeAverage
(
"4.9.6",
621,
"Change in percentage of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorChangeSign
(
"4.9.7",
622,
"Change sign of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorChangeLineBestFit
(
"4.9.8",
623,
"Change line best fit of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorChangeNumTimes
(
"4.9.9",
624,
"Change num times of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorMaxIncrease
(
"4.9.10",
625,
"Max increase of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** Computed with playouts. */
DecisionFactorMaxDecrease
(
"4.9.11",
626,
"Max Decrease of possible moves when the number of possible moves is greater than 1.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.DecisionFactor
),
/** */
MoveDistance
(
"4.10",
627,
"Move distance.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
MoveDistanceAverage
(
"4.10.1",
628,
"Average distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceMedian
(
"4.10.2",
629,
"Median distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceMaximum
(
"4.10.3",
630,
"Maximum distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceMinimum
(
"4.10.4",
631,
"Minimum distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceVariance
(
"4.10.5",
632,
"Variance in distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceChangeAverage
(
"4.10.6",
633,
"Change average in distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceChangeSign
(
"4.10.7",
634,
"Change sign in distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceChangeLineBestFit
(
"4.10.8",
635,
"Change line best fit in distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceChangeNumTimes
(
"4.10.9",
636,
"Change num times in distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceMaxIncrease
(
"4.10.10",
637,
"Max increase in distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** Computed with playouts. */
MoveDistanceMaxDecrease
(
"4.10.11",
638,
"Max decrease in distance traveled by pieces when they move around the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.MoveDistance
),
/** */
PieceNumber
(
"4.11",
639,
"Piece number.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
PieceNumberAverage
(
"4.11.1",
640,
"Average number of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberMedian
(
"4.11.2",
641,
"Median number of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberMaximum
(
"4.11.3",
642,
"Maximum number of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberMinimum
(
"4.11.4",
643,
"Minimum number of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberVariance
(
"4.11.5",
644,
"Variance in number of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberChangeAverage
(
"4.11.6",
645,
"Change in percentage of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberChangeSign
(
"4.11.7",
646,
"Change in sign of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberChangeLineBestFit
(
"4.11.8",
647,
"Change line best fit of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberChangeNumTimes
(
"4.11.9",
648,
"Change in number of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberMaxIncrease
(
"4.11.10",
649,
"Max increase of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** Computed with playouts. */
PieceNumberMaxDecrease
(
"4.11.11",
650,
"Max decrease of pieces on the board.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.PieceNumber
),
/** */
ScoreDifference
(
"4.12",
651,
"Score Difference.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
ScoreDifferenceAverage
(
"4.12.1",
652,
"Average difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceMedian
(
"4.12.2",
653,
"Median difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceMaximum
(
"4.12.3",
654,
"Maximum difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceMinimum
(
"4.12.4",
655,
"Minimum difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceVariance
(
"4.12.5",
656,
"Variance in difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceChangeAverage
(
"4.12.6",
657,
"Change average in difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceChangeSign
(
"4.12.7",
658,
"Change sign in difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceChangeLineBestFit
(
"4.12.8",
659,
"Change line best fit in difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceChangeNumTimes
(
"4.12.9",
660,
"Change number times in difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceMaxIncrease
(
"4.12.10",
661,
"Max increase in difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** Computed with playouts. */
ScoreDifferenceMaxDecrease
(
"4.12.11",
662,
"Max decrease in difference in player scores.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.ScoreDifference
),
/** */
SkillTrace
(
"4.13",
805,
"Skill Trace.",
ConceptType.Behaviour,
ConceptDataType.BooleanData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Behaviour
),
/** Computed with playouts. */
SkillTraceScore
(
"4.13.1",
806,
"Skill Trace Score.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.SkillTrace
),
/** Computed with playouts. */
SkillTraceTrials
(
"4.13.2",
807,
"Skill Trace Trials.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.SkillTrace
),
/** Computed with playouts. */
SkillTraceErrorSlope
(
"4.13.3",
808,
"Skill Trace Error Slope.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.SkillTrace
),
/** Computed with playouts. */
SkillTraceErrorIntercept
(
"4.13.4",
809,
"Skill Trace Error Intercept.",
ConceptType.Behaviour,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.SkillTrace
),
//-------------------------------------------------------------------------
// Math
//-------------------------------------------------------------------------
/** */
Math
(
"5",
663,
"Mathematics.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
null
),
/** */
Arithmetic
(
"5.1",
664,
"Arithmetic.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Math
),
/** */
Operations
(
"5.1.1",
665,
"Operations.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Arithmetic
),
/** (+ ...) is used. */
Addition
(
"5.1.1.1",
666,
"Addition operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (- ...) is used. */
Subtraction
(
"5.1.1.2",
667,
"Subtraction operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (* ...) is used.. */
Multiplication
(
"5.1.1.3",
668,
"Multiplication operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (/ ...) is used. */
Division
(
"5.1.1.4",
669,
"Division operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (% ...) is used. */
Modulo
(
"5.1.1.5",
670,
"Modulo operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (abs ...) is used. */
Absolute
(
"5.1.1.6",
671,
"Absolute operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (sqrt ...) used.. */
Roots
(
"5.1.1.7",
672,
"Root operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (cos ...) is used. */
Cosine
(
"5.1.1.8",
673,
"Cosine operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (sin ...) is used. */
Sine
(
"5.1.1.9",
674,
"Sine operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (tan ...) is used. */
Tangent
(
"5.1.1.10",
675,
"Tangent operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (^ ...) is used. */
Exponentiation
(
"5.1.1.11",
676,
"Exponentiation operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (exp ...) is used. */
Exponential
(
"5.1.1.12",
677,
"Exponential operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (log ...) or (log10 ...) is used. */
Logarithm
(
"5.1.1.13",
678,
"Logarithm operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (min ...) is used. */
Minimum
(
"5.1.1.14",
679,
"Minimum value.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** (max ...) is used. */
Maximum
(
"5.1.1.15",
680,
"Maximum value.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Operations
),
/** */
Comparison
(
"5.1.2",
681,
"Comparison of numbers.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Arithmetic
),
/** = operator. */
Equal
(
"5.1.2.1",
682,
"= operator.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Comparison
),
/** != operator. */
NotEqual
(
"5.1.2.2",
683,
"!= operator.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Comparison
),
/** < operator. */
LesserThan
(
"5.1.2.3",
684,
"< operator.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Comparison
),
/** <= operator. */
LesserThanOrEqual
(
"5.1.2.4",
685,
"<= operator.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Comparison
),
/** > operator. */
GreaterThan
(
"5.1.2.5",
686,
"> operator.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Comparison
),
/** >= operator. */
GreaterThanOrEqual
(
"5.1.2.6",
687,
">= operator.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Comparison
),
/** */
Parity
(
"5.1.3",
688,
"Whether a number is even or odd.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Arithmetic
),
/** Even values. */
Even
(
"5.1.3.1",
689,
"Even values.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Parity
),
/** Odd values. */
Odd
(
"5.1.3.2",
690,
"Odd values.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Parity
),
/** */
Logic
(
"5.2",
691,
"Logic operations.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Math
),
/** (and ...). */
Conjunction
(
"5.2.1",
692,
"Conjunction (And).",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Logic
),
/**(or ...). */
Disjunction
(
"5.2.2",
693,
"Disjunction (Or).",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Logic
),
/** (xor ...). */
ExclusiveDisjunction
(
"5.2.3",
694,
"Exclusive Disjunction (Xor).",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Logic
),
/** (not ...). */
Negation
(
"5.2.4",
695,
"Negation (Not).",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Logic
),
/** */
Set
(
"5.3",
696,
"Set operations.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Math
),
/** (union ...). */
Union
(
"5.3.1",
697,
"Union operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Set
),
/** (intersection ...). */
Intersection
(
"5.3.2",
698,
"Intersection operation.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Set
),
/** (difference ...). */
Complement
(
"5.3.3",
699,
"Complement operation (Difference).",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Set
),
/** */
Algorithmics
(
"5.4",
700,
"Algorithmic operations.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
false,
Concept.Math
),
/** (if ...) is used. */
ConditionalStatement
(
"5.4.1",
701,
"Conditional Statement (If).",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Algorithmics
),
/** (for ...) is used. */
ControlFlowStatement
(
"5.4.2",
702,
"Control Flow Statement (For).",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Algorithmics
),
/** Float values. */
Float
(
"5.5",
703,
"Float values.",
ConceptType.Math,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.Reconstruction, ConceptPurpose.AI },
true,
Concept.Math
),
//-------------------------------------------------------------------------
// Visual
//-------------------------------------------------------------------------
/** */
Visual
(
"6",
704,
"Important visual aspects.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
false,
null
),
/** */
Style
(
"6.1",
705,
"Style of game elements.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[]{ },
false,
Concept.Visual
),
/** */
BoardStyle
(
"6.1.1",
706,
"Style of the board.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
false,
Concept.Style
),
/** Use Graph style. */
GraphStyle
(
"6.1.1.1",
707,
"Use Graph style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Chess style. */
ChessStyle
(
"6.1.1.2",
708,
"Use Chess style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Go style.*/
GoStyle
(
"6.1.1.3",
709,
"Use Go style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[]{ },
true,
Concept.BoardStyle
),
/** Use Mancala style.*/
MancalaStyle
(
"6.1.1.4",
710,
"Use Mancala style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use PenAndPaper style.*/
PenAndPaperStyle
(
"6.1.1.5",
711,
"Use PenAndPaper style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Shibumi style.*/
ShibumiStyle
(
"6.1.1.6",
712,
"Use Shibumi style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Backgammon style.*/
BackgammonStyle
(
"6.1.1.7",
713,
"Use Backgammon style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Janggi style. */
JanggiStyle
(
"6.1.1.8",
714,
"Use Janggi style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Xiangqi style. */
XiangqiStyle
(
"6.1.1.9",
715,
"Use Xiangqi style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Shogi style. */
ShogiStyle(
"6.1.1.10",
716,
"Use Shogi style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Table style. */
TableStyle(
"6.1.1.11",
717,
"Use Table style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Surakarta style. */
SurakartaStyle
(
"6.1.1.12",
718,
"Use Surakarta style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Use Tafl style. */
TaflStyle
(
"6.1.1.13",
719,
"Use Tafl style.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** Board is not shown. */
NoBoard
(
"6.1.1.14",
720,
"Board is not shown.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.BoardStyle
),
/** */
ComponentStyle
(
"6.1.2",
721,
"Style of the component.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
false,
Concept.Style
),
/** Use animal components. */
AnimalComponent
(
"6.1.2.1",
722,
"Use animal components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Chess components. */
ChessComponent
(
"6.1.2.2",
723,
"Use Chess components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
false,
Concept.ComponentStyle
),
/** Use King components. */
KingComponent
(
"6.1.2.2.1",
724,
"Use Chess components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ChessComponent
),
/** Use Queen components. */
QueenComponent
(
"6.1.2.2.2",
725,
"Use Queen components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ChessComponent
),
/** Use Knight components. */
KnightComponent
(
"6.1.2.2.3",
726,
"Use Knight components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ChessComponent
),
/** Use Rook components. */
RookComponent
(
"6.1.2.2.4",
727,
"Use Rook components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ChessComponent
),
/** Use Bishop components. */
BishopComponent
(
"6.1.2.2.5",
728,
"Use Bishop components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ChessComponent
),
/** Use Pawn components. */
PawnComponent
(
"6.1.2.2.6",
729,
"Use Pawn components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ChessComponent
),
/** Use fairy Chess components. */
FairyChessComponent
(
"6.1.2.3",
730,
"Use fairy Chess components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Ploy components. */
PloyComponent
(
"6.1.2.4",
731,
"Use Ploy components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Shogi components. */
ShogiComponent
(
"6.1.2.5",
732,
"Use Shogi components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Xiangqi components. */
XiangqiComponent
(
"6.1.2.6",
733,
"Use Xiangqi components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Stratego components. */
StrategoComponent
(
"6.1.2.7",
734,
"Use Stratego components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Janggi components. */
JanggiComponent
(
"6.1.2.8",
735,
"Use Janggi components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Hand components. */
HandComponent
(
"6.1.2.9",
736,
"Use Hand components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Checkers components. */
CheckersComponent
(
"6.1.2.10",
737,
"Use Checkers components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Ball components. */
BallComponent
(
"6.1.2.11",
738,
"Use Ball components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Tafl components. */
TaflComponent
(
"6.1.2.12",
739,
"Use Tafl components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Disc components. */
DiscComponent
(
"6.1.2.13",
740,
"Use Disc components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/** Use Marker components. */
MarkerComponent
(
"6.1.2.14",
741,
"Use Marker components.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.ComponentStyle
),
/**
* Visual of a stack is modified.
*/
StackType
(
"6.2",
742,
"Visual of a stack.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] {},
false,
Concept.Visual
),
/**
* Use stacks.
*/
Stack
(
"6.2.1",
743,
"Stacks of pieces.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.StackType
),
/** Use Symbols. */
Symbols
(
"6.3",
744,
"Symbols on the board.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.Visual
),
/** Show piece value. */
ShowPieceValue
(
"6.4",
745,
"Show piece values.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.Visual
),
/** Show piece state. */
ShowPieceState
(
"6.5",
746,
"Show piece states.",
ConceptType.Visual,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { },
true,
Concept.Visual
),
//-------------------------------------------------------------------------
// Implementation
//-------------------------------------------------------------------------
/** */
Implementation
(
"7",
747,
"Internal implementation details, e.g. for performance predictions.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
false,
null
),
/** */
State
(
"7.1",
748,
"State related implementation.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
false,
Concept.Implementation
),
/** */
StateType
(
"7.1.1",
749,
"Type of state used.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
false,
Concept.State
),
/** Use stack state. */
StackState
(
"7.1.1.1",
750,
"Use stack state.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI, },
true,
Concept.StateType
),
/** */
PieceState
(
"7.1.2",
751,
"State related information about piece.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
false,
Concept.State
),
/** Use site state. */
SiteState
(
"7.1.2.1",
752,
"Use site state.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.PieceState
),
/** Use (set State ...). */
SetSiteState
(
"7.1.2.2",
753,
"Set the site state.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.PieceState
),
/** Store visited sites in previous moves of a turn. */
VisitedSites
(
"7.1.2.3",
754,
"Store visited sites in previous moves of a turn.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.PieceState
),
/** Use state variable(s). */
Variable
(
"7.1.3",
755,
"Use state variable(s).",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
false,
Concept.State
),
/** (set Var ...). */
SetVar
(
"7.1.3.1",
756,
"The variable 'var' is set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Variable
),
/** (remember ...). */
RememberValues
(
"7.1.3.2",
757,
"Some values are remembered.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Variable
),
/** (remember ...). */
ForgetValues
(
"7.1.3.3",
758,
"Some values are forgotten.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Variable
),
/** (set Pending ...). */
SetPending
(
"7.1.3.4",
759,
"The variable pending is set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Variable
),
/** Use internal counter of the state. */
InternalCounter
(
"7.1.4",
760,
"Use internal counter of the state.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
false,
Concept.State
),
/** Set internal counter of the state. */
SetInternalCounter
(
"7.1.4.1",
761,
"Set internal counter of the state.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.InternalCounter
),
/** Use player value. */
PlayerValue
(
"7.1.5",
762,
"Use player value.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.State
),
/** */
SetHidden
(
"7.1.6",
763,
"Hidden information are set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
false,
Concept.State
),
/** (set Hidden ...) is used. */
SetInvisible
(
"7.1.6.1",
764,
"Invisibility is set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.SetHidden
),
/** (set Hidden Count ...) is used. */
SetHiddenCount
(
"7.1.6.2",
765,
"Hidden count is set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.SetHidden
),
/** (set Hidden Rotation ...) is used. */
SetHiddenRotation
(
"7.1.6.3",
766,
"Hidden rotation is set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.SetHidden
),
/** (set Hidden State ...) is used. */
SetHiddenState
(
"7.1.6.4",
767,
"Hidden state is set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.SetHidden
),
/** (set Hidden Value ...) is used. */
SetHiddenValue
(
"7.1.6.5",
768,
"Hidden value is set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.SetHidden
),
/** (set Hidden What ...) is used. */
SetHiddenWhat
(
"7.1.6.6",
769,
"Hidden count are set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.SetHidden
),
/** (set Hidden Who ...) is used. */
SetHiddenWho
(
"7.1.6.7",
770,
"Hidden who is set.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.SetHidden
),
/** */
Efficiency
(
"7.2",
771,
"Implementation related to efficiency (run on Intel E7-8860, 2.2 GHz, 4GB RAM, Seed = 2077).",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
false,
Concept.Implementation
),
/** The context can be copied during computation of the moves. */
CopyContext
(
"7.2.1",
772,
"The context can be copied during computation of the moves.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Efficiency
),
/** Use consequences moves (then). */
Then
(
"7.2.2",
773,
"Use consequences moves (then).",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Efficiency
),
/** Describes moves per piece. */
ForEachPiece
(
"7.2.3",
774,
"Describes moves per piece.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[]{ ConceptPurpose.AI },
true,
Concept.Efficiency
),
/** Use a (do ...) ludeme. */
DoLudeme
(
"7.2.4",
775,
"Use a (do ...) ludeme.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Efficiency
),
/** Use a (trigger ...) ludeme. */
Trigger
(
"7.2.5",
776,
"Use a (trigger ...) ludeme.",
ConceptType.Implementation,
ConceptDataType.BooleanData,
ConceptComputationType.Compilation,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Efficiency
),
/** Computed with playouts. */
PlayoutsPerSecond
(
"7.2.6",
777,
"Number of playouts computed per second.",
ConceptType.Implementation,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Efficiency
),
/** Computed with playouts. */
MovesPerSecond
(
"7.2.7",
778,
"Number of moves computed per second.",
ConceptType.Implementation,
ConceptDataType.DoubleData,
ConceptComputationType.Playout,
new ConceptPurpose[] { ConceptPurpose.AI },
true,
Concept.Efficiency
),
;
//-------------------------------------------------------------------------
/** The type of the game concepts. */
final ConceptType type;
/** The data type of the game concepts. */
final ConceptDataType dataType;
/** The computation type of the game concepts. */
final ConceptComputationType computationType;
/** The description of the concept. */
final String description;
/** The taxonomy node. */
final String taxonomy;
/** The list of the possible purposes of the concept. */
final ConceptPurpose[] purposes;
/** True if the concept is a leaf in the taxonomy. */
final boolean leaf;
/** The id of the concept. */
final int id;
/** The parent concept in the taxonomy. */
final Concept parent;
//-------------------------------------------------------------------------
/**
* To create a new concept.
*
* @param taxonomy The taxonomy node.
* @param description The description of the concept.
* @param type The type of the concept.
* @param dataType The type of the data.
* @param purposes The possible uses of the concept.
* @param leaf True if the concept is a leaf in the taxonomy.
* @param parent The parent node in the taxonomy.
*/
private Concept
(
final String taxonomy,
final int id,
final String description,
final ConceptType type,
final ConceptDataType dataType,
final ConceptComputationType computationType,
final ConceptPurpose[] purposes,
final boolean leaf,
final Concept parent
)
{
this.taxonomy = taxonomy;
this.description = description;
this.type = type;
this.purposes = purposes;
this.dataType = dataType;
this.computationType = computationType;
this.leaf = leaf;
this.id = id;
this.parent = parent;
}
//-------------------------------------------------------------------------
/**
* @return The taxonomy node.
*/
public String taxonomy()
{
return taxonomy;
}
/**
* @return The id of the concept.
*/
public int id()
{
return id; //this.ordinal() + 1;
}
/**
* @return The plain English description of the game concept.
*/
public String description()
{
return description;
}
/**
* @return The type of the concept.
*/
public ConceptType type()
{
return type;
}
/**
* @return The data type of the concept.
*/
public ConceptDataType dataType()
{
return dataType;
}
/**
* @return The computation type of the concept.
*/
public ConceptComputationType computationType()
{
return computationType;
}
/**
* @return The different possible purposes of the concept.
*/
public ConceptPurpose[] purposes()
{
return purposes;
}
/**
* @return True if the concept is a leaf in the taxonomy.
*/
public boolean isleaf()
{
return leaf;
}
/**
* @return The parent node in the taxonomy.
*/
public Concept parent()
{
return parent;
}
/**
* @return The concepts used by the portfolio (which are all except implementation ones, behavior ones and visual ones).
*/
public static Concept[] portfolioConcepts()
{
final List<Concept> portfolioConcepts = new ArrayList<Concept>();
for(Concept concept : Concept.values())
if(!concept.type().equals(ConceptType.Implementation) && !concept.type().equals(ConceptType.Behaviour) && !concept.type().equals(ConceptType.Visual))
portfolioConcepts.add(concept);
final Concept[] returnConcepts = new Concept[portfolioConcepts.size()];
for(int i = 0; i < returnConcepts.length; i++)
returnConcepts[i] = portfolioConcepts.get(i);
return returnConcepts;
}
/**
* @param description The description of the game.
* @return True if the game description involves the expected concepts.
*/
public static boolean isExpectedConcepts(final String description)
{
final Game game = (Game)Compiler.compileTest(new Description(description), false);
final BitSet booleanConcepts = game.computeBooleanConcepts();
final Map<Integer, String> nonBooleanConcepts = game.computeNonBooleanConcepts();
final Map<String, Double> startConcepts;
try {
startConcepts = game.startsConceptsWithoutRNG();
}
catch(Exception e) // In case the starting rules can not be applied, the concepts are not correct.
{
System.err.println("Start Concepts have a problem");
//e.printStackTrace();
return false;
}
final ArrayList<metadata.recon.concept.Concept> expectedConcepts = game.expectedConcepts();
for(metadata.recon.concept.Concept conceptMeta : expectedConcepts)
{
if(conceptMeta != null)
{
final Concept concept = conceptMeta.concept();
final double minValue = conceptMeta.minValue();
final double maxValue = conceptMeta.maxValue();
if(concept != null)
{
if(concept.dataType().equals(ConceptDataType.BooleanData))
{
if(minValue == 1)
{
if(!booleanConcepts.get(concept.id()))
return false;
}
else
{
if(booleanConcepts.get(concept.id()))
return false;
}
}
else if(concept.type.equals(ConceptType.Start))
{
final Double value = startConcepts.get(concept.name());
if(minValue > value.doubleValue() || value.doubleValue() > maxValue)
return false;
}
else
{
final String valuestr = nonBooleanConcepts.get(Integer.valueOf(concept.id()));
final Double value = Double.valueOf(valuestr);
if(minValue > value.doubleValue() || value.doubleValue() > maxValue)
return false;
}
}
}
}
return true;
}
} | 263,796 | 21.67661 | 152 | java |
Ludii | Ludii-master/Core/src/other/concept/ConceptComputationType.java | package other.concept;
/**
* The different concept computation types.
*
* @author Eric.Piette
*/
public enum ConceptComputationType
{
/** Compute during compilation. */
Compilation(1),
/** Compute thanks to playouts. */
Playout(2),
;
//-------------------------------------------------------------------------
/** The id of the concept computation type. */
final int id;
//-------------------------------------------------------------------------
/**
* To create a new concept computation type.
*
* @param id The id of the concept data type.
*/
private ConceptComputationType
(
final int id
)
{
this.id = id;
}
//-------------------------------------------------------------------------
/**
* @return The id of the concept computation type.
*/
public int id()
{
return this.id;
}
}
| 836 | 16.808511 | 76 | java |
Ludii | Ludii-master/Core/src/other/concept/ConceptDataType.java | package other.concept;
/**
* The different concept data types.
*
* @author Eric.Piette
*/
public enum ConceptDataType
{
/** Boolean Data. */
BooleanData(1),
/** Integer Data. */
IntegerData(2),
/** String Data. */
StringData(3),
/** Double Data. */
DoubleData(4),
;
//-------------------------------------------------------------------------
/** The id of the concept data type. */
final int id;
//-------------------------------------------------------------------------
/**
* To create a new concept data type.
*
* @param id The id of the concept data type.
*/
private ConceptDataType
(
final int id
)
{
this.id = id;
}
//-------------------------------------------------------------------------
/**
* @return The id of the concept data type.
*/
public int id()
{
return this.id;
}
}
| 846 | 14.981132 | 76 | java |
Ludii | Ludii-master/Core/src/other/concept/ConceptKeyword.java | package other.concept;
/**
* The keywords of the concepts.
*
* @author Eric.Piette
*/
public enum ConceptKeyword
{
/** To hop a neighbouring site. */
Hop(1, "Hop move concepts."),
/** Involves Enemy piece. */
Enemy(2, "Enemy piece or player."),
/** Tiling of the board. */
Tiling(3, "Tiling of the board."),
/** Shape of the board. */
Shape(4, "Shape of the board."),
/** Test a condition. */
Test(5, "Test a condition."),
/** Space concept. */
Space(6, "Spatial concepts."),
/** Moving a piece. */
MovePiece(7, "Moving a piece."),
/** Capture. */
Capture(8, "Capture concepts."),
/** Decision Move. */
Decision(9, "Decide to make a move."),
/** Line. */
Line(10, "Line concepts."),
/** Loop. */
Loop(11, "Loop concepts."),
/** Related to the legal moves. */
LegalMoves(12, "Legal moves concepts."),
/** Connected sites. */
Connected(13, "connected regions concepts"),
/** Group of sites. */
Group(14, "Group concepts"),
/** Related to Mancala games. */
Mancala(15, "Mancala games"),
/** Related to any move types. */
Move(16, "Move concepts."),
/** Related to a race. */
Race(18, "Race concepts."),
/** Related to a player. */
Player(19, "Player concepts."),
/** To slide a piece. */
Slide(20, "Slide move concepts."),
/** to step a piece. */
Step(21, "Step move concepts."),
/** Related to a empty site. */
Empty(22, "Empty site concepts."),
/** To leap a piece. */
Leap(23, "Leap move concepts."),
/** Related to a walk. */
Walk(24, "Walk concepts."),
/** To bet. */
Bet(25, "Bet move concepts."),
/** To vote. */
Vote(26, "Vote move concepts"),
/** Cards. */
Card(27, "Card components."),
/** Component. */
Component(28, "Component concepts."),
/** Domino. */
Domino(29, "Domino component concepts."),
/** Dice. */
Dice(30, "Dice component concepts."),
/** Related to stochastic. */
Stochastic(31, "Stochastic concepts."),
/** Related to hidden information. */
Hidden(32, "Hidden information concepts."),
/** Related to promotion. */
Promotion(33, "Promotion move concepts."),
/** Related to a puzzle. */
Puzzle(34, "Puzzle games."),
/** Related to a CSP. */
CSP(35, "Constraint Satisfaction problems."),
/** Container. */
Container(36, "Container concepts."),
/** Pattern. */
Pattern(37, "Pattern concepts."),
/** Path. */
Path(38, "Path concepts."),
/** Territory. */
Territory(39, "Territory concepts."),
/** Phase. */
Phase(40, "Play Phase concepts."),
/** LargePiece. */
LargePiece(41, "Large piece concepts."),
/** Tile. */
Tile(42, "Tile piece concepts."),
/** Score. */
Score(43, "Score concepts."),
/** Fill. */
Fill(44, "Fill region concepts."),
/** Rotation. */
Rotation(45, "Rotated pieces."),
/** Team. */
Team(46, "Team concepts."),
/** Track. */
Track(47, "Track concepts."),
/** Push. */
Push(48, "Push move concepts."),
/** The line of sight. */
LineOfSight(49, "Line of sight concepts."),
/** Stack. */
Stack(50, "Stack concepts."),
/** State. */
State(51, "Game state concepts."),
/** Graph. */
Graph(52, "Graph concepts."),
/** Flip. */
Flip(53, "Flip move concepts."),
/** Swap. */
Swap(54, "Swap move concepts."),
/** Repetition. */
Repetition(55, "Repetition state concepts."),
/** Amount. */
Amount(56, "Amount data concepts."),
/** Random. */
Random(57, "Random concepts."),
/** Placement. */
Placement(58, "Initial Placement starting rules."),
/** Hint. */
Hint(59, "Board with hints."),
/** Reach. */
Reach(60, "Reach a region concepts."),
/** Chess. */
Chess(61, "Chess games."),
/** Style of the board. */
Style(62, "Style of the board."),
/** Match. */
Match(63, "Match concepts."),
/** Pot. */
Pot(64, "Pot concepts."),
/** Direction. */
Direction(65, "Direction concepts."),
/** Piece Value. */
PieceValue(66, "Piece value concepts."),
/** Relative Direction. */
RelativeDirection(67, "Relative Direction concepts."),
/** Absolute Direction. */
AbsoluteDirection(68, "Absolute Direction concepts."),
/** Piece Count. */
PieceCount(69, "Piece count concepts."),
/** Column. */
Column(70, "Column concepts."),
/** Row. */
Row(71, "Row concepts."),
/** Board. */
Board(72, "Board concepts."),
/** Distance. */
Distance(73, "Distance concepts."),
/** Shogi. */
Shogi(74, "Shogi games."),
/** Xiangqi. */
Xiangqi(75, "Xiangqi games."),
/** Algebra. */
Algebra(76, "Algebra."),
/** Arithmetic. */
Arithmetic(77, "Arithmetic."),
/** Algorithmic. */
Algorithmic(78, "Algorithmic."),
/** Logical Operators. */
LogicalOperator(79, "Logical Operators."),
/** Comparison Operators. */
ComparisonOperator(80, "Comparison Operators."),
/** Set Operators. */
SetOperator(81, "Set Operators."),
/** Involves friend pieces. */
Friend(82, "Involves friend pieces."),
;
//-------------------------------------------------------------------------
/** The id of the keyword. */
final int id;
/** The description of the concept keyword. */
final String description;
//-------------------------------------------------------------------------
/**
* To create a new keyword.
*
* @param id The id of the keyword.
*/
private ConceptKeyword
(
final int id,
final String description
)
{
this.id = id;
this.description = description;
}
//-------------------------------------------------------------------------
/**
* @return The id of the keyword.
*/
public int id()
{
return this.id;
}
/**
* @return The plain English description of the game concept keyword.
*/
public String description()
{
return description;
}
}
| 5,637 | 17.983165 | 76 | java |
Ludii | Ludii-master/Core/src/other/concept/ConceptPurpose.java | package other.concept;
/**
* The different possible uses of a game concept.
*
* @author Eric.Piette
*/
public enum ConceptPurpose
{
/** Can be used for AI. */
AI(1),
/** Can be used for reconstruction. */
Reconstruction(2),
;
//-------------------------------------------------------------------------
/** The id of the concept purpose. */
final int id;
//-------------------------------------------------------------------------
/**
* To create a new concept purpose.
*
* @param id The id of the concept purpose.
*/
private ConceptPurpose
(
final int id
)
{
this.id = id;
}
//-------------------------------------------------------------------------
/**
* @return The id of the concept purpose.
*/
public int id()
{
return this.id;
}
}
| 789 | 16.173913 | 76 | java |
Ludii | Ludii-master/Core/src/other/concept/ConceptType.java | package other.concept;
/**
* The different types of the concepts.
*
* @author Eric.Piette
*/
public enum ConceptType
{
/** The properties of the game. */
Properties(1),
/** The concepts related to the equipment. */
Equipment(2),
/** The concepts related to the meta rules. */
Meta(3),
/** The concepts related to the starting rules. */
Start(4),
/** The concepts related to the play rules. */
Play(5),
/** The concepts related to the ending rules. */
End(6),
/** The concepts related to the metrics (behaviour). */
Behaviour(7),
/** The concepts related to the implementation. */
Implementation(8),
/** The concepts related to the visuals. */
Visual(9),
/** The concepts related to the Math. */
Math(10),
/** The concepts related to the containers. */
Container(11),
/** The concepts related to the components. */
Component(12)
;
//-------------------------------------------------------------------------
/** The id of the concept type. */
final int id;
//-------------------------------------------------------------------------
/**
* To create a new concept type.
*
* @param id The id of the concept type.
*/
private ConceptType
(
final int id
)
{
this.id = id;
}
//-------------------------------------------------------------------------
/**
* @return The id of the concept type.
*/
public int id()
{
return this.id;
}
}
| 1,413 | 17.363636 | 76 | java |
Ludii | Ludii-master/Core/src/other/concept/EndConcepts.java | package other.concept;
import java.util.BitSet;
import game.Game;
import game.functions.booleans.BooleanFunction;
import game.rules.end.Result;
import game.types.play.ResultType;
import game.types.play.RoleType;
import main.Constants;
import other.context.Context;
/**
* Utilities class used to compute the end concepts from the concepts of the
* condition which is true.
*
* @author Eric.Piette
*/
public class EndConcepts
{
/**
* @param condition The condition
* @param context The context
* @param game The game
* @param result The result
* @return The ending concepts
*/
public static BitSet get
(
final BooleanFunction condition,
final Context context,
final Game game,
final Result result
)
{
final ResultType resultType = (result != null) ? result.result() : null;
final RoleType who = (result != null) ? result.who() : null;
final BitSet condConcepts = (context == null) ? condition.concepts(game) : condition.stateConcepts(context);
final BitSet endConcepts = new BitSet();
// ------------------------------------------- Legal Moves End ----------------------------------------------------
if (condConcepts.get(Concept.NoMoves.id()))
{
endConcepts.set(Concept.NoMovesEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.NoMovesWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.NoMovesLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.NoMovesLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.NoMovesWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.NoMovesDraw.id(), true);
}
}
// ------------------------------------------- Time End ----------------------------------------------------
if (condConcepts.get(Concept.ProgressCheck.id()))
{
endConcepts.set(Concept.NoProgressEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.NoProgressWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.NoProgressLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.NoProgressLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.NoProgressWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.NoProgressDraw.id(), true);
}
}
// ------------------------------------------- Scoring End ----------------------------------------------------
// Scoring End
if (condConcepts.get(Concept.Scoring.id()))
{
endConcepts.set(Concept.ScoringEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.ScoringWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.ScoringLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.ScoringLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.ScoringWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.ScoringDraw.id(), true);
}
}
// ------------------------------------------- Race End ----------------------------------------------------
// No Own Pieces End
if (condConcepts.get(Concept.NoPieceMover.id()))
{
endConcepts.set(Concept.NoOwnPiecesEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.NoOwnPiecesWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.NoOwnPiecesLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.NoOwnPiecesLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.NoOwnPiecesWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.NoOwnPiecesDraw.id(), true);
}
if(result.concepts(game).get(Concept.Scoring.id))
endConcepts.set(Concept.NoOwnPiecesWin.id(), true);
}
// Fill End
if (condConcepts.get(Concept.Fill.id()))
{
endConcepts.set(Concept.FillEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.FillLoss.id(), true);
else if(who.equals(RoleType.Mover) || who.owner() != Constants.NOBODY)
endConcepts.set(Concept.FillWin.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.FillLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.FillWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.FillDraw.id(), true);
}
}
// Reach End
if (condConcepts.get(Concept.Contains.id()))
{
endConcepts.set(Concept.ReachEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.ReachWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.ReachLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.ReachLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.ReachWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.ReachDraw.id(), true);
}
}
// ---------------------------------------------- Capture End ------------------------------------------------
// Checkmate end.
if (condConcepts.get(Concept.CanNotMove.id()) && condConcepts.get(Concept.Threat.id()))
{
endConcepts.set(Concept.Checkmate.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.CheckmateWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.CheckmateLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.CheckmateLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.CheckmateWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.CheckmateDraw.id(), true);
}
}
// No Target piece End
if (condConcepts.get(Concept.NoTargetPiece.id()))
{
endConcepts.set(Concept.NoTargetPieceEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.NoTargetPieceWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.NoTargetPieceLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.NoTargetPieceLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.NoTargetPieceWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.NoTargetPieceDraw.id(), true);
}
}
// Eliminate Pieces End
if (condConcepts.get(Concept.NoPieceNext.id()) || condConcepts.get(Concept.CountPiecesNextComparison.id()) ||
(condConcepts.get(Concept.NoPiece.id()) && !condConcepts.get(Concept.NoPieceMover.id())))
{
endConcepts.set(Concept.EliminatePiecesEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.EliminatePiecesWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.EliminatePiecesLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.EliminatePiecesLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.EliminatePiecesWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.EliminatePiecesDraw.id(), true);
}
}
//----------------------------------- Space End -----------------------------------------
// Line End
if (condConcepts.get(Concept.Line.id()))
{
endConcepts.set(Concept.LineEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.LineWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.LineLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.LineLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.LineWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.LineDraw.id(), true);
}
}
// Connection End
if (condConcepts.get(Concept.Connection.id()))
{
endConcepts.set(Concept.ConnectionEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.ConnectionWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.ConnectionLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.ConnectionLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.ConnectionWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.ConnectionDraw.id(), true);
}
}
// Group End
if (condConcepts.get(Concept.Group.id()))
{
endConcepts.set(Concept.GroupEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.GroupWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.GroupLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.GroupLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.GroupWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.GroupDraw.id(), true);
}
}
// Loop End
if (condConcepts.get(Concept.Loop.id()))
{
endConcepts.set(Concept.LoopEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.LoopWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.LoopLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.LoopLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.LoopWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.LoopDraw.id(), true);
}
}
// Pattern End
if (condConcepts.get(Concept.Pattern.id()))
{
endConcepts.set(Concept.PatternEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.PatternWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.PatternLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.PatternLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.PatternWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.PatternDraw.id(), true);
}
}
// Territory End
if (condConcepts.get(Concept.Territory.id()))
{
endConcepts.set(Concept.TerritoryEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.TerritoryWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.TerritoryLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.TerritoryLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.TerritoryWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.TerritoryDraw.id(), true);
}
}
// PathExtent End
if (condConcepts.get(Concept.PathExtent.id()))
{
endConcepts.set(Concept.PathExtentEnd.id(), true);
if(resultType != null && who != null)
{
if(resultType.equals(ResultType.Win))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.PathExtentWin.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.PathExtentLoss.id(), true);
}
else if(resultType.equals(ResultType.Loss))
{
if(who.equals(RoleType.Mover))
endConcepts.set(Concept.PathExtentLoss.id(), true);
else if(who.equals(RoleType.Next) && game.players().count() == 2)
endConcepts.set(Concept.PathExtentWin.id(), true);
}
else if(resultType.equals(ResultType.Draw))
endConcepts.set(Concept.PathExtentDraw.id(), true);
}
}
//----------------------------- Misere -------------------------------------------------
if(game.players().count() == 2)
{
if(resultType != null && who != null)
{
if (
(resultType.equals(ResultType.Win) && who.equals(RoleType.Next))
||
resultType.equals(ResultType.Loss) && who.equals(RoleType.Mover)
)
endConcepts.set(Concept.Misere.id(), true);
}
}
if (result != null)
endConcepts.or(result.concepts(game));
return endConcepts;
}
}
| 15,849 | 32.158996 | 117 | java |
Ludii | Ludii-master/Core/src/other/context/Context.java | package other.context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.rng.core.source64.SplitMix64;
import game.Game;
import game.equipment.Equipment;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.equipment.container.board.Board;
import game.equipment.container.board.Track;
import game.equipment.container.other.Dice;
import game.functions.ints.IntFunction;
import game.functions.ints.board.Id;
import game.functions.region.RegionFunction;
import game.match.Subgame;
import game.players.Player;
import game.rules.Rules;
import game.rules.end.End;
import game.rules.play.moves.Moves;
import game.types.play.RoleType;
import game.util.equipment.Region;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TIntIntHashMap;
import main.Constants;
import main.math.BitTwiddling;
import metadata.Metadata;
import other.GameLoader;
import other.UndoData;
import other.model.MatchModel;
import other.model.Model;
import other.move.Move;
import other.state.State;
import other.state.container.ContainerState;
import other.topology.Topology;
import other.trial.Trial;
/**
* Context for generating moves during playouts.
*
* @author cambolbro and Eric Piette
*/
public class Context
{
//-------------------------------------------------------------------------
/**
* A single RNG which is shared by all Context objects created through
* copy-constructor.
*
* Such Context objects should only be created by search algorithms such as
* MCTS, and for those we do not need reproducibility.
*/
private static SplitMix64 sharedRNG = new SplitMix64();
//-------------------------------------------------------------------------
/** Reference to controlling game object. */
private final Game game;
/** Reference to "parent" Context of match we're in. Will be null if this is the top-level Context. */
private Context parentContext;
/** Reference to active subcontext. Will be null if this is not a context for a Match */
private Context subcontext;
/** Current game state. */
protected transient State state;
/** Index for our current subgame (will always be 0 for non-Matches) */
private int currentSubgameIdx = 0;
/** Our control flow models (one per phase) */
private Model[] models;
/** Our Trial. */
private Trial trial;
/**
* List of trials that have already been completed.
*
* Will only be non-empty for Matches. TODO should probably just have it be null for instances then
*/
private List<Trial> completedTrials;
//-------------------------------------------------------------------------
/** RNG object used for any rules / actions / etc. in this context */
private SplitMix64 rng;
//-------------------------------------------------------------------------
/** Data used to evaluate ludemes */
private EvalContext evalContext = new EvalContext();
//-------------------------------------------------------------------------
/** Require for loop */
//private boolean ringFlagCalled = false;
/** Used in case of recursive called for some ludeme. */
private boolean recursiveCalled = false;
/**
* Data used during the computation of the ranking in case of multi results in
* the same turn. (we need a better name for that variable but I am too tired to
* find one ^^) TODO officially I guess this should actually be in EvalContext?
*/
private int numLossesDecided = 0;
/** Same as above, but for wins */ // TODO officially I guess this should actually be in EvalContext?
private int numWinsDecided = 0;
// WARNING: if we have a State object, that object should perform modifications of the below fields for us!
// this allows it to also update Zobrist hash!
/** Scores per player. Game scores if this is a trial for just a game, match scores if it's a trial for a Match */
private int[] scores;
/**
* Payoffs per player. Game payoff if this is a trial for just a game, match
* scores if it's a trial for a Match
*/
private double[] payoffs;
/** For every player, a bit indicating whether they are active */
private int active = 0;
// WARNING: if we have a State object, that object should perform modifications of the above fields for us!
// this allows it to also update Zobrist hash!
/** List of players who've already won */
private TIntArrayList winners;
/** List of players who've already lost */
private TIntArrayList losers;
/** Tells us whether we've ever called game.start() with this context */
private boolean haveStarted = false;
/** The states of each site where is a die */
final TIntIntHashMap diceSiteStates;
//-------------------------------------------------------------------------
/** Lock for Game methods that should not be executed in parallel on the same Context object. */
private transient ReentrantLock lock = new ReentrantLock();
//-------------------------------------------------------------------------
/**
* Constructs a new Context for given game and trial
*
* @param game
* @param trial
*/
public Context(final Game game, final Trial trial)
{
this(game, trial, new SplitMix64(), null);
}
/**
* Constructor
*
* @param game
* @param trial
* @param rng
* @param parentContext
*/
private Context(final Game game, final Trial trial, final SplitMix64 rng, final Context parentContext)
{
this.game = game;
this.parentContext = parentContext;
diceSiteStates = new TIntIntHashMap();
this.trial = trial;
completedTrials = new ArrayList<Trial>(1);
this.rng = rng;
if (game.hasSubgames())
{
// This is a Context for a Match
state = null;
final Game subgame = game.instances()[0].getGame();
subcontext = new Context(subgame, new Trial(subgame), rng, this); // plug in the same RNG for complete Match
models = new Model[1]; // Assuming no phases in matches
models[0] = new MatchModel();
}
else
{
// This is a Context for just a single Game
state = game.stateReference() != null ? new State(game.stateReference()) : null;
subcontext = null;
models = new Model[game.rules().phases().length];
for (int i = 0; i < game.rules().phases().length; ++i)
{
if (game.rules().phases()[i].mode() != null)
models[i] = game.rules().phases()[i].mode().createModel();
else
models[i] = game.mode().createModel();
}
}
if (game.requiresScore())
scores = new int[game.players().count() + 1];
else
scores = null;
if (game.requiresPayoff())
payoffs = new double[game.players().count() + 1];
else
payoffs = null;
for (int p = 1; p <= game.players().count(); ++p)
setActive(p, true);
winners = new TIntArrayList(game.players().count());
losers = new TIntArrayList(game.players().count());
}
/**
* Copy constructor, which creates a deep copy of the Trial (except for ignoring
* its history), but only copies the reference to the game. Intended for search
* algorithms, which can safely apply moves on these copies without modifying
* the original context.
*
* @param other
*/
public Context(final Context other)
{
this(other, null);
}
/**
* @param other
* @return A copy of the given other context, with a new RNG that has
* a copied interal state (i.e., seed etc.)
*/
public static Context copyWithSeed(final Context other)
{
final Context copy = new Context(other, null, new SplitMix64());
copy.rng.restoreState(other.rng.saveState());
return copy;
}
/**
* Copy constructor
*
* @param other
* @param otherParentCopy Copy of the parent context of the given other
*/
private Context(final Context other, final Context otherParentCopy)
{
// Pass shared RNG, don't expect to need reproducibility
this(other, otherParentCopy, sharedRNG);
}
/**
* Copy constructor
*
* @param other
* @param otherParentCopy Copy of the parent context of the given other
* @param rng The RNG to use for the copy
*/
private Context(final Context other, final Context otherParentCopy, final SplitMix64 rng)
{
other.getLock().lock();
try
{
game = other.game;
parentContext = otherParentCopy;
diceSiteStates = new TIntIntHashMap();
state = copyState(other.state);
trial = copyTrial(other.trial);
// WARNING: Currently just copying the completed trials by reference here
// TODO: Would actually want these trials to become immutable somehow...
// Would add a level of safety but is not critical (to do when time permits).
completedTrials = new ArrayList<Trial>(other.completedTrials);
this.rng = rng;
subcontext = other.subcontext == null ? null : new Context(other.subcontext, this);
currentSubgameIdx = other.currentSubgameIdx;
models = new Model[other.models.length];
for (int i = 0; i < models.length; ++i)
{
models[i] = other.models[i].copy();
}
evalContext = new EvalContext(other.evalContext());
numLossesDecided = other.numLossesDecided;
numWinsDecided = other.numWinsDecided;
//ringFlagCalled = other.ringFlagCalled;
recursiveCalled = other.recursiveCalled;
if (other.scores != null)
scores = Arrays.copyOf(other.scores, other.scores.length);
else
scores = null;
if (other.payoffs != null)
payoffs = Arrays.copyOf(other.payoffs, other.payoffs.length);
else
payoffs = null;
active = other.active;
winners = new TIntArrayList(other.winners);
losers = new TIntArrayList(other.losers);
}
finally
{
other.getLock().unlock();
}
}
/**
* @return The object used to evalutate the ludemes.
*/
public EvalContext evalContext()
{
return evalContext;
}
/**
* Method for copying game states. NOTE: we override this in TempContext for
* copy-on-write states.
*
* @param otherState
* @return Copy of given game state.
*/
@SuppressWarnings("static-method")
protected State copyState(final State otherState)
{
return otherState == null ? null : new State(otherState);
}
/**
* Method for copying Trials. NOTE: we override this in TempContext
* for Trial copies with MoveSequences that are allowed to be
* invalidated.
*
* @param otherTrial
* @return Copy of given Trial
*/
@SuppressWarnings("static-method")
protected Trial copyTrial(final Trial otherTrial)
{
return new Trial(otherTrial);
}
/**
* NOTE: we don't really need this method to exist in Java, but this is
* much more convenient to call from Python than directly calling the
* copy constructor.
*
* @return Deep copy of this context.
*/
public Context deepCopy()
{
return new Context(this, null);
}
//-------------------------------------------------------------------------
/**
* Reset this Context to play again from the start.
*/
public void reset()
{
// **
// ** Don't clear state here. Calling function should copy
// ** the reference state stored in the Game object.
// **
if (state != null)
state.resetStateTo(game.stateReference(), game);
trial.reset(game);
if (scores != null)
Arrays.fill(scores, 0);
if (payoffs != null)
Arrays.fill(payoffs, 0);
active = 0;
for (int p = 1; p <= game.players().count(); ++p)
setActive(p, true);
winners.reset();
losers.reset();
haveStarted = true;
if (subcontext != null)
{
final Game subgame = game.instances()[0].getGame();
subcontext = new Context(subgame, new Trial(subgame), rng, this); // plug in the same RNG for complete Match
completedTrials.clear();
}
currentSubgameIdx = 0;
}
//-------------------------------------------------------------------------
/**
* To set the active bits.
* @param active For each player a bit to indicate if a player is active.
*/
public void setActive(final int active)
{
this.active = active;
}
/**
* @param who
* @return Whether player is active.
*/
public boolean active(final int who)
{
return (active & (1 << (who - 1))) != 0;
}
/**
* @return If only one player is active, we return the id of that player. Otherwise 0
*/
public int onlyOneActive()
{
if (BitTwiddling.exactlyOneBitSet(active))
return BitTwiddling.lowBitPos(active) + 1;
return 0;
}
/**
* @return if only one team is active, we return the id of that team. Otherwise 0
*/
public int onlyOneTeamActive()
{
final TIntArrayList activePlayers = new TIntArrayList();
for (int i = 1; i <= game.players().count(); i++)
if (active(i))
activePlayers.add(i);
final TIntArrayList activeTeam = new TIntArrayList();
for (int i = 0; i < activePlayers.size(); i++)
{
final int pid = activePlayers.getQuick(i);
final int tid = state.getTeam(pid);
if (!activeTeam.contains(tid))
activeTeam.add(tid);
}
if (activeTeam.size() != 1)
return 0;
return activeTeam.getQuick(0);
}
/**
* To add a winner in the list of winners.
* NOTE: important to call this AFTER calling computeNextWinRank(), if
* the intention is to also call that to compute the rank for this player
*
* @param idPlayer
*/
public void addWinner(final int idPlayer)
{
winners.add(idPlayer);
}
/**
* To add a loser in the list of losers.
* @param idPlayer
*/
public void addLoser(final int idPlayer)
{
losers.add(idPlayer);
}
/**
* @return The number of winners.
*/
public int numWinners()
{
return winners.size();
}
/**
* @return The number of losers.
*/
public int numLosers()
{
return losers.size();
}
/**
* @return The winners.
*/
public TIntArrayList winners()
{
return winners;
}
/**
* @return The losers.
*/
public TIntArrayList losers()
{
return losers;
}
/**
* @return The array of scores.
*/
public int[] scores()
{
return this.scores;
}
/**
* @param pid
* @return Current score for player with given Player ID
*/
public int score(final int pid)
{
return scores[pid];
}
/**
* @return The array of payoffs.
*/
public double[] payoffs()
{
return this.payoffs;
}
/**
* @param pid
* @return Current payoff for player with given Player ID
*/
public double payoff(final int pid)
{
return payoffs[pid];
}
/**
* Sets the payoff for the given player
*
* @param pid Player ID
* @param payoffToSet New payoff
*/
public void setPayoff(final int pid, final double payoffToSet)
{
if (state != null) // Let State do it so it can also update Zobrist hash!
state.setPayoff(pid, payoffToSet, payoffs);
else
payoffs[pid] = payoffToSet;
}
/**
* Sets the score for the given player
* @param pid Player ID
* @param scoreToSet New score
*/
public void setScore(final int pid, final int scoreToSet)
{
if (state != null) // Let State do it so it can also update Zobrist hash!
state.setScore(pid, scoreToSet, scores);
else
scores[pid] = scoreToSet;
}
/**
* Sets a player to be active or inactive.
*
* @param who
* @param newActive
*/
public void setActive(final int who, final boolean newActive)
{
if (state != null) // Let State do it so it can also update Zobrist hash!
{
active = state.setActive(who, newActive, active);
}
else
{
final int whoBit = (1 << (who - 1));
final boolean wasActive = (active & whoBit) != 0;
if (wasActive && !newActive)
active &= ~whoBit;
else if (!wasActive && newActive)
active |= whoBit;
}
}
/**
* @return Whether any player is active
*/
public boolean active()
{
return active != 0;
}
/**
* Set all players to "inactive".
*/
public void setAllInactive()
{
active = 0;
if (state != null)
state.updateHashAllPlayersInactive();
}
/**
* @return The number of active players.
*/
public int numActive()
{
return Integer.bitCount(active);
}
/**
* @return Next rank to assign to players who obtain a win now.
*/
public double computeNextWinRank()
{
final int numWinRanksTaken = numWinners();
return numWinRanksTaken + 1;
}
/**
* @return Next rank to assign to players who obtain a loss now.
*/
public double computeNextLossRank()
{
final int numRanks = trial.ranking().length - 1;
final int numLossRanksTaken = numLosers();
return numRanks - numLossRanksTaken;
}
/**
* @return Rank to assign to remaining players if we were to obtain a draw now.
*/
public double computeNextDrawRank()
{
return (numActive() + 1) / 2.0 + (numWinners());
}
//-------------------------------------------------------------------------
/**
* @return Game.
*/
public Game game()
{
return game;
}
/**
* @return True if game being played is a Match.
*/
public boolean isAMatch()
{
return game.hasSubgames();
}
/**
* @return Our control flow model.
*/
public Model model()
{
if (models.length == 1)
return models[0];
else
return models[state.currentPhase(state.mover())];
}
/**
* @return Shortcut reference to list of players.
*/
public List<Player> players()
{
return game.players().players();
}
/**
* @return Trial.
*/
public Trial trial()
{
return trial;
}
/**
* @return Current subcontext in the case of Matches. Will be null if this is
* already a context for just an instance.
*/
public Context subcontext()
{
return subcontext;
}
/**
* @return The context for the current instance. May just be this context if it's
* already not a context for a Match.
*/
public Context currentInstanceContext()
{
Context context = this;
while (context.isAMatch())
{
context = context.subcontext();
}
return context;
}
/**
* @return Random Number Generator for this context.
*/
public SplitMix64 rng()
{
return rng;
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @return Team array.
*/
public int[] team()
{
return evalContext.team();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @param team The team..
*/
public void setTeam(int[] team)
{
evalContext.setTeam(team);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @return From index.
*/
public int from()
{
return evalContext.from();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @param val The value.
*/
public void setTrack(final int val)
{
evalContext.setTrack(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @return track index.
*/
public int track()
{
return evalContext.track();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @param val
*/
public void setFrom(final int val)
{
evalContext.setFrom(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
* @return To index.
*/
public int to()
{
return evalContext.to();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @param val
*/
public void setTo(final int val)
{
evalContext.setTo(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
* @return between index.
*/
public int between()
{
return evalContext.between();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls To set the
* between value.
*
* @param val
*/
public void setBetween(final int val)
{
evalContext.setBetween(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @return player index.
*/
public int player()
{
return evalContext.player();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls To set the
* player value.
*
* @param val
*/
public void setPlayer(final int val)
{
evalContext.setPlayer(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
* @return dieValue.
*/
public int pipCount()
{
return evalContext.pipCount();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @param val
*/
public void setPipCount(final int val)
{
evalContext.setPipCount(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
* @return Level index.
*/
public int level()
{
return evalContext.level();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @param val
*/
public void setLevel(final int val)
{
evalContext.setLevel(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
* @return Hint index.
*/
public int hint()
{
return evalContext.hint();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @param val
*/
public void setHint(final int val)
{
evalContext.setHint(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
* @return Edge index.
*/
public int edge()
{
return evalContext.edge();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @param val
*/
public void setEdge(final int val)
{
evalContext.setEdge(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @return site index.
*/
public int site()
{
return evalContext.site();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls To set the site
* value.
*
* @param val
*/
public void setSite(final int val)
{
evalContext.setSite(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @return value.
*/
public int value()
{
return evalContext.value();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls To set the
* value.
*
* @param val
*/
public void setValue(final int val)
{
evalContext.setValue(val);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @return A region iterated.
*/
public Region region()
{
return evalContext.region();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* To set the region iterated.
*
* @param region The region.
*/
public void setRegion(final Region region)
{
evalContext.setRegion(region);
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* @return The hint region iterated in the
* game.functions.booleans.deductionPuzzle.ForEach or called by (sites
* Hint).
*/
public RegionFunction hintRegion()
{
return evalContext.hintRegion();
}
/**
* WARNING: Should NOT be used outside of Ludemes' eval() calls
*
* To set the hint region when we iterate them in
* game.functions.booleans.deductionPuzzle.ForEach.
*
* @param region The region.
*/
public void setHintRegion(final RegionFunction region)
{
evalContext.setHintRegion(region);
}
/**
* @return Number of times we applied loss End result in a single apply()
*/
public int numLossesDecided()
{
return numLossesDecided;
}
/**
* @return Number of times we applied win End result in a single apply()
*/
public int numWinsDecided()
{
return numWinsDecided;
}
/**
* Set the number of times we applied loss End result in a single ForEach apply()
*
* @param numLossesDecided
*/
public void setNumLossesDecided(final int numLossesDecided)
{
this.numLossesDecided = numLossesDecided;
}
/**
* Set the number of times we applied win End result in a single ForEach apply()
*
* @param numWinsDecided
*/
public void setNumWinsDecided(final int numWinsDecided)
{
this.numWinsDecided = numWinsDecided;
}
/**
* @return Tells us whether we've ever called game.start() with this context
*/
public boolean haveStarted()
{
return haveStarted;
}
//-------------------------------------------------------------------------
// /**
// * @return The ring flag.
// */
// public boolean ringFlagCalled()
// {
// return ringFlagCalled;
// }
//
// /**
// * Set the ring flag.
// *
// * @param called
// */
// public void setRingFlagCalled(final boolean called)
// {
// ringFlagCalled = called;
// }
/**
* @return Reference to containers list.
*/
public Container[] containers()
{
if (subcontext != null)
return subcontext.containers();
return game.equipment().containers();
}
/**
* @return Reference to components list.
*/
public Component[] components()
{
if (subcontext != null)
return subcontext.components();
return game.equipment().components();
}
/**
* @return Reference to track list.
*/
public List<Track> tracks()
{
if (subcontext != null)
return subcontext.tracks();
return game.board().tracks();
}
/**
* @return Reference to region list.
*/
public game.equipment.other.Regions[] regions()
{
if (subcontext != null)
return subcontext.regions();
return game.equipment().regions();
}
/**
* @return Reference to the containerId.
*/
public int[] containerId()
{
if (subcontext != null)
return subcontext.containerId();
return game.equipment().containerId();
}
/**
* @return Reference to the sitesFrom.
*/
public int[] sitesFrom()
{
if (subcontext != null)
return subcontext.sitesFrom();
return game.equipment().sitesFrom();
}
/**
* @return Reference to main board.
*/
public Board board()
{
if (subcontext != null)
return subcontext.board();
return game.board();
}
/**
* @return Reference to main board.
*/
public Rules rules()
{
if (subcontext != null)
return subcontext.rules();
return game.rules();
}
/**
* @return Metadata of game we're currently playing in this context.
*/
public Metadata metadata()
{
if (subcontext != null)
return subcontext.metadata();
return game.metadata();
}
/**
* @return Equipment of the game we're currently playing in this context.
*/
public Equipment equipment()
{
if (subcontext != null)
return subcontext.equipment();
return game.equipment();
}
/**
* @return The dice hands of the game we're currently playing in this context
*/
public List<Dice> handDice()
{
if (subcontext != null)
return subcontext.handDice();
return game.handDice();
}
/**
* @return Reference to main board graph.
*/
public Topology topology()
{
if (subcontext != null)
return subcontext.topology();
return game.board().topology();
}
/**
* @return True if the game we're currently player has any containers owned by the Shared player
*/
public boolean hasSharedPlayer()
{
if (subcontext != null)
return subcontext.hasSharedPlayer();
return game.hasSharedPlayer();
}
/**
* @return Number of distinct containers in the game we're currently playing.
*/
public int numContainers()
{
if (subcontext != null)
return subcontext.numContainers();
return game.numContainers();
}
/**
* @return Number of distinct components in the game we're currently playing.
*/
public int numComponents()
{
if (subcontext != null)
return subcontext.numComponents();
return game.numComponents();
}
/**
* @return Reference to current state.
*/
public State state()
{
if (subcontext != null)
return subcontext.state();
return state;
}
/**
* Helper method to return player name for given player index. Takes into
* account whether or not player roles have been swapped in the current state.
*
* @param p
* @return Player name
*/
public String getPlayerName(final int p)
{
if (subcontext != null)
return subcontext.getPlayerName(p);
return game.players().players().get(state().playerToAgent(p)).name();
}
//-------------------------------------------------------------------------
/**
* @return Whether all players passed in the last round.
*/
public boolean allPass()
{
if (subcontext != null)
return subcontext.allPass();
final int numPlayers = game.players().count();
final Iterator<Move> reverseMoves = trial.reverseMoveIterator();
int lastMover = state().mover();
if (numPlayers == 1)
return trial.lastMove().isPass();
boolean passMove = false;
int countMovesTurn = 0;
for (int i = 1; i <= numPlayers; i++) // we look the previous turn of each player.
{
while (true) // We need to check each previous turn of each player.
{
if (!reverseMoves.hasNext()) // Not enough moves to check if all players passed.
{
if (!passMove) // First move of the next turn was not a pass.
return false;
return true;
}
if (countMovesTurn > 1) // we look only for full round with only a pass move.
return false;
final Move move = reverseMoves.next();
if (lastMover != move.mover()) // That's a new turn.
{
if (!passMove) // First move of the next turn was not a pass.
return false;
lastMover = move.mover(); // get the mover of this new turn.
countMovesTurn = 0; // we init the counter.
passMove = move.isPass(); // we init the test on passMove
break;
}
countMovesTurn++;
passMove = move.isPass();
}
}
return true;
}
//-------------------------------------------------------------------------
/**
* @return Our direct parent context (null if we're already the top-level context)
*/
public Context parentContext()
{
return parentContext;
}
/**
* @return List of completed trials within this context.
*/
public List<Trial> completedTrials()
{
return completedTrials;
}
//-------------------------------------------------------------------------
/**
* @param role
* @return A list of the index of the player in function of the role type.
*/
public TIntArrayList convertRole(final RoleType role)
{
TIntArrayList indexPlayer = new TIntArrayList();
final int moverId = state.mover();
if (role == RoleType.Enemy)
{
indexPlayer = game.players().players().get(moverId).enemies();
}
else if (role == RoleType.Shared)
{
for (int i = 1; i <= game.players().count(); i++)
indexPlayer.add(i);
}
else
{
indexPlayer.add(new Id(null, role).eval(this));
}
return indexPlayer;
}
/**
* @param cid
* @return The ItemStateContainer of the container cid.
*/
public ContainerState containerState(final int cid)
{
if (subcontext != null)
return subcontext.containerState(cid);
return cid < state().containerStates().length ? state().containerStates()[cid] : null;
}
/**
* @return the recursiveCalled value
*/
public boolean recursiveCalled()
{
return recursiveCalled;
}
/**
* To set the value of the recursiveCalled
*
* @param value
*/
public void setRecursiveCalled(final boolean value)
{
recursiveCalled = value;
}
/**
* @return The from location of the first move of the current turn.
*/
public int fromStartOfTurn()
{
if (trial.numMoves() == 0)
return Constants.UNDEFINED;
final Iterator<Move> reverseMoves = trial.reverseMoveIterator();
final int mover = state.mover();
Move currMove = reverseMoves.next();
// If the current state corresponds to a new turn the from is not defined.
if (mover != currMove.mover())
return Constants.UNDEFINED;
int fromStartOfTurn = currMove.fromNonDecision();
while (reverseMoves.hasNext())
{
currMove = reverseMoves.next();
if (currMove.mover() != mover)
break;
fromStartOfTurn = currMove.fromNonDecision();
}
return fromStartOfTurn;
}
/**
* @return Index of our current Subgame (always 0 for non-Match games).
*/
public int currentSubgameIdx()
{
return currentSubgameIdx;
}
/**
* Advance this context to the next instance in a multi-game match.
*/
public void advanceInstance()
{
final int numPlayers = trial.ranking().length - 1;
final Subgame currentInstance = game.instances()[currentSubgameIdx];
for (int p = 1; p <= numPlayers; p++)
{
final int currentMatchScore = score(p);
final int scoreToAdd;
if (currentInstance.result() != null && subcontext.winners.contains(p))
{
scoreToAdd = currentInstance.result().eval(subcontext);
}
else
{
if(numPlayers > 2)
scoreToAdd = subcontext.winners().contains(p) ? 1 : 0;
else if (numPlayers == 2)
scoreToAdd = numPlayers - (int) subcontext.trial().ranking()[p];
else
scoreToAdd = (subcontext.trial().ranking()[p] == 1.0) ? 1 : 0;
}
setScore(p, currentMatchScore + scoreToAdd);
}
completedTrials.add(subcontext.trial());
final End end = game.endRules();
end.eval(this);
if (!trial.over())
{
final IntFunction nextFunc = currentInstance.next();
if (nextFunc == null)
{
if (currentSubgameIdx + 1 >= game.instances().length)
currentSubgameIdx = 0;
else
currentSubgameIdx += 1;
}
else
currentSubgameIdx = nextFunc.eval(this);
final Subgame nextInstance = game.instances()[currentSubgameIdx];
//System.out.println("advancing to next instance: " + nextInstance);
// If next game not compiled we compile it.
if (nextInstance.getGame() == null)
GameLoader.compileInstance(nextInstance);
final Game nextGame = nextInstance.getGame();
final Trial nextTrial = new Trial(nextGame);
subcontext = new Context(nextGame, nextTrial, rng, this);
((MatchModel) model()).resetCurrentInstanceModel();
// TODO set players to be inactive in the trial if they should be inactive from the start
// May have to tell subtrial to store auxiliary data
if (trial().auxilTrialData() != null)
{
if (trial().auxilTrialData().legalMovesHistory() != null)
nextTrial.storeLegalMovesHistory();
if (trial().auxilTrialData().legalMovesHistorySizes() != null)
nextTrial.storeLegalMovesHistorySizes();
}
nextGame.start(subcontext);
}
}
//-------------------------------------------------------------------------
/**
* @return Lock for Game methods that should not be executed in parallel
* on the same Context object.
* Do not call this method "lock()" otherwise we get context.lock().lock();
*/
public ReentrantLock getLock()
{
return lock;
}
//-------------------------------------------------------------------------
/**
* Set the mover to the index in entry of the method and set the correct
* previous and next player according to that index.
*
* @param newMover The new mover.
*/
public void setMoverAndImpliedPrevAndNext(final int newMover)
{
state.setMover(newMover);
int next = (newMover) % game().players().count() + 1;
while (!active(next))
{
next++;
if (next > game().players().count())
next = 1;
}
state.setNext(next);
int prev = (newMover - 1);
if (prev < 1)
prev = game().players().count();
while (!active(prev))
{
prev--;
if (prev < 1)
prev = game().players().count();
}
state.setPrev(prev);
}
//-------------------------------------------------------------------------
/**
* @return True if the game we're current playing is a graph game.
*/
public boolean isGraphGame()
{
if (subcontext != null)
return subcontext.isGraphGame();
return game.isGraphGame();
}
/**
* @return True if the game we're current playing is a vertex game.
*/
public boolean isVertexGame()
{
if (subcontext != null)
return subcontext.isVertexGame();
return game.isVertexGame();
}
/**
* @return True if the game we're current playing is an edge game.
*/
public boolean isEdgeGame()
{
if (subcontext != null)
return subcontext.isEdgeGame();
return game.isEdgeGame();
}
/**
* @return True if the game we're current playing is a cell game.
*/
public boolean isCellGame()
{
if (subcontext != null)
return subcontext.isCellGame();
return game.isCellGame();
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @return The list of legal moves for that state.
*/
@SuppressWarnings("static-method")
public Moves moves(final Context context)
{
return context.game().moves(context);
}
/**
* @return The id of the player point of view used.
*/
public int pointofView()
{
return state().mover(); // For the normal context that's always the mover.
}
/**
* NOTE: The RNG seed is NOT reset to the one of the startContext here!
* Method used to set the context to another context.
* @param context The context to reset to.
*/
public void resetToContext(final Context context)
{
parentContext = context.parentContext();
state.resetStateTo(context.state(),game);
trial.resetToTrial(context.trial());
// WARNING: Currently just copying the completed trials by reference here
// TODO: Would actually want these trials to become immutable somehow...
// Would add a level of safety but is not critical (to do when time permits).
completedTrials = new ArrayList<Trial>(context.completedTrials());
subcontext = context.subcontext() == null ? null : new Context(context.subcontext(), this);
currentSubgameIdx = context.currentSubgameIdx;
models = new Model[context.models.length];
for (int i = 0; i < models.length; ++i)
models[i] = context.models[i].copy();
evalContext = new EvalContext(context.evalContext());
numLossesDecided = context.numLossesDecided;
numWinsDecided = context.numWinsDecided;
//ringFlagCalled = other.ringFlagCalled;
recursiveCalled = context.recursiveCalled();
if (context.scores != null)
scores = Arrays.copyOf(context.scores, context.scores.length);
else
scores = null;
if (context.payoffs != null)
payoffs = Arrays.copyOf(context.payoffs, context.payoffs.length);
else
payoffs = null;
active = context.active;
winners = new TIntArrayList(context.winners());
losers = new TIntArrayList(context.losers());
}
/**
* @return A map with key = site of a die, value = state of the die (for GUI only).
*/
public TIntIntHashMap diceSiteState()
{
return diceSiteStates;
}
/**
* Store the current end data into the trial.
*/
public void storeCurrentData()
{
// Store the phase of each player.
final int[] phases = new int[players().size()];
for(int pid = 1; pid < players().size(); pid++)
phases[pid] = state().currentPhase(pid);
final UndoData endData = new UndoData(
trial.ranking(),
trial.status(),
winners,
losers,
active,
scores,
payoffs,
numLossesDecided,
numWinsDecided,
phases,
state.pendingValues(),
state.counter(),
trial.previousStateWithinATurn(),
trial.previousState(),
state.prev(),
state.mover(),
state.next(),
state.numTurn(),
state.numTurnSamePlayer(),
state.numConsecutivesPasses(),
state.remainingDominoes(),
state.visited(),
state.sitesToRemove(),
state.onTrackIndices(),
state.owned(),
state.isDecided()
);
trial.addUndoData(endData);
}
}
| 38,911 | 21.324727 | 115 | java |
Ludii | Ludii-master/Core/src/other/context/EvalContext.java | package other.context;
import java.util.Arrays;
import game.functions.region.RegionFunction;
import game.util.equipment.Region;
import main.Constants;
/**
* Class storing all the data from context used in the eval method of each
* ludeme.
*
* WARNING: All the data here should never be used outside of the eval methods.
*
* @author Eric.Piette
*/
public class EvalContext
{
/** Variable used to iterate the 'from' locations. */
private int from = Constants.OFF;
/** Variable used to iterate the levels. */
private int level = Constants.OFF;
/** Variable used to iterate the 'to' locations. */
private int to = Constants.OFF;
/** Variable used to iterate the 'between' locations. */
private int between = Constants.OFF;
/** Variable used to iterate the number of pips of each die. */
private int pipCount = Constants.OFF;
/** Variable used to iterate the players. */
private int player = Constants.OFF;
/** Variable used to iterate the tracks. */
private int track = Constants.OFF;
/** Variable used to iterate some sites. */
private int site = Constants.OFF;
/** Variable used to iterate values. */
private int value = Constants.OFF;
/** Variable used to iterate regions. */
private Region region = null;
/** Variable used to iterate hint regions. */
private RegionFunction hintRegion = null;
/** Variable used to iterate the hints. */
private int hint = Constants.OFF;
/** Variable used to iterate edges. */
private int edge = Constants.OFF;
/** Variable used to iterate teams. */
private int[] team = null;
//-------------------------------------------------------------------------
/**
* Default constructor.
*/
public EvalContext()
{
// Nothing to do.
}
/**
* Copy constructor.
*
* @param other
*/
public EvalContext(final EvalContext other)
{
setFrom(other.from());
setTo(other.to());
setLevel(other.level());
setBetween(other.between());
setPipCount(other.pipCount());
setPlayer(other.player());
setTrack(other.track());
setSite(other.site);
setValue(other.value);
setRegion(other.region);
if (other.team != null)
setTeam(Arrays.copyOf(other.team, other.team.length));
setHint(other.hint());
setEdge(other.edge());
setHintRegion(other.hintRegion);
}
//-------------------------------------------------------------------------
/**
* @return From iterator.
*/
public int from()
{
return from;
}
/**
* Set the from iterator.
*
* @param from The from iterator.
*/
public void setFrom(final int from)
{
this.from = from;
}
//-------------------------------------------------------------------------
/**
* @return Track iterator.
*/
public int track()
{
return this.track;
}
/**
* Set the track iterator.
*
* @param track The track iterator.
*/
public void setTrack(final int track)
{
this.track = track;
}
//-------------------------------------------------------------------------
/**
* @return To iterator.
*/
public int to()
{
return to;
}
/**
* Set the to iterator.
*
* @param to The to iterator.
*/
public void setTo(final int to)
{
this.to = to;
}
//-------------------------------------------------------------------------
/**
* @return Between iterator.
*/
public int between()
{
return between;
}
/**
* Set the between iterator.
*
* @param between The between iterator.
*/
public void setBetween(final int between)
{
this.between = between;
}
//-------------------------------------------------------------------------
/**
* @return Player iterator.
*/
public int player()
{
return player;
}
/**
* Set the player iterator.
*
* @param player The player iterator.
*/
public void setPlayer(final int player)
{
this.player = player;
}
//-------------------------------------------------------------------------
/**
* @return PipCount iterator.
*/
public int pipCount()
{
return pipCount;
}
/**
* Set the pipCount iterator.
*
* @param pipCount The player iterator.
*/
public void setPipCount(final int pipCount)
{
this.pipCount = pipCount;
}
//-------------------------------------------------------------------------
/**
* @return Level iterator.
*/
public int level()
{
return level;
}
/**
* Set the level iterator.
*
* @param level The level iterator.
*/
public void setLevel(final int level)
{
this.level = level;
}
//-------------------------------------------------------------------------
/**
* @return Hint iterator.
*/
public int hint()
{
return hint;
}
/**
* Set the hint iterator.
*
* @param hint The hint iterator.
*/
public void setHint(final int hint)
{
this.hint = hint;
}
//-------------------------------------------------------------------------
/**
* @return Edge iterator.
*/
public int edge()
{
return edge;
}
/**
* Set the edge iterator.
*
* @param edge The edge iterator.
*/
public void setEdge(final int edge)
{
this.edge = edge;
}
//-------------------------------------------------------------------------
/**
* @return Site iterator.
*/
public int site()
{
return site;
}
/**
* Set the site iterator.
*
* @param site The site iterator.
*/
public void setSite(final int site)
{
this.site = site;
}
//-------------------------------------------------------------------------
/**
* @return Value iterator.
*/
public int value()
{
return value;
}
/**
* Set the value iterator.
*
* @param value The value iterator.
*/
public void setValue(final int value)
{
this.value = value;
}
//-------------------------------------------------------------------------
/**
* @return Region iterator.
*/
public Region region()
{
return region;
}
/**
* To set the region iterator.
*
* @param region The region iterator.
*/
public void setRegion(final Region region)
{
this.region = region;
}
//-------------------------------------------------------------------------
/**
* @return The hint region function iterator.
*/
public RegionFunction hintRegion()
{
return hintRegion;
}
/**
* To set the region function iterator.
*
* @param region The region function iterator.
*/
public void setHintRegion(final RegionFunction region)
{
hintRegion = region;
}
//-------------------------------------------------------------------------
/**
* @return Team iterator.
*/
public int[] team()
{
return team;
}
/**
* Set the team iterator.
*
* @param team The team iterator.
*/
public void setTeam(final int[] team)
{
this.team = team;
}
}
| 6,656 | 16.704787 | 79 | java |
Ludii | Ludii-master/Core/src/other/context/EvalContextData.java | package other.context;
/**
* Defines each eval context data used in the eval method of the ludemes.
*
* @author Eric.Piette
*/
public enum EvalContextData
{
/** Variable used to iterate the 'from' locations. */
From,
/** Variable used to iterate the levels. */
Level,
/** Variable used to iterate the 'to' locations. */
To,
/** Variable used to iterate the 'between' locations. */
Between,
/** Variable used to iterate the number of pips of each die. */
PipCount,
/** Variable used to iterate the players. */
Player,
/** Variable used to iterate the tracks. */
Track,
/** Variable used to iterate some sites. */
Site,
/** Variable used to iterate values. */
Value,
/** Variable used to iterate regions. */
Region,
/** Variable used to iterate hint regions. */
HintRegion,
/** Variable used to iterate the hints. */
Hint,
/** Variable used to iterate edges. */
Edge,
/** Variable used to iterate teams. */
Team,
;
//-------------------------------------------------------------------------
/**
* @return The id of the data.
*/
public int id()
{
return this.ordinal();
}
}
| 1,132 | 16.984127 | 76 | java |
Ludii | Ludii-master/Core/src/other/context/InformationContext.java | package other.context;
import java.util.ArrayList;
import java.util.List;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.rules.play.moves.BaseMoves;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import main.Constants;
import main.collections.FastArrayList;
import other.action.Action;
import other.action.die.ActionUpdateDice;
import other.move.Move;
import other.state.container.ContainerState;
import other.topology.Cell;
/**
* Return the context as it should be seen for a player for games with hidden
* information.
*
* @author Eric.Piette
*/
public class InformationContext extends Context
{
/** The id of the player point of view. */
final int playerPointOfView;
/** Context with all info to compute the legal moves. */
final Context originalContext;
//-------------------------------------------------------------------------
/**
* @param context The real context.
* @param player The id of the player point of view.
*/
public InformationContext(final Context context, final int player)
{
super(context);
playerPointOfView = player;
originalContext = new Context(context);
if(context.game().hasHandDice())
{
final Moves legalMoves = context.moves(context);
final FastArrayList<Move> moves = new FastArrayList<Move>(legalMoves.moves());
if (moves.size() > 0)
{
final ArrayList<Action> allSameActionsOld = new ArrayList<Action>(moves.get(0).actions());
final ArrayList<Action> allSameActionsNew = new ArrayList<Action>();
final ArrayList<Action> allSameActionsNew2 = new ArrayList<Action>();
for (final Move m : moves)
{
boolean differentAction = false;
for (int k = 0; k < allSameActionsOld.size(); k++)
{
if (k >= m.actions().size() || allSameActionsOld.get(k) != m.actions().get(k))
differentAction = true;
if (!differentAction)
allSameActionsNew.add(allSameActionsOld.get(k));
}
}
for (int k = 0; k < allSameActionsNew.size(); k++)
if ((allSameActionsNew.get(k) instanceof ActionUpdateDice))
allSameActionsNew2.add(allSameActionsNew.get(k));
for(int cid = 0; cid < context.containers().length ; cid++)
{
final List<Cell> cells = context.containers()[cid].topology().cells();
for (int j = 0; j < cells.size(); j++)
{
final int site = cells.get(j).index();
final ContainerState cs = context.containerState(cid);
final int what = cs.what(site, 0, SiteType.Cell);
if(what != 0)
{
final Component component = context.components()[what];
if(component.isDie())
{
for (final Action a : allSameActionsNew2)
if (a.from() == site && a.state() != Constants.UNDEFINED)
{
diceSiteStates.put(site, a.state());
break;
}
}
}
}
}
}
}
if (context.game().hiddenInformation() && player >= 1 && player <= context.game().players().count())
{
// All players have now the same information of the one in entry.
for (int cid = 0; cid < state().containerStates().length; cid++)
{
final ContainerState cs = state().containerStates()[cid];
final Container container = containers()[cid];
if (game().isCellGame())
{
for (int cellId = sitesFrom()[cid]; cellId < sitesFrom()[cid]
+ container.topology().cells().size(); cellId++)
{
for (int levelId = 0; levelId < cs.sizeStack(cellId, SiteType.Cell); levelId++)
{
final boolean isHidden = cs.isHidden(player, cellId, levelId, SiteType.Cell);
final boolean isHiddenWhat = cs.isHiddenWhat(player, cellId, levelId, SiteType.Cell);
final boolean isHiddenWho = cs.isHiddenWho(player, cellId, levelId, SiteType.Cell);
final boolean isHiddenState = cs.isHiddenState(player, cellId, levelId, SiteType.Cell);
final boolean isHiddenRotation = cs.isHiddenRotation(player, cellId, levelId, SiteType.Cell);
final boolean isHiddenValue = cs.isHiddenValue(player, cellId, levelId, SiteType.Cell);
final boolean isHiddenCount = cs.isHiddenCount(player, cellId, levelId, SiteType.Cell);
for (int pid = 1; pid < game().players().size(); pid++)
{
cs.setHidden(state(), pid, cellId, levelId, SiteType.Cell, isHidden);
cs.setHiddenWhat(state(), pid, cellId, levelId, SiteType.Cell, isHiddenWhat);
cs.setHiddenWho(state(), pid, cellId, levelId, SiteType.Cell, isHiddenWho);
cs.setHiddenState(state(), pid, cellId, levelId, SiteType.Cell, isHiddenState);
cs.setHiddenRotation(state(), pid, cellId, levelId, SiteType.Cell, isHiddenRotation);
cs.setHiddenValue(state(), pid, cellId, levelId, SiteType.Cell, isHiddenValue);
cs.setHiddenCount(state(), pid, cellId, levelId, SiteType.Cell, isHiddenCount);
}
}
}
}
}
if (context.game().isStacking())
{
for (int cid = 0; cid < state().containerStates().length; cid++)
{
final ContainerState cs = state().containerStates()[cid];
final Container container = containers()[cid];
if (game().isCellGame())
{
for (int cellId = sitesFrom()[cid]; cellId < sitesFrom()[cid]
+ container.topology().cells().size(); cellId++)
{
for (int levelId = 0; levelId < cs.sizeStack(cellId, SiteType.Cell); levelId++)
{
if (cs.isHidden(player, cellId, levelId, SiteType.Cell))
cs.setSite(state(), cellId, levelId, 0, 0, 0, 0, 0, 0);
else
{
final int what = cs.isHiddenWhat(player, cellId, levelId, SiteType.Cell)
? 0
: cs.what(cellId, levelId, SiteType.Cell);
final int who = cs.isHiddenWho(player, cellId, levelId, SiteType.Cell)
? 0
: cs.who(cellId, levelId, SiteType.Cell);
final int stateValue = cs.isHiddenState(player, cellId, levelId, SiteType.Cell)
? 0
: cs.state(cellId, levelId, SiteType.Cell);
final int value = cs.isHiddenValue(player, cellId, levelId, SiteType.Cell)
? 0
: cs.value(cellId, levelId, SiteType.Cell);
final int rotation = cs.isHiddenRotation(player, cellId, levelId, SiteType.Cell)
? 0
: cs.rotation(cellId, levelId, SiteType.Cell);
cs.remove(state(), cellId, levelId, SiteType.Cell);
cs.insertCell(state(), cellId, levelId, what, who, stateValue, rotation,
value,
game());
}
}
}
}
if (cid == 0)
{
if (game().isVertexGame())
{
for (int vertexId = 0; vertexId < container.topology().vertices().size(); vertexId++)
{
for (int levelId = 0; levelId < cs.sizeStack(vertexId, SiteType.Vertex); levelId++)
{
if (cs.isHidden(player, cid, vertexId, SiteType.Vertex))
cs.setSite(state(), vertexId, levelId, 0, 0, 0, 0, 0, 0);
else
{
final int what = cs.isHiddenWhat(player, vertexId, levelId, SiteType.Vertex)
? 0
: cs.what(vertexId, levelId, SiteType.Vertex);
final int who = cs.isHiddenWho(player, vertexId, levelId, SiteType.Vertex)
? 0
: cs.who(vertexId, levelId, SiteType.Vertex);
final int stateValue = cs.isHiddenState(player, vertexId, levelId,
SiteType.Vertex)
? 0
: cs.state(vertexId, levelId, SiteType.Vertex);
final int value = cs.isHiddenValue(player, vertexId, levelId, SiteType.Vertex)
? 0
: cs.value(vertexId, levelId, SiteType.Vertex);
final int rotation = cs.isHiddenRotation(player, vertexId, levelId,
SiteType.Vertex)
? 0
: cs.rotation(vertexId, levelId, SiteType.Vertex);
cs.remove(state(), vertexId, levelId, SiteType.Vertex);
cs.insertVertex(state(), vertexId, levelId, what, who, stateValue,
rotation, value, game());
}
}
}
}
if (game().isEdgeGame())
{
for (int edgeId = 0; edgeId < container.topology().edges().size(); edgeId++)
{
for (int levelId = 0; levelId < cs.sizeStack(edgeId, SiteType.Edge); levelId++)
{
if (cs.isHidden(player, cid, edgeId, SiteType.Edge))
cs.setSite(state(), edgeId, levelId, 0, 0, 0, 0, 0, 0);
else
{
final int what = cs.isHiddenWhat(player, edgeId, levelId, SiteType.Edge)
? 0
: cs.what(edgeId, levelId, SiteType.Edge);
final int who = cs.isHiddenWho(player, edgeId, levelId, SiteType.Edge)
? 0
: cs.who(edgeId, levelId, SiteType.Edge);
final int stateValue = cs.isHiddenState(player, edgeId, levelId, SiteType.Edge)
? 0
: cs.state(edgeId, levelId, SiteType.Edge);
final int value = cs.isHiddenValue(player, edgeId, levelId, SiteType.Edge)
? 0
: cs.value(edgeId, levelId, SiteType.Edge);
final int rotation = cs.isHiddenRotation(player, edgeId, levelId, SiteType.Edge)
? 0
: cs.rotation(edgeId, levelId, SiteType.Edge);
cs.remove(state(), edgeId, levelId, SiteType.Edge);
cs.insertEdge(state(), edgeId, levelId, what, who, stateValue, rotation,
value, game());
}
}
}
}
}
}
}
else
{
for (int cid = 0; cid < state().containerStates().length; cid++)
{
final ContainerState cs = state().containerStates()[cid];
final Container container = containers()[cid];
if (game().isCellGame())
{
for (int cellId = sitesFrom()[cid]; cellId < sitesFrom()[cid]
+ container.topology().cells().size(); cellId++)
{
final boolean wasEmpty = cs.isEmpty(cellId, SiteType.Cell);
// System.out.println("was Empty = " + wasEmpty);
if (cs.isHidden(player, cellId, 0, SiteType.Cell))
cs.setSite(state(), cellId, 0, 0, 0, 0, 0, 0, SiteType.Cell);
else
{
final int what = cs.isHiddenWhat(player, cellId, 0, SiteType.Cell)
? 0
: cs.what(cellId, SiteType.Cell);
final int who = cs.isHiddenWho(player, cellId, 0, SiteType.Cell)
? 0
: cs.who(cellId, SiteType.Cell);
final int stateValue = cs.isHiddenState(player, cellId, 0, SiteType.Cell)
? 0
: cs.state(cellId, SiteType.Cell);
final int value = cs.isHiddenValue(player, cellId, 0, SiteType.Cell)
? 0
: cs.value(cellId, SiteType.Cell);
final int rotation = cs.isHiddenRotation(player, cellId, 0, SiteType.Cell)
? 0
: cs.rotation(cellId, SiteType.Cell);
final int count = cs.isHiddenCount(player, cellId, 0, SiteType.Cell)
? 0
: cs.count(cellId, SiteType.Cell);
cs.setSite(state(), cellId, who, what, count, stateValue, rotation, value,
SiteType.Cell);
}
final boolean isEmpty = cs.isEmpty(cellId, SiteType.Cell);
// System.out.println("is Empty = " + isEmpty);
// We keep the empty info.
if (!wasEmpty && isEmpty)
cs.removeFromEmpty(cellId, SiteType.Cell);
// System.out.println("so empty value is " + cs.isEmpty(cellId, SiteType.Cell));
}
}
if (cid == 0)
{
if (game().isVertexGame())
{
for (int vertexId = 0; vertexId < container.topology().vertices().size(); vertexId++)
{
final boolean wasEmpty = cs.isEmpty(vertexId, SiteType.Vertex);
if (cs.isHidden(player, vertexId, 0, SiteType.Vertex))
cs.setSite(state(), vertexId, 0, 0, 0, 0, 0, 0, SiteType.Vertex);
else
{
final int what = cs.isHiddenWhat(player, vertexId, 0, SiteType.Vertex)
? 0
: cs.what(vertexId, SiteType.Vertex);
final int who = cs.isHiddenWho(player, vertexId, 0, SiteType.Vertex)
? 0
: cs.who(vertexId, SiteType.Vertex);
final int stateValue = cs.isHiddenState(player, vertexId, 0, SiteType.Vertex)
? 0
: cs.state(vertexId, SiteType.Vertex);
final int value = cs.isHiddenValue(player, vertexId, 0, SiteType.Vertex)
? 0
: cs.value(vertexId, SiteType.Vertex);
final int rotation = cs.isHiddenRotation(player, vertexId, 0, SiteType.Vertex)
? 0
: cs.rotation(vertexId, SiteType.Vertex);
final int count = cs.isHiddenCount(player, vertexId, 0, SiteType.Vertex)
? 0
: cs.count(vertexId, SiteType.Vertex);
cs.setSite(state(), vertexId, who, what, count, stateValue, rotation, value,
SiteType.Vertex);
}
final boolean isEmpty = cs.isEmpty(vertexId, SiteType.Vertex);
// We keep the empty info.
if (!wasEmpty && isEmpty)
cs.removeFromEmpty(vertexId, SiteType.Vertex);
}
}
if (game().isEdgeGame())
{
for (int edgeId = 0; edgeId < container.topology().edges().size(); edgeId++)
{
final boolean wasEmpty = cs.isEmpty(edgeId, SiteType.Edge);
if (cs.isHidden(player, edgeId, 0, SiteType.Edge))
cs.setSite(state(), edgeId, 0, 0, 0, 0, 0, 0, SiteType.Edge);
else
{
final int what = cs.isHiddenWhat(player, edgeId, 0, SiteType.Edge)
? 0
: cs.what(edgeId, SiteType.Edge);
final int who = cs.isHiddenWho(player, edgeId, 0, SiteType.Edge)
? 0
: cs.who(edgeId, SiteType.Edge);
final int stateValue = cs.isHiddenState(player, edgeId, 0, SiteType.Edge)
? 0
: cs.state(edgeId, SiteType.Edge);
final int value = cs.isHiddenValue(player, edgeId, 0, SiteType.Edge)
? 0
: cs.value(edgeId, SiteType.Edge);
final int rotation = cs.isHiddenRotation(player, edgeId, 0, SiteType.Edge)
? 0
: cs.rotation(edgeId, SiteType.Edge);
final int count = cs.isHiddenCount(player, edgeId, 0, SiteType.Edge)
? 0
: cs.count(edgeId, SiteType.Edge);
cs.setSite(state(), edgeId, who, what, count, stateValue, rotation, value,
SiteType.Edge);
}
final boolean isEmpty = cs.isEmpty(edgeId, SiteType.Edge);
// We keep the empty info.
if (!wasEmpty && isEmpty)
cs.removeFromEmpty(edgeId, SiteType.Edge);
}
}
}
}
}
}
}
//-------------------------------------------------------------------------
@Override
public Moves moves(final Context context)
{
if (originalContext.state().mover() == playerPointOfView)
return originalContext.game().moves(originalContext);
return new BaseMoves(null);
}
@Override
public int pointofView()
{
return playerPointOfView;
}
}
| 14,968 | 35.599022 | 102 | java |
Ludii | Ludii-master/Core/src/other/context/TempContext.java | package other.context;
import other.state.CopyOnWriteState;
import other.state.State;
import other.trial.TempTrial;
import other.trial.Trial;
/**
* A temporary version of a context. Can only be constructed by "copying" another
* context. Contains optimisations that may make it invalid for long-term use,
* only intended to be used shortly and temporarily after creation. Changes to
* the source-context may also seep through into this temp context due to
* copy-on-write optimisations, making it potentially invalid.
*
* @author Dennis Soemers
*/
public final class TempContext extends Context
{
//-------------------------------------------------------------------------
/**
*
* @param other
*/
public TempContext(final Context other)
{
super(other);
}
//-------------------------------------------------------------------------
@Override
protected State copyState(final State otherState)
{
return otherState == null ? null : new CopyOnWriteState(otherState);
}
@Override
protected Trial copyTrial(final Trial otherTrial)
{
return new TempTrial(otherTrial);
}
//-------------------------------------------------------------------------
}
| 1,191 | 23.833333 | 81 | java |
Ludii | Ludii-master/Core/src/other/location/CellOnlyLocation.java | package other.location;
import game.types.board.SiteType;
/**
* A version of Location for games that use only Cells (no other site types)
*
* @author Dennis Soemers
*/
public final class CellOnlyLocation extends Location
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The site of the component.
*/
private final int site;
/**
* The level of the component in case of stack.
*/
private int level = 0;
//-------------------------------------------------------------------------
/**
* Constructor for stacking game.
*
* @param site
* @param level
*/
public CellOnlyLocation(final int site, final int level)
{
this.site = site;
this.level = level;
}
/**
* Constructor for non stacking game.
*
* @param site
*/
public CellOnlyLocation(final int site)
{
this.site = site;
this.level = 0;
}
/**
* Copy Constructor.
* @param other
*/
private CellOnlyLocation(final CellOnlyLocation other)
{
this.site = other.site;
this.level = other.level;
}
//-------------------------------------------------------------------------
@Override
public Location copy()
{
return new CellOnlyLocation(this);
}
//-------------------------------------------------------------------------
@Override
public int site()
{
return this.site;
}
@Override
public int level()
{
return this.level;
}
@Override
public SiteType siteType()
{
return SiteType.Cell;
}
//-------------------------------------------------------------------------
@Override
public void decrementLevel()
{
this.level = this.level - 1;
}
@Override
public void incrementLevel()
{
this.level = this.level + 1;
}
//--------------------------------------------------------------------------
}
| 1,935 | 16.441441 | 77 | java |
Ludii | Ludii-master/Core/src/other/location/FlatCellOnlyLocation.java | package other.location;
import game.types.board.SiteType;
/**
* A version of Location for games that use only Cells, and no levels
*
* @author Dennis Soemers
*/
public final class FlatCellOnlyLocation extends Location
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The site of the component.
*/
private final int site;
//-------------------------------------------------------------------------
/**
* Constructor for non stacking game.
*
* @param site
*/
public FlatCellOnlyLocation(final int site)
{
this.site = site;
}
/**
* Copy Constructor.
* @param other
*/
private FlatCellOnlyLocation(final FlatCellOnlyLocation other)
{
this.site = other.site;
}
//-------------------------------------------------------------------------
@Override
public Location copy()
{
return new FlatCellOnlyLocation(this);
}
//-------------------------------------------------------------------------
@Override
public int site()
{
return site;
}
@Override
public int level()
{
return 0;
}
@Override
public SiteType siteType()
{
return SiteType.Cell;
}
//-------------------------------------------------------------------------
@Override
public void decrementLevel()
{
throw new UnsupportedOperationException();
}
@Override
public void incrementLevel()
{
throw new UnsupportedOperationException();
}
//--------------------------------------------------------------------------
}
| 1,640 | 17.032967 | 77 | java |
Ludii | Ludii-master/Core/src/other/location/FlatVertexOnlyLocation.java | package other.location;
import game.types.board.SiteType;
/**
* A version of Location for games that use only Vertices, and no levels
*
* @author Dennis Soemers
*/
public final class FlatVertexOnlyLocation extends Location
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The site of the component.
*/
private final int site;
//-------------------------------------------------------------------------
/**
* Constructor for non stacking game.
*
* @param site
*/
public FlatVertexOnlyLocation(final int site)
{
this.site = site;
}
/**
* Copy Constructor.
* @param other
*/
private FlatVertexOnlyLocation(final FlatVertexOnlyLocation other)
{
this.site = other.site;
}
//-------------------------------------------------------------------------
@Override
public Location copy()
{
return new FlatVertexOnlyLocation(this);
}
//-------------------------------------------------------------------------
@Override
public int site()
{
return site;
}
@Override
public int level()
{
return 0;
}
@Override
public SiteType siteType()
{
return SiteType.Vertex;
}
//-------------------------------------------------------------------------
@Override
public void decrementLevel()
{
throw new UnsupportedOperationException();
}
@Override
public void incrementLevel()
{
throw new UnsupportedOperationException();
}
//--------------------------------------------------------------------------
}
| 1,655 | 17.197802 | 77 | java |
Ludii | Ludii-master/Core/src/other/location/FullLocation.java | package other.location;
import game.types.board.SiteType;
/**
* A "Full" version of Location, with all the data we could ever need (no optimisations)
*
* @author Dennis Soemers
*/
public final class FullLocation extends Location
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The site of the component.
*/
private final int site;
/**
* The level of the component in case of stack.
*/
private int level = 0;
/**
* The graph element type.
*/
private final SiteType siteType;
//-------------------------------------------------------------------------
/**
* Constructor for stacking game with the site type.
*
* @param site
* @param level
* @param siteType
*/
public FullLocation(final int site, final int level, final SiteType siteType)
{
this.site = site;
this.level = level;
this.siteType = siteType;
}
/**
* Constructor for stacking game.
*
* @param site
* @param level
*/
public FullLocation(final int site, final int level)
{
this.site = site;
this.level = level;
this.siteType = SiteType.Cell;
}
/**
* Constructor for non stacking game.
*
* @param site
*/
public FullLocation(final int site)
{
this.site = site;
this.level = 0;
this.siteType = SiteType.Cell;
}
/**
* Constructor for non stacking game.
*
* @param site
* @param siteType
*/
public FullLocation(final int site, final SiteType siteType)
{
this.site = site;
this.level = 0;
this.siteType = siteType;
}
/**
* Copy Constructor.
* @param other
*/
private FullLocation(final FullLocation other)
{
this.site = other.site;
this.level = other.level;
this.siteType = other.siteType;
}
//-------------------------------------------------------------------------
@Override
public Location copy()
{
return new FullLocation(this);
}
//-------------------------------------------------------------------------
@Override
public int site()
{
return site;
}
@Override
public int level()
{
return level;
}
@Override
public SiteType siteType()
{
return siteType;
}
//-------------------------------------------------------------------------
@Override
public void decrementLevel()
{
this.level = this.level - 1;
}
@Override
public void incrementLevel()
{
this.level = this.level + 1;
}
//--------------------------------------------------------------------------
}
| 2,584 | 16.827586 | 88 | java |
Ludii | Ludii-master/Core/src/other/location/Location.java | package other.location;
import java.io.Serializable;
import game.types.board.SiteType;
/**
* A position is the site of a component and the level on it (in case of stack).
* This is used for the cache Owned on the trial.
*
* @author Eric.Piette and Matthew.Stephenson and Dennis Soemers
*
*/
public abstract class Location implements Serializable
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @return A deep copy of this Location object.
*/
public abstract Location copy();
//-------------------------------------------------------------------------
/**
* @return The site of this location
*/
public abstract int site();
/**
* @return The level of this location
*/
public abstract int level();
/**
* @return The site type of this location
*/
public abstract SiteType siteType();
//-------------------------------------------------------------------------
/**
* Decrements the level of this location
*/
public abstract void decrementLevel();
/**
* Increments the level of this location
*/
public abstract void incrementLevel();
//--------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + site();
result = prime * result + level();
result = prime * result + siteType().hashCode();
return result;
}
//--------------------------------------------------------------------------
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof Location))
return false;
final Location other = (Location) obj;
return (site() == other.site() &&
level() == other.level() &&
siteType() == other.siteType());
}
//--------------------------------------------------------------------------
@Override
public String toString()
{
return "Location(site:" + site() + " level: " + level() + " siteType: " + siteType() + ")";
}
//-------------------------------------------------------------------------
}
| 2,246 | 21.47 | 93 | java |
Ludii | Ludii-master/Core/src/other/model/AlternatingMove.java | package other.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import game.rules.phase.Phase;
import game.rules.play.moves.Moves;
import main.collections.FastArrayList;
import other.AI;
import other.ThinkingThread;
import other.action.Action;
import other.context.Context;
import other.move.Move;
import other.playout.PlayoutMoveSelector;
import other.trial.Trial;
/**
* Model for alternating-move games
*
* @author Dennis Soemers
*/
public final class AlternatingMove extends Model
{
//-------------------------------------------------------------------------
/** Are we ready with our current step? */
protected transient volatile boolean ready = true;
/** Are we ready to receive external actions? */
protected transient volatile boolean running = false;
/** Currently-running thinking thread */
protected transient volatile ThinkingThread currentThinkingThread = null;
/** AI used to select a move in the last step */
protected transient AI lastStepAI = null;
/** Move selected in last step */
protected transient Move lastStepMove = null;
//-------------------------------------------------------------------------
@Override
public Move applyHumanMove(final Context context, final Move move, final int player)
{
if (currentThinkingThread != null)
{
// Don't interrupt AI
return null;
}
if (!ready)
{
// only apply move if we've actually started a new step
final Move appliedMove = context.game().apply(context, move);
context.trial().setNumSubmovesPlayed(context.trial().numSubmovesPlayed() + 1);
lastStepMove = move;
ready = true;
running = false;
return appliedMove;
}
return null;
}
@Override
public Model copy()
{
return new AlternatingMove();
}
@Override
public boolean expectsHumanInput()
{
return (!ready && running && (currentThinkingThread == null));
}
@Override
public List<AI> getLastStepAIs()
{
if (!ready)
return null;
return Arrays.asList(lastStepAI);
}
@Override
public List<Move> getLastStepMoves()
{
if (!ready)
return null;
return Arrays.asList(lastStepMove);
}
@Override
public synchronized void interruptAIs()
{
if (!ready)
{
if (currentThinkingThread != null)
{
AI ai = null;
try
{
ai = currentThinkingThread.interruptAI();
while (currentThinkingThread.isAlive())
{
try
{
Thread.sleep(15L);
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
}
currentThinkingThread = null;
}
catch (final NullPointerException e)
{
// Do nothing
}
if (ai != null)
ai.setWantsInterrupt(false);
}
lastStepAI = null;
ready = true;
running = false;
}
}
@Override
public boolean isReady()
{
return ready;
}
@Override
public boolean isRunning()
{
return running;
}
@Override
public synchronized void randomStep
(
final Context context,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback
)
{
if (!ready && currentThinkingThread == null)
{
final FastArrayList<Move> legalMoves = context.game().moves(context).moves();
final int r = ThreadLocalRandom.current().nextInt(legalMoves.size());
final Move move = legalMoves.get(r);
if (inPreAgentMoveCallback != null)
{
final long waitMillis = inPreAgentMoveCallback.call(move);
if (waitMillis > 0L)
{
try
{
Thread.sleep(waitMillis);
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
}
}
final Move appliedMove = applyHumanMove(context, move, context.state().mover());
ready = true;
if (inPostAgentMoveCallback != null)
inPostAgentMoveCallback.call(appliedMove);
running = false;
}
}
//-------------------------------------------------------------------------
@Override
public void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback
)
{
startNewStep
(
context, ais, maxSeconds, maxIterations, maxSearchDepth,
minSeconds, block, forceThreaded, forceNotThreaded,
inPreAgentMoveCallback, inPostAgentMoveCallback, false, null
);
}
//-------------------------------------------------------------------------
@Override
public void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback,
final boolean checkMoveValid,
final MoveMessageCallback moveMessageCallback
)
{
// context.getLock().lock();
//
// try
// {
if (!ready)
{
// we're already running our current step, so don't start a new one
return;
}
while (true)
{
final ThinkingThread thinkingThread = currentThinkingThread;
if (thinkingThread == null || !thinkingThread.isAlive())
break;
// TODO uncomment below if we move to Java >= 9
//Thread.onSpinWait();
}
ready = false;
final int mover = context.state().mover();
final AI agent;
if (ais == null || mover >= ais.size())
agent = null;
else
agent = ais.get(context.state().playerToAgent(mover));
lastStepAI = agent;
if (block)
{
// we're allowed to block, so just compute the move here
if (agent == null)
{
randomStep(context, inPreAgentMoveCallback, inPostAgentMoveCallback);
return;
}
Move move;
if (!forceThreaded)
{
// we don't have to run AI in separate thread, so run it here
move = agent.selectAction
(
context.game(),
agent.copyContext(context),
maxSeconds[context.state().playerToAgent(mover)],
maxIterations,
maxSearchDepth
);
}
else
{
// we have to run AI in different thread
currentThinkingThread =
ThinkingThread.construct
(
agent,
context.game(),
agent.copyContext(context),
maxSeconds[context.state().playerToAgent(mover)],
maxIterations,
maxSearchDepth,
minSeconds,
null
);
currentThinkingThread.setDaemon(true);
currentThinkingThread.start();
while (currentThinkingThread.isAlive())
{
// TODO uncomment below if we move to Java >= 9
//Thread.onSpinWait();
}
move = currentThinkingThread.move();
currentThinkingThread = null;
}
move = checkMoveValid(checkMoveValid, context, move, moveMessageCallback);
if (inPreAgentMoveCallback != null)
{
final long waitMillis = inPreAgentMoveCallback.call(move);
if (waitMillis > 0L)
{
try
{
Thread.sleep(waitMillis);
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
}
}
// apply chosen move
final Move appliedMove = context.game().apply(context, move);
context.trial().setNumSubmovesPlayed(context.trial().numSubmovesPlayed() + 1);
lastStepMove = move;
// we're done
ready = true;
if (inPostAgentMoveCallback != null)
inPostAgentMoveCallback.call(appliedMove);
running = false;
}
else
{
// we're not allowed to block, must return immediately
// this implies we have to run a thread for AI
if (agent != null)
{
// only create Thread if agent is not null (no human)
currentThinkingThread =
ThinkingThread.construct
(
agent,
context.game(),
agent.copyContext(context),
maxSeconds[context.state().playerToAgent(mover)],
maxIterations,
maxSearchDepth,
minSeconds,
new Runnable()
{
@Override
public void run()
{
// this code runs when AI finished selecting move
Move move = currentThinkingThread.move();
move = checkMoveValid(checkMoveValid, context, move, moveMessageCallback);
while (!running)
{
// TODO uncomment below if we move to Java >= 9
//Thread.onSpinWait();
}
if (inPreAgentMoveCallback != null)
{
final long waitMillis = inPreAgentMoveCallback.call(move);
if (waitMillis > 0L)
{
try
{
Thread.sleep(waitMillis);
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
}
}
final Move appliedMove = context.game().apply(context, move);
context.trial().setNumSubmovesPlayed(context.trial().numSubmovesPlayed() + 1);
lastStepMove = move;
ready = true;
if (inPostAgentMoveCallback != null)
inPostAgentMoveCallback.call(appliedMove);
running = false;
currentThinkingThread = null;
}
}
);
currentThinkingThread.setDaemon(true);
currentThinkingThread.start();
running = true;
}
else
{
running = true;
}
}
// }
// finally
// {
// context.getLock().unlock();
// }
}
@Override
public void unpauseAgents
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback,
final boolean checkMoveValid,
final MoveMessageCallback moveMessageCallback
)
{
final int mover = context.state().mover();
final AI agent;
if (ais == null || mover >= ais.size())
agent = null;
else
agent = ais.get(context.state().playerToAgent(mover));
lastStepAI = agent;
if (agent != null)
{
currentThinkingThread =
ThinkingThread.construct
(
agent,
context.game(),
agent.copyContext(context),
maxSeconds[mover],
maxIterations,
maxSearchDepth,
minSeconds,
new Runnable()
{
@Override
public void run()
{
// this code runs when AI finished selecting move
Move move = currentThinkingThread.move();
currentThinkingThread = null;
move = checkMoveValid(checkMoveValid, context, move, moveMessageCallback);
if (inPreAgentMoveCallback != null)
{
final long waitMillis = inPreAgentMoveCallback.call(move);
if (waitMillis > 0L)
{
try
{
Thread.sleep(waitMillis);
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
}
}
final Move appliedMove = context.game().apply(context, move);
context.trial().setNumSubmovesPlayed(context.trial().numSubmovesPlayed() + 1);
lastStepMove = move;
ready = true;
if (inPostAgentMoveCallback != null)
inPostAgentMoveCallback.call(appliedMove);
running = false;
}
}
);
currentThinkingThread.setDaemon(true);
currentThinkingThread.start();
}
}
//-------------------------------------------------------------------------
@Override
public List<AI> getLiveAIs()
{
final List<AI> ais = new ArrayList<>(1);
if (currentThinkingThread != null)
ais.add(currentThinkingThread.ai());
return ais;
}
//-------------------------------------------------------------------------
@Override
public boolean verifyMoveLegal(final Context context, final Move move)
{
boolean validMove = false;
final FastArrayList<Move> legal = new FastArrayList<Move>(context.game().moves(context).moves());
final List<Action> moveActions = move.getActionsWithConsequences(context);
for (final Move m : legal)
{
if (movesEqual(move, moveActions, m, context))
{
validMove = true;
break;
}
}
if (legal.isEmpty() && move.isPass())
validMove = true;
return validMove;
}
//-------------------------------------------------------------------------
@Override
public Trial playout
(
final Context context, final List<AI> ais, final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector, final int maxNumBiasedActions,
final int maxNumPlayoutActions, final Random random
)
{
final Game game = context.game();
final Phase startPhase = game.rules().phases()[context.state().currentPhase(context.state().mover())];
int numActionsApplied = 0;
final Trial trial = context.trial();
while
(
!trial.over()
&&
(maxNumPlayoutActions < 0 || maxNumPlayoutActions > numActionsApplied)
)
{
final int mover = context.state().mover();
final Phase currPhase = game.rules().phases()[context.state().currentPhase(mover)];
if (currPhase != startPhase && currPhase.playout() != null)
{
// May have to switch over to new playout implementation
return trial;
}
Move move = null;
AI ai = null;
if (ais != null)
ai = ais.get(context.state().playerToAgent(mover));
if (ai != null)
{
// Make AI move
move = ai.selectAction(game, ai.copyContext(context), thinkingTime, -1, -1);
}
else
{
// Make (biased) random move
final Moves legal = game.moves(context);
if
(
playoutMoveSelector == null
||
(maxNumBiasedActions >= 0 && maxNumBiasedActions < numActionsApplied)
||
playoutMoveSelector.wantsPlayUniformRandomMove()
)
{
// Select move uniformly at random
final int r = random.nextInt(legal.moves().size());
move = legal.moves().get(r);
}
else
{
// Let our playout move selector pick a move
move = playoutMoveSelector.selectMove(context, legal.moves(), mover, (final Move m) -> {return true;});
}
}
if (move == null)
{
System.out.println("Game.playout(): No move found.");
break;
}
game.apply(context, move);
++numActionsApplied;
}
return trial;
}
//-------------------------------------------------------------------------
@Override
public boolean callsGameMoves()
{
return true;
}
//-------------------------------------------------------------------------
/**
* @return The specified move, else a random move if it's not valid.
*/
static Move checkMoveValid
(
final boolean checkMoveValid, final Context context,
final Move move, final MoveMessageCallback callBack
)
{
if (checkMoveValid && !context.model().verifyMoveLegal(context, move))
{
final FastArrayList<Move> legalMoves = context.game().moves(context).moves();
final Move randomMove = legalMoves.get(ThreadLocalRandom.current().nextInt(legalMoves.size()));
final String msg = "illegal move detected: " + move.actions() +
", instead applying: " + randomMove;
callBack.call(msg);
System.out.println(msg);
return randomMove;
}
return move;
}
//-------------------------------------------------------------------------
}
| 15,620 | 22.073855 | 108 | java |
Ludii | Ludii-master/Core/src/other/model/MatchModel.java | package other.model;
import java.util.List;
import java.util.Random;
import game.Game;
import game.match.Subgame;
import game.rules.play.moves.Moves;
import other.AI;
import other.context.Context;
import other.move.Move;
import other.playout.PlayoutMoveSelector;
import other.trial.Trial;
/**
* Model for multi-game Matches
*
* @author Dennis Soemers
*/
public class MatchModel extends Model
{
//-------------------------------------------------------------------------
/** Model to use within the current instance */
protected transient Model currentInstanceModel = null;
//-------------------------------------------------------------------------
@Override
public Move applyHumanMove(final Context context, final Move move, final int player)
{
return currentInstanceModel.applyHumanMove(context, move, player);
}
@Override
public Model copy()
{
return new MatchModel();
}
@Override
public boolean expectsHumanInput()
{
return currentInstanceModel != null && currentInstanceModel.expectsHumanInput();
}
@Override
public List<AI> getLastStepAIs()
{
return currentInstanceModel.getLastStepAIs();
}
@Override
public List<Move> getLastStepMoves()
{
return currentInstanceModel.getLastStepMoves();
}
@Override
public synchronized void interruptAIs()
{
if (currentInstanceModel != null)
currentInstanceModel.interruptAIs();
}
@Override
public boolean isReady()
{
return currentInstanceModel == null || currentInstanceModel.isReady();
}
@Override
public boolean isRunning()
{
return currentInstanceModel != null && currentInstanceModel.isRunning();
}
@Override
public synchronized void randomStep
(
final Context context,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback
)
{
currentInstanceModel.randomStep(context, inPreAgentMoveCallback, inPostAgentMoveCallback);
}
/**
* Resets this MatchModel's current instance Model back to null
*/
public void resetCurrentInstanceModel()
{
currentInstanceModel = null;
}
@Override
public boolean verifyMoveLegal(final Context context, final Move move)
{
return context.subcontext().model().verifyMoveLegal(context, move);
}
//-------------------------------------------------------------------------
@Override
public synchronized void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback
)
{
startNewStep(context,ais,maxSeconds,maxIterations,maxSearchDepth,minSeconds,block,forceThreaded,forceNotThreaded,inPreAgentMoveCallback,inPostAgentMoveCallback,false,null);
}
//-------------------------------------------------------------------------
@Override
public synchronized void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback,
final boolean checkMoveValid,
final MoveMessageCallback moveMessageCallback
)
{
currentInstanceModel = context.subcontext().model();
currentInstanceModel.startNewStep
(
context,
ais,
maxSeconds,
maxIterations,
maxSearchDepth,
minSeconds,
block,
forceThreaded,
forceNotThreaded,
inPreAgentMoveCallback,
inPostAgentMoveCallback,
checkMoveValid,
moveMessageCallback
);
}
@Override
public void unpauseAgents
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback,
final boolean checkMoveValid,
final MoveMessageCallback moveMessageCallback
)
{
currentInstanceModel.unpauseAgents
(
context,
ais,
maxSeconds,
maxIterations,
maxSearchDepth,
minSeconds,
inPreAgentMoveCallback,
inPostAgentMoveCallback,
checkMoveValid,
moveMessageCallback
);
}
//-------------------------------------------------------------------------
@Override
public List<AI> getLiveAIs()
{
return currentInstanceModel.getLiveAIs();
}
//-------------------------------------------------------------------------
@Override
public Trial playout
(
final Context context, final List<AI> ais, final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector, final int maxNumBiasedActions,
final int maxNumPlayoutActions, final Random random
)
{
final Game match = context.game();
final Trial matchTrial = context.trial();
int numActionsApplied = 0;
while
(
!matchTrial.over()
&&
(maxNumPlayoutActions < 0 || maxNumPlayoutActions > numActionsApplied)
)
{
final Subgame instance = match.instances()[context.currentSubgameIdx()];
final Game instanceGame = instance.getGame();
final Context subcontext = context.subcontext();
final Trial subtrial = subcontext.trial();
final int numStartMoves = subtrial.numMoves();
// May have to tell subtrial to store auxiliary data
if (context.trial().auxilTrialData() != null)
{
if (context.trial().auxilTrialData().legalMovesHistory() != null)
subtrial.storeLegalMovesHistory();
if (context.trial().auxilTrialData().legalMovesHistorySizes() != null)
subtrial.storeLegalMovesHistorySizes();
}
final Trial instanceEndTrial = instanceGame.playout
(
subcontext, ais, thinkingTime, playoutMoveSelector,
maxNumBiasedActions, maxNumPlayoutActions - numActionsApplied,
random
);
// Will likely have to append some extra moves to the match-wide trial
final List<Move> subtrialMoves = subtrial.generateCompleteMovesList();
final int numMovesAfterPlayout = subtrialMoves.size();
final int numMovesToAppend = numMovesAfterPlayout - numStartMoves;
for (int i = 0; i < numMovesToAppend; ++i)
{
context.trial().addMove(subtrialMoves.get(subtrialMoves.size() - numMovesToAppend + i));
}
// If the instance we over, we have to advance here in this Match
if (subcontext.trial().over())
{
final Moves legalMatchMoves = context.game().moves(context);
assert (legalMatchMoves.moves().size() == 1);
assert (legalMatchMoves.moves().get(0).containsNextInstance());
context.game().apply(context, legalMatchMoves.moves().get(0));
}
// May have to update Match-wide auxiliary trial data
if (context.trial().auxilTrialData() != null)
{
context.trial().auxilTrialData().updateFromSubtrial(subtrial);
// Need to add 1 here, for the special state where we have to play a NextInstance move
if (context.trial().auxilTrialData().legalMovesHistorySizes() != null)
context.trial().auxilTrialData().legalMovesHistorySizes().add(1);
}
numActionsApplied += (instanceEndTrial.numMoves() - numStartMoves);
}
return matchTrial;
}
//-------------------------------------------------------------------------
@Override
public boolean callsGameMoves()
{
return true;
}
//-------------------------------------------------------------------------
}
| 7,567 | 24.654237 | 174 | java |
Ludii | Ludii-master/Core/src/other/model/Model.java | package other.model;
import java.util.Arrays;
import java.util.List;
import other.AI;
import other.action.Action;
import other.context.Context;
import other.move.Move;
import other.playout.Playout;
//-----------------------------------------------------------------------------
/**
* Model of game's control flow, can be used to step through a trial
* correctly (i.e. alternating moves, simultaneous moves, etc.)
*
* @author Dennis Soemers
*/
public abstract class Model implements Playout
{
//-------------------------------------------------------------------------
/**
* Applies a move selected by human
* @param context
* @param move
* @param player
* @return applied move
*/
public abstract Move applyHumanMove(final Context context, final Move move, final int player);
/**
* @return A copy of the Model object
*/
public abstract Model copy();
/**
* @return True if we expect human input
*/
public abstract boolean expectsHumanInput();
/**
* @return List of AIs who have made a move in the last step
*/
public abstract List<AI> getLastStepAIs();
/**
* @return List of moves selected by different players in the last step
*/
public abstract List<Move> getLastStepMoves();
/**
* Interrupts any AIs that are currently running in separate threads
*/
public abstract void interruptAIs();
/**
* @return True if and only if the last step that has been started has
* also finished processing.
*/
public abstract boolean isReady();
/**
* @return True if and only if a step has been started and is properly
* running (ready to receive external moves if threaded)
*/
public abstract boolean isRunning();
/**
* Completes the current step by taking random moves (for any players who
* do not currently have AIs thinking).
* @param context
* @param inPreAgentMoveCallback
* @param inPostAgentMoveCallback
*/
public abstract void randomStep
(
final Context context,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback
);
/**
* @param context
* @param move
* @return True if given move is legal in given context, false otherwise.
*/
public abstract boolean verifyMoveLegal(final Context context, final Move move);
//-------------------------------------------------------------------------
/**
* Starts a new "time step" (a single move by a single player in Alternating-Move
* games, or a collection of moves by active players in Simultaneous-Move games).<br>
* <br>
* By default: <br>
* - A blocking call (sequences not return until the step has been completed).<br>
* - Does not force running in a separate thread (so may run in the calling thread).<br>
* - Allows running AIs in different threads (simultaneous-move models will prefer to
* run AIs in multiple threads if allowed, whereas alternating-move models prefer to
* just run in a single thread). <br>
*
* @param context Current context (containing current state/trial)
* @param ais List of AIs (0 index should be null)
* @param maxSeconds Maximum number of seconds that AIs are allowed to use
*/
public void startNewStep
(
final Context context,
final List<AI> ais,
final double maxSeconds
)
{
final double[] timeLimits = new double[context.game().players().count() + 1];
Arrays.fill(timeLimits, maxSeconds);
startNewStep(context, ais, timeLimits);
}
/**
* Similar to {@link #startNewStep(Context, List, double)}, but allows
* specifying an array with different thinking times for different agents.
*
* @param context Current context (containing current state/trial)
* @param ais List of AIs (0 index should be null)
* @param maxSeconds For every AI, maximum number of seconds that that AI is
* allowed to use. Index 0 is not used.
*/
public void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds
)
{
startNewStep(context, ais, maxSeconds, -1, -1, 0.0);
}
/**
* Similar to {@link #startNewStep(Context, List, double)}, but allows
* specifying max iterations, max search depth, and minimum search time
* for AIs (in addition to the maximum search time).
*
* @param context Current context (containing current state/trial)
* @param ais List of AIs (0 index should be null)
* @param maxSeconds Maximum number of seconds that AIs are allowed to use
* @param maxIterations Maximum number of iterations for AIs (such as MCTS)
* @param maxSearchDepth Maximum search depth for AIs (such as Alpha-Beta)
* @param minSeconds Minimum number of seconds that the AI must spend per move
*/
public void startNewStep
(
final Context context,
final List<AI> ais,
final double maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds
)
{
final double[] timeLimits = new double[context.game().players().count() + 1];
Arrays.fill(timeLimits, maxSeconds);
startNewStep(context, ais, timeLimits, maxIterations, maxSearchDepth, minSeconds);
}
/**
* Similar to {@link #startNewStep(Context, List, double[])}, but allows
* specifying max iterations, max search depth, and minimum search time
* for AIs (in addition to the array of maximum search times).
*
* @param context Current context (containing current state/trial)
* @param ais List of AIs (0 index should be null)
* @param maxSeconds For every AI, maximum number of seconds that that AI is
* allowed to use. Index 0 is not used.
* @param maxIterations Maximum number of iterations for AIs (such as MCTS)
* @param maxSearchDepth Maximum search depth for AIs (such as Alpha-Beta)
* @param minSeconds Minimum number of seconds that the AI must spend per move
*/
public void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds
)
{
startNewStep(context, ais, maxSeconds, maxIterations, maxSearchDepth, minSeconds, true, false, false, null, null);
}
/**
* Similar to {@link #startNewStep(Context, List, double, int, int, double)},
* but with additional parameters to control the threading/blocking behaviour
* of the call.
*
* @param context Current context (containing current state/trial)
* @param ais List of AIs (0 index should be null)
* @param maxSeconds Maximum number of seconds that AIs are allowed to use
* @param maxIterations Maximum number of iterations for AIs (such as MCTS)
* @param maxSearchDepth Maximum search depth for AIs (such as Alpha-Beta)
* @param minSeconds Minimum number of seconds that the AI must spend per move
* @param block If true, this method will block and only return once a move has
* been applied to the current game state. If false, the method will return
* immediately while AIs may still spend time thinking about their moves in
* different threads.
* @param forceThreaded If true, this method is forced to run in a new thread.
* @param forceNotThreaded If true, this method may not create new threads and
* is forced to run entirely in the calling thread.
*/
public void startNewStep
(
final Context context,
final List<AI> ais,
final double maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded
)
{
final double[] timeLimits = new double[context.game().players().count() + 1];
Arrays.fill(timeLimits, maxSeconds);
startNewStep(context, ais, timeLimits, maxIterations, maxSearchDepth, minSeconds, block, forceThreaded, forceNotThreaded, null, null);
}
/**
* Similar to {@link #startNewStep(Context, List, double[], int, int, double)},
* but with additional parameters to control the threading/blocking behaviour
* of the call, and options to add extra callbacks to be called before and after
* agents select their moves.
*
* @param context Current context (containing current state/trial)
* @param ais List of AIs (0 index should be null)
* @param maxSeconds Maximum number of seconds that AIs are allowed to use
* @param maxIterations Maximum number of iterations for AIs (such as MCTS)
* @param maxSearchDepth Maximum search depth for AIs (such as Alpha-Beta)
* @param minSeconds Minimum number of seconds that the AI must spend per move
* @param block If true, this method will block and only return once a move has
* been applied to the current game state. If false, the method will return
* immediately while AIs may still spend time thinking about their moves in
* different threads.
* @param forceThreaded If true, this method is forced to run in a new thread.
* @param forceNotThreaded If true, this method may not create new threads and
* is forced to run entirely in the calling thread.
* @param inPreAgentMoveCallback If not null, this callback will be called when
* an AI has picked its move, but before applying it.
* @param inPostAgentMoveCallback If not null, this callback will be called right
* after an AI's move has been applied.
*/
public abstract void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback
);
/**
* Same as above, but with additional boolean param to check legal moves
*
* @param context
* @param ais
* @param maxSeconds
* @param maxIterations
* @param maxSearchDepth
* @param minSeconds
* @param block
* @param forceThreaded
* @param forceNotThreaded
* @param inPreAgentMoveCallback
* @param inPostAgentMoveCallback
* @param checkMoveValid
* @param moveMessageCallback
*/
public abstract void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback,
final boolean checkMoveValid,
final MoveMessageCallback moveMessageCallback
);
/**
* Notifies the model that agents are unpaused, and should now start running
*
* @param context
* @param ais
* @param maxSeconds
* @param maxIterations
* @param maxSearchDepth
* @param minSeconds
* @param inPreAgentMoveCallback
* @param inPostAgentMoveCallback
* @param checkMoveValid
* @param moveMessageCallback
*/
public abstract void unpauseAgents
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback,
final boolean checkMoveValid,
final MoveMessageCallback moveMessageCallback
);
//-------------------------------------------------------------------------
/**
* @return List of AIs that are currently thinking
*/
public abstract List<AI> getLiveAIs();
//-------------------------------------------------------------------------
/**
* Interface for callback functions that can be called before or after agents
* select/apply their moves.
*
* @author Dennis Soemers
*/
public interface AgentMoveCallback
{
/**
* Callback function
* @param move The selected/applied move
* @return Number of milliseconds for which to sleep after calling this.
*/
long call(final Move move);
}
/**
* Interface for callback functions that can be called when moves are checked.
*
* @author Matthew Stephenson
*/
public interface MoveMessageCallback
{
/**
* Callback function
* @param message The message to display on the status tab.
*/
void call(final String message);
}
/**
* @return The moves per player.
*/
@SuppressWarnings("static-method")
public Move[] movesPerPlayer()
{
return null;
}
//-------------------------------------------------------------------------
/**
* @param m1
* @param m2
* @param context
* @return if m1 is equivalent to m2
*/
public static boolean movesEqual(final Move m1, final Move m2, final Context context)
{
if (m1.from() != m2.from() || m1.to() != m2.to())
return false;
if (m1.then().isEmpty() && m2.then().isEmpty() && m1.actions().equals(m2.actions()))
return true;
return (m1.getActionsWithConsequences(context).equals(m2.getActionsWithConsequences(context)));
}
/**
* @param m1
* @param m1Actions
* @param m2
* @param context
* @return if m1 is equivalent to m2, with m1's actions already pre-calculated.
*/
public static boolean movesEqual(final Move m1, final List<Action> m1Actions, final Move m2, final Context context)
{
if (m1.from() != m2.from() || m1.to() != m2.to())
return false;
if (m1.then().isEmpty() && m2.then().isEmpty() && m1.actions().equals(m2.actions()))
return true;
return (m1Actions.equals(m2.getActionsWithConsequences(context)));
}
//-------------------------------------------------------------------------
}
| 13,417 | 31.100478 | 136 | java |
Ludii | Ludii-master/Core/src/other/model/SimulationMove.java | package other.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import main.Status;
import main.collections.FastArrayList;
import other.AI;
import other.ThinkingThread;
import other.context.Context;
import other.move.Move;
import other.playout.PlayoutMoveSelector;
import other.trial.Trial;
/**
* Model for simulation games.
*
* @author Eric.Piette
*/
public final class SimulationMove extends Model
{
//-------------------------------------------------------------------------
/** Are we ready with our current step? */
protected transient volatile boolean ready = true;
/** Are we ready to receive external actions? */
protected transient volatile boolean running = false;
/** Currently-running thinking thread */
protected transient volatile ThinkingThread currentThinkingThread = null;
/** AI used to select a move in the last step */
protected transient AI lastStepAI = null;
/** Move selected in last step */
protected transient Move lastStepMove = null;
//-------------------------------------------------------------------------
@Override
public Move applyHumanMove(final Context context, final Move move, final int player)
{
if (!ready)
{
// only apply move if we've actually started a new step
final Move appliedMove = context.game().apply(context, move);
context.trial().setNumSubmovesPlayed(context.trial().numSubmovesPlayed() + 1);
lastStepMove = move;
ready = true;
running = false;
return appliedMove;
}
return null;
}
@Override
public Model copy()
{
return new SimulationMove();
}
@Override
public boolean expectsHumanInput()
{
return (!ready && running && (currentThinkingThread == null));
}
@Override
public List<AI> getLastStepAIs()
{
if (!ready)
return null;
return Arrays.asList(lastStepAI);
}
@Override
public List<Move> getLastStepMoves()
{
if (!ready)
return null;
return Arrays.asList(lastStepMove);
}
@Override
public synchronized void interruptAIs()
{
if (!ready)
{
if (currentThinkingThread != null)
{
AI ai = null;
try
{
ai = currentThinkingThread.interruptAI();
while (currentThinkingThread.isAlive())
{
try
{
Thread.sleep(15L);
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
}
currentThinkingThread = null;
}
catch (final NullPointerException e)
{
// do nothing
}
if (ai != null)
ai.setWantsInterrupt(false);
}
lastStepAI = null;
ready = true;
running = false;
}
}
@Override
public boolean isReady()
{
return ready;
}
@Override
public boolean isRunning()
{
return running;
}
@Override
public void randomStep(final Context context, final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback)
{
if (!ready && currentThinkingThread == null)
{
final FastArrayList<Move> legalMoves = new FastArrayList<Move>(context.game().moves(context).moves());
if (!legalMoves.isEmpty())
applyHumanMove(context, legalMoves.get(0), context.state().mover());
ready = true;
running = false;
}
}
//-------------------------------------------------------------------------
@Override
public synchronized void startNewStep(final Context context, final List<AI> ais, final double[] maxSeconds,
final int maxIterations, final int maxSearchDepth, final double minSeconds, final boolean block,
final boolean forceThreaded, final boolean forceNotThreaded, final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback)
{
startNewStep(context,ais,maxSeconds,maxIterations,maxSearchDepth,minSeconds,block,forceThreaded,forceNotThreaded,inPreAgentMoveCallback,inPostAgentMoveCallback,false,null);
}
@Override
public synchronized void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback,
final boolean checkMoveValid,
final MoveMessageCallback moveMessageCallback
)
{
if (!ready)
{
// we're already running our current step, so don't start a new one
return;
}
while (true)
{
final ThinkingThread thinkingThread = currentThinkingThread;
if (thinkingThread == null || !thinkingThread.isAlive())
break;
// TODO uncomment below if we move to Java >= 9
//Thread.onSpinWait();
}
final Game game = context.game();
ready = false;
running = true;
final Trial trial = context.trial();
if (!trial.over())
{
final FastArrayList<Move> legalMoves = new FastArrayList<Move>(context.game().moves(context).moves());
game.apply(context, legalMoves.get(0));
}
final FastArrayList<Move> legalMoves = new FastArrayList<Move>(context.game().moves(context).moves());
if (legalMoves.isEmpty())
context.trial().setStatus(new Status(0));
running = false;
ready = true;
}
//-------------------------------------------------------------------------
@Override
public void unpauseAgents(final Context context, final List<AI> ais, final double[] maxSeconds,
final int maxIterations, final int maxSearchDepth, final double minSeconds,
final AgentMoveCallback inPreAgentMoveCallback, final AgentMoveCallback inPostAgentMoveCallback, final boolean checkMoveValid, final MoveMessageCallback moveMessageCallback)
{
currentThinkingThread =
ThinkingThread.construct
(
ais.get(0),
context.game(),
ais.get(0).copyContext(context),
maxSeconds[0],
maxIterations,
maxSearchDepth,
minSeconds,
new Runnable()
{
@Override
public void run()
{
final long startTime = System.currentTimeMillis();
final long stopTime = (maxSeconds[0] > 0.0) ? startTime + (long) (maxSeconds[0] * 1000)
: Long.MAX_VALUE;
while (System.currentTimeMillis() < stopTime)
{
// Wait
}
final FastArrayList<Move> legalMoves = new FastArrayList<Move>(
context.game().moves(context).moves());
if (!legalMoves.isEmpty())
applyHumanMove(context, legalMoves.get(0), context.state().mover());
ready = true;
running = false;
}
}
);
currentThinkingThread.setDaemon(true);
currentThinkingThread.start();
}
//-------------------------------------------------------------------------
@Override
public List<AI> getLiveAIs()
{
final List<AI> ais = new ArrayList<>(1);
if (currentThinkingThread != null)
ais.add(currentThinkingThread.ai());
return ais;
}
//-------------------------------------------------------------------------
@Override
public boolean verifyMoveLegal(final Context context, final Move move)
{
return true;
}
//-------------------------------------------------------------------------
@Override
public Trial playout(final Context context, final List<AI> ais, final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector, final int maxNumBiasedActions,
final int maxNumPlayoutActions, final Random random)
{
final Game game = context.game();
int numActionsApplied = 0;
final Trial trial = context.trial();
while (!trial.over() && (maxNumPlayoutActions < 0 || maxNumPlayoutActions > numActionsApplied))
{
final FastArrayList<Move> legalMoves = new FastArrayList<Move>(context.game().moves(context).moves());
if (!legalMoves.isEmpty())
game.apply(context, legalMoves.get(0));
else
context.trial().setStatus(new Status(0));
++numActionsApplied;
}
return trial;
}
//-------------------------------------------------------------------------
@Override
public boolean callsGameMoves()
{
return true;
}
//-------------------------------------------------------------------------
/**
* @return The specified move, else a random move if it's not valid.
*/
static Move checkMoveValid
(
final boolean checkMoveValid, final Context context,
final Move move, final MoveMessageCallback callBack
)
{
if (checkMoveValid && !context.model().verifyMoveLegal(context, move))
{
final FastArrayList<Move> legalMoves = context.game().moves(context).moves();
final Move randomMove = legalMoves.get(ThreadLocalRandom.current().nextInt(legalMoves.size()));
final String msg = "illegal move detected: " + move.actions() +
", instead applying: " + randomMove;
callBack.call(msg);
System.out.println(msg);
return randomMove;
}
return move;
}
} | 8,858 | 24.311429 | 176 | java |
Ludii | Ludii-master/Core/src/other/model/SimultaneousMove.java | package other.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import game.rules.play.moves.Moves;
import main.collections.FastArrayList;
import other.AI;
import other.ThinkingThread;
import other.action.Action;
import other.action.others.ActionPass;
import other.context.Context;
import other.move.Move;
import other.playout.PlayoutMoveSelector;
import other.trial.Trial;
/**
* Model for simultaneous-move games.
*
* @author Dennis Soemers
*/
public final class SimultaneousMove extends Model
{
//-------------------------------------------------------------------------
/** Are we ready with our current step? */
protected transient boolean ready = true;
/** Are we ready to receive external actions? */
protected transient boolean running = false;
/** Moves selected per player so far */
protected transient Move[] movesPerPlayer = null;
/** Currently-running thinking threads */
protected transient ThinkingThread[] currentThinkingThreads = null;
/** AIs used to select a move in the last step */
protected transient AI[] lastStepAIs;
/** Moves selected in the last step */
protected transient Move[] lastStepMoves;
/** Callback function to call before agents apply moves */
protected transient AgentMoveCallback preAgentMoveCallback;
/** Callback function to call after agents apply moves */
protected transient AgentMoveCallback postAgentMoveCallback;
//-------------------------------------------------------------------------
@Override
public Move applyHumanMove(final Context context, final Move move, final int player)
{
if (currentThinkingThreads[player] != null)
{
// Don't interrupt AI
return null;
}
if (movesPerPlayer[player] == null)
{
addMoveForPlayer(context, move, player);
return move;
}
return null;
}
@Override
public Model copy()
{
return new SimultaneousMove();
}
@Override
public boolean expectsHumanInput()
{
if (!ready && running)
{
for (int p = 1; p < currentThinkingThreads.length; ++p)
{
if (currentThinkingThreads[p] == null && movesPerPlayer[p] == null)
return true;
}
return false;
}
else
{
return false;
}
}
@Override
public synchronized void interruptAIs()
{
if (!ready)
{
final List<AI> interruptedAIs = new ArrayList<>();
boolean stillHaveLiveAIs = false;
for (int p = 1; p < currentThinkingThreads.length; ++p)
{
if (currentThinkingThreads[p] != null)
{
final AI ai = currentThinkingThreads[p].interruptAI();
if (ai != null)
interruptedAIs.add(ai);
}
}
stillHaveLiveAIs = true;
while (stillHaveLiveAIs)
{
stillHaveLiveAIs = false;
for (int p = 1; p < currentThinkingThreads.length; ++p)
{
if (currentThinkingThreads[p] != null)
{
if (currentThinkingThreads[p].isAlive())
{
stillHaveLiveAIs = true;
break;
}
else
{
currentThinkingThreads[p] = null;
}
}
}
if (stillHaveLiveAIs)
{
try
{
Thread.sleep(15L);
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
}
}
for (final AI ai : interruptedAIs)
{
ai.setWantsInterrupt(false);
}
lastStepAIs = new AI[lastStepAIs.length];
lastStepMoves = new Move[lastStepMoves.length];
ready = true;
running = false;
}
}
@Override
public List<AI> getLastStepAIs()
{
if (!ready)
return null;
return Arrays.asList(lastStepAIs);
}
@Override
public List<Move> getLastStepMoves()
{
if (!ready)
return null;
return Arrays.asList(lastStepMoves);
}
@Override
public boolean isReady()
{
return ready;
}
@Override
public boolean isRunning()
{
return running;
}
@Override
public synchronized void randomStep
(
final Context context,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback
)
{
if (!ready)
{
final FastArrayList<Move> legalMoves = context.game().moves(context).moves();
for (int p = 1; p < currentThinkingThreads.length; ++p)
{
if (currentThinkingThreads[p] == null && movesPerPlayer[p] == null)
{
final FastArrayList<Move> playerMoves = new FastArrayList<>(legalMoves.size());
for (final Move move : legalMoves)
{
if (move.mover() == p)
playerMoves.add(move);
}
if (playerMoves.size() == 0)
{
final ActionPass actionPass = new ActionPass(true);
actionPass.setDecision(true);
final Move passMove = new Move(actionPass);
passMove.setMover(p);
if (inPreAgentMoveCallback != null)
inPreAgentMoveCallback.call(passMove);
applyHumanMove(context, passMove, p);
if (inPostAgentMoveCallback != null)
inPostAgentMoveCallback.call(passMove);
return;
}
final int r = ThreadLocalRandom.current().nextInt(playerMoves.size());
final Move move = playerMoves.get(r);
if (inPreAgentMoveCallback != null)
inPreAgentMoveCallback.call(move);
applyHumanMove(context, move, p);
if (inPostAgentMoveCallback != null)
inPostAgentMoveCallback.call(move);
}
}
}
}
//-------------------------------------------------------------------------
@Override
public synchronized void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback
)
{
startNewStep
(
context, ais, maxSeconds, maxIterations, maxSearchDepth,
minSeconds, block, forceThreaded, forceNotThreaded,
inPreAgentMoveCallback, inPostAgentMoveCallback, false, null
);
}
//-------------------------------------------------------------------------
@Override
public synchronized void startNewStep
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final boolean block,
final boolean forceThreaded,
final boolean forceNotThreaded,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback,
final boolean checkMoveValid,
final MoveMessageCallback moveMessageCallback
)
{
if (!ready)
{
// we're already running our current step, so don't start a new one
return;
}
ready = false;
preAgentMoveCallback = inPreAgentMoveCallback;
postAgentMoveCallback = inPostAgentMoveCallback;
final int numPlayers = context.game().players().count();
movesPerPlayer = new Move[numPlayers + 1];
lastStepAIs = new AI[numPlayers + 1];
lastStepMoves = new Move[numPlayers + 1];
currentThinkingThreads = new ThinkingThread[numPlayers + 1];
// compute legal moves once, then the list of legal moves can get
// copied into copies of trials for different AIs (more efficient)
final FastArrayList<Move> legalMoves = context.game().moves(context).moves();
if (block && forceNotThreaded)
{
// we're not allowed to use threads, so compute moves one by one here
for (int p = 1; p <= numPlayers; ++p)
{
if (context.active(p))
{
lastStepAIs[p] = ais.get(p);
Move move = ais.get(p).selectAction
(
context.game(),
ais.get(p).copyContext(context),
maxSeconds[p],
maxIterations,
maxSearchDepth
);
move = checkMoveValid(checkMoveValid, context, move, p, moveMessageCallback);
movesPerPlayer[p] = move;
lastStepMoves[p] = move;
}
}
// now we should be ready to advance state
applyCombinedMove(context);
}
else
{
// we're allowed to use threads to have any AIs run simultaneously
for (int p = 1; p <= numPlayers; ++p)
{
final AI agent;
if (ais == null || p >= ais.size())
agent = null;
else
agent = ais.get(p);
if (ais != null)
lastStepAIs[p] = agent;
if (context.active(p) && agent != null)
{
currentThinkingThreads[p] =
ThinkingThread.construct
(
agent,
context.game(),
agent.copyContext(context),
maxSeconds[p],
maxIterations,
maxSearchDepth,
minSeconds,
createPostThinking(context, block, p, checkMoveValid, moveMessageCallback)
);
currentThinkingThreads[p].setDaemon(true);
currentThinkingThreads[p].start();
}
else if (context.active(p))
{
// a human; auto-pass if no legal moves for this player
boolean humanHasMoves = false;
for (final Move move : legalMoves)
{
if (move.mover() == p)
{
humanHasMoves = true;
break;
}
}
if (!humanHasMoves)
{
final ActionPass actionPass = new ActionPass(true);
actionPass.setDecision(true);
final Move passMove = new Move(actionPass);
passMove.setMover(p);
if (inPreAgentMoveCallback != null)
inPreAgentMoveCallback.call(passMove);
addMoveForPlayer(context, passMove, p);
if (inPostAgentMoveCallback != null)
inPostAgentMoveCallback.call(passMove);
}
}
}
if (block)
{
// We're allowed to block, so let's wait until all threads are done
boolean threadsAlive = true;
while (threadsAlive)
{
threadsAlive = false;
for (int p = 1; p < currentThinkingThreads.length; ++p)
{
if (currentThinkingThreads[p] != null && currentThinkingThreads[p].isAlive())
{
threadsAlive = true;
break;
}
}
}
// all threads done, extract their moves
// no need to go through the synchronized method in this case
for (int p = 1; p < currentThinkingThreads.length; ++p)
{
if (currentThinkingThreads[p] != null)
{
movesPerPlayer[p] = currentThinkingThreads[p].move();
currentThinkingThreads[p] = null;
lastStepMoves[p] = movesPerPlayer[p];
}
}
// now we should be ready to advance state
applyCombinedMove(context);
}
else
{
running = true;
}
}
}
@Override
public void unpauseAgents
(
final Context context,
final List<AI> ais,
final double[] maxSeconds,
final int maxIterations,
final int maxSearchDepth,
final double minSeconds,
final AgentMoveCallback inPreAgentMoveCallback,
final AgentMoveCallback inPostAgentMoveCallback,
final boolean checkMoveValid,
final MoveMessageCallback moveMessageCallback
)
{
final int numPlayers = context.game().players().count();
currentThinkingThreads = new ThinkingThread[numPlayers + 1];
preAgentMoveCallback = inPreAgentMoveCallback;
postAgentMoveCallback = inPostAgentMoveCallback;
for (int p = 1; p <= numPlayers; ++p)
{
final AI agent;
if (ais == null || p >= ais.size())
agent = null;
else
agent = ais.get(p);
if (ais != null)
lastStepAIs[p] = agent;
if (context.active(p) && agent != null && movesPerPlayer[p] == null)
{
currentThinkingThreads[p] =
ThinkingThread.construct
(
agent,
context.game(),
agent.copyContext(context),
maxSeconds[p],
maxIterations,
maxSearchDepth,
minSeconds,
createPostThinking(context, false, p, checkMoveValid, moveMessageCallback)
);
currentThinkingThreads[p].setDaemon(true);
currentThinkingThreads[p].start();
}
}
}
//-------------------------------------------------------------------------
@Override
public List<AI> getLiveAIs()
{
final List<AI> ais = new ArrayList<>(currentThinkingThreads.length);
for (final ThinkingThread thinkingThread : currentThinkingThreads)
if (thinkingThread != null)
ais.add(thinkingThread.ai());
return ais;
}
//-------------------------------------------------------------------------
@Override
public boolean verifyMoveLegal(final Context context, final Move move)
{
boolean validMove = false;
final FastArrayList<Move> legal = new FastArrayList<Move>(context.game().moves(context).moves());
final List<Action> moveActions = move.getActionsWithConsequences(context);
final int mover = move.mover();
boolean noLegalMoveForMover = true;
for (final Move m : legal)
{
if (movesEqual(move, moveActions, m, context))
{
validMove = true;
break;
}
else if (m.mover() == mover)
{
noLegalMoveForMover = false;
}
}
if (noLegalMoveForMover && move.isPass())
validMove = true;
return validMove;
}
//-------------------------------------------------------------------------
/**
* Adds move selected by player
*
* @param context
* @param move
* @param p
*/
void addMoveForPlayer(final Context context, final Move move, final int p)
{
movesPerPlayer[p] = move;
lastStepMoves[p] = move;
maybeApplyCombinedMove(context);
}
/**
* Checks if we have all the moves we need, and if so, applies the combined move.
* Synchronized for thread-safety.
* @param context
*/
private synchronized void maybeApplyCombinedMove(final Context context)
{
// only do something if we're not ready, otherwise we've already done this
if (!ready)
{
final int numPlayers = context.game().players().count();
// check if we have moves for all active players now
for (int i = 1; i <= numPlayers; ++i)
{
if (context.active(i) && movesPerPlayer[i] == null)
{
// still missing at least one move, so we return
return;
}
}
// we have all the moves we need, so we can apply our combined move
applyCombinedMove(context);
}
}
/**
* Applies combined move and sets the model as being ready, having completed
* processing for the current time step.
* @param context
*/
private void applyCombinedMove(final Context context)
{
// gather all the actions into a single move
final List<Action> actions = new ArrayList<>();
final List<Moves> topLevelCons = new ArrayList<Moves>();
int numSubmoves = 0;
for (int p = 1; p < movesPerPlayer.length; ++p)
{
final Move move = movesPerPlayer[p];
if (move != null)
{
final Move moveToAdd = new Move(move.actions());
actions.add(moveToAdd);
++numSubmoves;
if (move.then() != null)
{
for (int i = 0; i < move.then().size(); ++i)
{
if (move.then().get(i).applyAfterAllMoves())
topLevelCons.add(move.then().get(i));
else
moveToAdd.then().add(move.then().get(i));
}
}
}
}
final Move combinedMove = new Move(actions);
combinedMove.setMover(movesPerPlayer.length);
combinedMove.then().addAll(topLevelCons);
//System.out.println(combinedMove.toDetailedString(context));
// apply move
context.game().apply(context, combinedMove);
context.trial().setNumSubmovesPlayed(context.trial().numSubmovesPlayed() + numSubmoves);
// clear movesPerPlayer
Arrays.fill(movesPerPlayer, null);
// now we're done with this time step
ready = true;
running = false;
}
/**
* @param context
* @param p
* @return A post-thinking callback for an AI thinking thread, or null
* if we're allowed to block (then we don't need callback)
*/
private Runnable createPostThinking
(
final Context context, final boolean block, final int p,
final boolean checkMoveValid, final MoveMessageCallback callBack
)
{
if (block)
return null;
return () ->
{
Move move = currentThinkingThreads[p].move();
currentThinkingThreads[p] = null;
move = checkMoveValid(checkMoveValid, context, move, p, callBack);
if (preAgentMoveCallback != null)
preAgentMoveCallback.call(move);
addMoveForPlayer(context, move, p);
if (postAgentMoveCallback != null)
postAgentMoveCallback.call(move);
};
}
//-------------------------------------------------------------------------
@Override
public Trial playout
(
final Context context, final List<AI> ais, final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector, final int maxNumBiasedActions,
final int maxNumPlayoutActions, final Random random
)
{
final Game game = context.game();
final int numPlayers = game.players().count();
int numActionsApplied = 0;
while
(
!context.trial().over()
&&
(maxNumPlayoutActions < 0 || maxNumPlayoutActions > numActionsApplied)
)
{
final Move[] movesPerPlayerPlayout = new Move[numPlayers + 1];
final Moves legal = game.moves(context);
final List<FastArrayList<Move>> legalPerPlayer = new ArrayList<>(numPlayers + 1);
legalPerPlayer.add(null);
for (int p = 1; p <= numPlayers; ++p)
legalPerPlayer.add(new FastArrayList<Move>());
for (final Move move : legal.moves())
legalPerPlayer.get(move.mover()).add(move);
for (int p = 1; p <= numPlayers; ++p)
{
if (context.active(p))
{
final AI ai;
if (ais != null)
ai = ais.get(p);
else
ai = null;
if (ai != null)
{
// Select AI move
movesPerPlayerPlayout[p] = ai.selectAction(game, ai.copyContext(context), thinkingTime, -1, -1);
}
else
{
final FastArrayList<Move> playerMoves = legalPerPlayer.get(p);
if (playerMoves.size() == 0)
{
final ActionPass actionPass = new ActionPass(true);
actionPass.setDecision(true);
final Move passMove = new Move(actionPass);
passMove.setMover(p);
playerMoves.add(passMove);
}
if
(
playoutMoveSelector == null
||
(maxNumBiasedActions >= 0 && maxNumBiasedActions < numActionsApplied)
||
playoutMoveSelector.wantsPlayUniformRandomMove()
)
{
// Select move uniformly at random
final int r = random.nextInt(playerMoves.size());
movesPerPlayerPlayout[p] = playerMoves.get(r);
}
else
{
// Let our playout move selector pick a move
movesPerPlayerPlayout[p] = playoutMoveSelector.selectMove(context, playerMoves, p, (final Move m) -> {return true;});
}
}
}
}
// gather all the actions into a single move
final List<Action> actions = new ArrayList<>();
final List<Moves> topLevelCons = new ArrayList<Moves>();
for (int p = 1; p < movesPerPlayerPlayout.length; ++p)
{
final Move move = movesPerPlayerPlayout[p];
if (move != null)
{
final Move moveToAdd = new Move(move.actions());
actions.add(moveToAdd);
if (move.then() != null)
{
for (int i = 0; i < move.then().size(); ++i)
{
if (move.then().get(i).applyAfterAllMoves())
topLevelCons.add(move.then().get(i));
else
moveToAdd.then().add(move.then().get(i));
}
}
}
}
final Move combinedMove = new Move(actions);
combinedMove.setMover(movesPerPlayerPlayout.length);
combinedMove.then().addAll(topLevelCons);
game.apply(context, combinedMove);
++numActionsApplied;
}
return context.trial();
}
//-------------------------------------------------------------------------
@Override
public boolean callsGameMoves()
{
return true;
}
@Override
public Move[] movesPerPlayer()
{
return movesPerPlayer;
}
//-------------------------------------------------------------------------
/**
* @return The specified move, else a random move if it's not valid.
*/
private static Move checkMoveValid
(
final boolean checkMoveValid, final Context context, final Move move,
final int player, final MoveMessageCallback callBack
)
{
if (checkMoveValid && !context.model().verifyMoveLegal(context, move))
{
final FastArrayList<Move> legal = extractMovesForMover(context.game().moves(context).moves(), player);
final Move randomMove = legal.get(ThreadLocalRandom.current().nextInt(legal.size()));
final String msg = "illegal move detected: " + move.actions() +
", instead applying: " + randomMove;
callBack.call(msg);
System.out.println(msg);
return randomMove;
}
return move;
}
//-------------------------------------------------------------------------
/**
* @param allMoves
* @param mover
* @return moves for player.
*/
public static FastArrayList<Move> extractMovesForMover
(
final FastArrayList<Move> allMoves, final int mover
)
{
final FastArrayList<Move> moves = new FastArrayList<Move>(allMoves.size());
for (final Move move : allMoves)
if (move.mover() == mover)
moves.add(move);
return moves;
}
//-------------------------------------------------------------------------
}
| 20,805 | 23.362998 | 124 | java |
Ludii | Ludii-master/Core/src/other/move/Move.java | package other.move;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import annotations.Hide;
import game.Game;
import game.equipment.container.other.Dice;
import game.rules.play.moves.Moves;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import game.util.directions.DirectionFacing;
import game.util.graph.Radial;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.list.array.TLongArrayList;
import gnu.trove.set.hash.TIntHashSet;
import main.Constants;
import main.Status;
import main.collections.FastArrayList;
import main.collections.FastTIntArrayList;
import other.UndoData;
import other.action.Action;
import other.action.ActionType;
import other.action.BaseAction;
import other.action.cards.ActionSetTrumpSuit;
import other.action.die.ActionSetDiceAllEqual;
import other.action.die.ActionUpdateDice;
import other.action.die.ActionUseDie;
import other.action.graph.ActionSetCost;
import other.action.graph.ActionSetPhase;
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.action.move.ActionAdd;
import other.action.move.ActionCopy;
import other.action.move.ActionInsert;
import other.action.move.ActionMoveN;
import other.action.move.ActionPromote;
import other.action.move.ActionSelect;
import other.action.move.ActionSubStackMove;
import other.action.move.move.ActionMove;
import other.action.move.remove.ActionRemove;
import other.action.others.ActionForfeit;
import other.action.others.ActionNextInstance;
import other.action.others.ActionNote;
import other.action.others.ActionPass;
import other.action.others.ActionPropose;
import other.action.others.ActionSetValueOfPlayer;
import other.action.others.ActionSwap;
import other.action.others.ActionVote;
import other.action.puzzle.ActionReset;
import other.action.puzzle.ActionSet;
import other.action.puzzle.ActionToggle;
import other.action.state.ActionAddPlayerToTeam;
import other.action.state.ActionBet;
import other.action.state.ActionForgetValue;
import other.action.state.ActionRememberValue;
import other.action.state.ActionSetAmount;
import other.action.state.ActionSetCount;
import other.action.state.ActionSetCounter;
import other.action.state.ActionSetNextPlayer;
import other.action.state.ActionSetPending;
import other.action.state.ActionSetPot;
import other.action.state.ActionSetRotation;
import other.action.state.ActionSetScore;
import other.action.state.ActionSetState;
import other.action.state.ActionSetTemp;
import other.action.state.ActionSetValue;
import other.action.state.ActionSetVar;
import other.action.state.ActionStoreStateInContext;
import other.action.state.ActionTrigger;
import other.concept.Concept;
import other.context.Context;
import other.context.TempContext;
import other.location.FullLocation;
import other.state.State;
import other.state.container.ContainerState;
import other.state.owned.Owned;
import other.state.track.OnTrackIndices;
import other.topology.Topology;
import other.topology.TopologyElement;
import other.trial.Trial;
/**
* Move made up of a list of actions for modifying the game state.
*
* @author Eric.Piette and cambolbro
*
*/
@Hide
public class Move extends BaseAction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The data of the move set during the computation whatever if this is a
* decision or not.
*/
private int from;
private int to;
private TIntArrayList between = new TIntArrayList();
private int state = -1;
private boolean oriented = true;
private int edge = -1;
/** The player making this move. */
private int mover = 0;
/** The levels to move a piece on Stacking game */
private int levelMin = 0;
private int levelMax = 0;
/** Sequence of actions making up this move. */
private final List<Action> actions;
/** Subsequents of the move. */
private final List<Moves> then = new ArrayList<>();
//-------------------------------------------------------------------------
/** The "Moves" where comes from the move. */
private transient Moves movesLudeme;
//-------------------------------------------------------------------------
/**
* @param actions
*/
public Move(final List<Action> actions)
{
this.actions = actions;
}
/**
* @param a The action to convert to a move.
*/
public Move(final Action a)
{
assert(!(a instanceof Move));
actions = new ArrayList<>(1);
actions.add(a);
from = a.from();
to = a.to();
}
/**
* @param a The first action of the move.
* @param b The second and last action of the move.
*/
public Move(final Action a, final Action b)
{
actions = new ArrayList<>(2);
actions.add(a);
actions.add(b);
from = a.from();
to = a.to();
}
/**
* Copy constructor.
*
* @param other The move to copy.
*/
public Move(final Move other)
{
from = other.from;
to = other.to;
between = new TIntArrayList(other.between);
actions = new ArrayList<Action>(other.actions);
mover = other.mover;
}
/**
* To add an action at the start of the list of moves.
*
* @param a The action
* @param list The list of moves.
*/
public Move(final Action a, final FastArrayList<Move> list)
{
actions = new ArrayList<>(list.size() + 1);
actions.add(a);
for (final Action b : list)
actions.add(b);
from = a.from();
to = a.to();
if (!list.isEmpty())
between = new TIntArrayList(list.get(0).betweenNonDecision());
}
/**
* To add an action at the end of the list of moves.
*
* @param list The list of moves.
* @param b The action.
*/
public Move(final FastArrayList<Move> list, final Action b)
{
actions = new ArrayList<>(list.size() + 1);
for (final Action a : list)
actions.add(a);
actions.add(b);
from = actions.get(0).from();
to = actions.get(0).to();
between = new TIntArrayList(list.get(0).betweenNonDecision());
}
/**
* To add a move with a specific list of moves.
*
* @param list The list of moves.
*/
public Move(final FastArrayList<Move> list)
{
actions = new ArrayList<>(list.size());
boolean hasDecision = false;
for (final Action a : list)
{
if (a.isDecision()) // to have only one decision max in the result.
if (!hasDecision)
hasDecision = true;
else
a.setDecision(false);
actions.add(a);
}
if (actions.size() > 0)
{
from = actions.get(0).from();
to = actions.get(0).to();
between = new TIntArrayList(list.get(0).betweenNonDecision());
}
}
/**
* Reconstructs a Move object from a detailed String
* (generated using toDetailedString())
* @param detailedString
*/
public Move(final String detailedString)
{
assert(detailedString.startsWith("[Move:"));
final String strBeforeActions = detailedString.substring(0, detailedString.indexOf("actions="));
final String strFrom = Action.extractData(strBeforeActions, "from");
from = (strFrom.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strFrom);
final String strTo = Action.extractData(strBeforeActions, "to");
to = (strTo.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strTo);
final String strState = Action.extractData(strBeforeActions, "state");
state = (strState.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strState);
final String strOriented = Action.extractData(strBeforeActions, "oriented");
oriented = (strOriented.isEmpty()) ? true : Boolean.parseBoolean(strOriented);
final String strEdge = Action.extractData(strBeforeActions, "edge");
edge = (strEdge.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strEdge);
final String strMover = Action.extractData(strBeforeActions, "mover");
mover = Integer.parseInt(strMover);
final String strLvlMin = Action.extractData(strBeforeActions, "levelMin");
levelMin = (strLvlMin.isEmpty()) ? Constants.GROUND_LEVEL : Integer.parseInt(strLvlMin);
final String strLvlMax = Action.extractData(strBeforeActions, "levelMax");
levelMax = (strLvlMax.isEmpty()) ? Constants.GROUND_LEVEL : Integer.parseInt(strLvlMax);
String str = detailedString;
actions = new ArrayList<>();
str = str.substring(str.indexOf(",actions=") + ",actions=".length());
while (true)
{
if (str.isEmpty())
break;
// find matching closing square bracket
int numOpenBrackets = 1;
int idx = 1;
while (numOpenBrackets > 0 && idx < str.length())
{
if (str.charAt(idx) == '[')
++numOpenBrackets;
else if (str.charAt(idx) == ']')
--numOpenBrackets;
++idx;
}
if (numOpenBrackets > 0)
{
// we reached end of string
break;
}
final int closingIdx = idx;
final String actionStr = str.substring(0, closingIdx);
if (actionStr.startsWith("[Move:") && actionStr.contains("actions="))
actions.add(new Move(actionStr));
else if (actionStr.startsWith("[Add:"))
actions.add(new ActionAdd(actionStr));
else if (actionStr.startsWith("[Insert:"))
actions.add(new ActionInsert(actionStr));
else if (actionStr.startsWith("[SetStateAndUpdateDice:"))
actions.add(new ActionUpdateDice(actionStr));
else if (actionStr.startsWith("[Move:") && actionStr.contains("count="))
actions.add(new ActionMoveN(actionStr));
else if (actionStr.startsWith("[Move:"))
actions.add(ActionMove.construct(actionStr));
else if (actionStr.startsWith("[StackMove:"))
actions.add(new ActionSubStackMove(actionStr));
else if (actionStr.startsWith("[SetValueOfPlayer:"))
actions.add(new ActionSetValueOfPlayer(actionStr));
else if (actionStr.startsWith("[SetAmount:"))
actions.add(new ActionSetAmount(actionStr));
else if (actionStr.startsWith("[Note:"))
actions.add(new ActionNote(actionStr));
else if (actionStr.startsWith("[SetPot:"))
actions.add(new ActionSetPot(actionStr));
else if (actionStr.startsWith("[Bet:"))
actions.add(new ActionBet(actionStr));
else if (actionStr.startsWith("[Pass:"))
actions.add(new ActionPass(actionStr));
else if (actionStr.startsWith("[SetTrumpSuit:"))
actions.add(new ActionSetTrumpSuit(actionStr));
else if (actionStr.startsWith("[SetPending:"))
actions.add(new ActionSetPending(actionStr));
else if (actionStr.startsWith("[Promote:"))
actions.add(new ActionPromote(actionStr));
else if (actionStr.startsWith("[Reset:"))
actions.add(new ActionReset(actionStr));
else if (actionStr.startsWith("[SetScore:"))
actions.add(new ActionSetScore(actionStr));
else if (actionStr.startsWith("[SetCost:"))
actions.add(new ActionSetCost(actionStr));
else if (actionStr.startsWith("[Propose:"))
actions.add(new ActionPropose(actionStr));
else if (actionStr.startsWith("[SetDiceAllEqual:"))
actions.add(new ActionSetDiceAllEqual(actionStr));
else if (actionStr.startsWith("[Vote:"))
actions.add(new ActionVote(actionStr));
else if (actionStr.startsWith("[Select:"))
actions.add(new ActionSelect(actionStr));
else if (actionStr.startsWith("[Set:"))
actions.add(new ActionSet(actionStr));
else if (actionStr.startsWith("[SetPhase:"))
actions.add(new ActionSetPhase(actionStr));
else if (actionStr.startsWith("[SetCount:"))
actions.add(new ActionSetCount(actionStr));
else if (actionStr.startsWith("[SetCounter:"))
actions.add(new ActionSetCounter(actionStr));
else if (actionStr.startsWith("[SetTemp:"))
actions.add(new ActionSetTemp(actionStr));
else if (actionStr.startsWith("[SetState:"))
actions.add(new ActionSetState(actionStr));
else if (actionStr.startsWith("[SetValue:"))
actions.add(new ActionSetValue(actionStr));
else if (actionStr.startsWith("[Toggle:"))
actions.add(new ActionToggle(actionStr));
else if (actionStr.startsWith("[Trigger:"))
actions.add(new ActionTrigger(actionStr));
else if (actionStr.startsWith("[Remove:"))
actions.add(ActionRemove.construct(actionStr));
else if (actionStr.startsWith("[SetNextPlayer:"))
actions.add(new ActionSetNextPlayer(actionStr));
else if (actionStr.startsWith("[Forfeit:"))
actions.add(new ActionForfeit(actionStr));
else if (actionStr.startsWith("[Swap:"))
actions.add(new ActionSwap(actionStr));
else if (actionStr.startsWith("[SetRotation:"))
actions.add(new ActionSetRotation(actionStr));
else if (actionStr.startsWith("[UseDie:"))
actions.add(new ActionUseDie(actionStr));
else if (actionStr.startsWith("[StoreStateInContext:"))
actions.add(new ActionStoreStateInContext(actionStr));
else if (actionStr.startsWith("[AddPlayerToTeam:"))
actions.add(new ActionAddPlayerToTeam(actionStr));
else if (actionStr.startsWith("[NextInstance"))
actions.add(new ActionNextInstance(actionStr));
else if (actionStr.startsWith("[Copy"))
actions.add(new ActionCopy(actionStr));
else if (actionStr.startsWith("[ForgetValue"))
actions.add(new ActionForgetValue(actionStr));
else if (actionStr.startsWith("[RememberValue"))
actions.add(new ActionRememberValue(actionStr));
else if (actionStr.startsWith("[SetVar"))
actions.add(new ActionSetVar(actionStr));
else if (actionStr.startsWith("[SetHiddenWho"))
actions.add(new ActionSetHiddenWho(actionStr));
else if (actionStr.startsWith("[SetHiddenWhat"))
actions.add(new ActionSetHiddenWhat(actionStr));
else if (actionStr.startsWith("[SetHiddenState"))
actions.add(new ActionSetHiddenState(actionStr));
else if (actionStr.startsWith("[SetHiddenRotation"))
actions.add(new ActionSetHiddenRotation(actionStr));
else if (actionStr.startsWith("[SetHiddenValue"))
actions.add(new ActionSetHiddenValue(actionStr));
else if (actionStr.startsWith("[SetHiddenCount"))
actions.add(new ActionSetHiddenCount(actionStr));
else if (actionStr.startsWith("[SetHidden"))
actions.add(new ActionSetHidden(actionStr));
else
System.err.println("Move constructor does not recognise action: " + str);
str = str.substring(closingIdx + 1); // +1 to skip over comma
}
}
//-------------------------------------------------------------------------
/**
* @return The mover.
*/
public int mover()
{
return mover;
}
/**
* Set the mover.
*
* @param who The new mover.
*/
public void setMover(final int who)
{
mover = who;
}
//-------------------------------------------------------------------------
/**
* @param context
* @return A list of all the actions that would be applied by this Move to the given Context, including consequents
*/
public List<Action> getActionsWithConsequences(final Context context)
{
return getMoveWithConsequences(context).actions();
}
/**
* @param context
* @return A Move with all actions that would be applied by this Move to the given Context, including consequents
*/
public Move getMoveWithConsequences(final Context context)
{
final Context contextCopy = new TempContext(context);
// we need to fix the RNG internal state for the full actions,
// including nondeterministic consequents, to match perfectly
final RandomProviderDefaultState realRngState = (RandomProviderDefaultState) context.rng().saveState();
contextCopy.rng().restoreState(realRngState);
// We pass true for skipping the computation of end rules, don't need to waste time on that
return contextCopy.game().apply(contextCopy, this, true);
}
//-------------------------------------------------------------------------
/**
* @return Sequence of sequence.
*/
public List<Action> actions()
{
return actions;
}
/**
* @return The subsequents of the move.
*/
public List<Moves> then()
{
return then;
}
//-------------------------------------------------------------------------
@Override
public final Action apply(final Context context, final boolean store)
{
final List<Action> returnActions = new ArrayList<>(actions.size());
final Trial trial = context.trial();
// Apply the list of actions
for (final Action action : actions)
{
final Action returnAction = action.apply(context, false);
if (returnAction instanceof Move)
returnActions.addAll(((Move) returnAction).actions);
else
returnActions.add(returnAction);
}
// Store the move if necessary
if (store)
trial.addMove(this);
// Apply the possible subsequents
// Create a list of actions to store in the trial
for (final Moves consequent : then)
{
final FastArrayList<Move> postActions = consequent.eval(context).moves();
for (final Move m : postActions)
{
// Remove the last stored action and store a list with subsequents
final Action innerApplied = m.apply(context, false);
if (innerApplied instanceof Move)
{
returnActions.addAll(((Move) innerApplied).actions);
}
else
{
returnActions.add(innerApplied);
}
// context.trial().actions().remove(context.trial().actions().size() - 1);
// context.trial().addMove(moveToStore);
}
}
if (store && context.game().hasSequenceCapture())
{
if (!containsReplayAction(returnActions))
{
final TIntArrayList sitesToRemove = context.state().sitesToRemove();
if(context.game().isStacking())
{
final ContainerState cs = context.containerState(0);
final SiteType defaultSiteType = context.board().defaultSite();
final int[] numRemoveBySite = new int[context.board().topology().getGraphElements(defaultSiteType).size()];
for (int i = sitesToRemove.size() - 1; i >= 0 ; i--)
numRemoveBySite[sitesToRemove.get(i)]++;
for(int site = 0; site < numRemoveBySite.length; site++)
{
if(numRemoveBySite[site] > 0)
{
final int numToRemove = Math.min(numRemoveBySite[site], cs.sizeStack(site, defaultSiteType));
if(numToRemove > 0)
for(int level = numToRemove - 1; level >=0 ; level--)
{
final Action remove = other.action.move.remove.ActionRemove.construct(
context.board().defaultSite(), site, level, true);
remove.apply(context, false);
returnActions.add(0, remove);
}
}
}
}
else
{
for (int i = 0; i < sitesToRemove.size();i++)
{
final int site = sitesToRemove.get(i);
final Action remove = other.action.move.remove.ActionRemove.construct(
context.board().defaultSite(), site, Constants.UNDEFINED,
true);
if (!returnActions.contains(remove))
{
remove.apply(context, false);
returnActions.add(0, remove);
}
}
}
context.state().reInitCapturedPiece();
}
}
final Move returnMove = new Move(returnActions);
returnMove.setFromNonDecision(from);
returnMove.setBetweenNonDecision(new TIntArrayList(betweenNonDecision()));
returnMove.setToNonDecision(to);
returnMove.setStateNonDecision(state);
returnMove.setOrientedMove(oriented);
returnMove.setEdgeMove(edge);
returnMove.setMover(mover);
returnMove.setLevelMaxNonDecision(levelMax);
returnMove.setLevelMinNonDecision(levelMin);
if (store)
{
// we applied extra consequents actions, so replace move in trial
trial.replaceLastMove(returnMove);
}
return returnMove;
}
//-------------------------------------------------------------------------
@Override
public Action undo(final Context context, boolean discard)
{
if(discard)
{
final Trial trial = context.trial();
final State currentState = context.state();
final Game game = context.game();
// Step 2: Restore the data modified by the last end rules or nextPhase.
// Get the previous end data.
final UndoData undoData = trial.endData().isEmpty() ? null : trial.endData().get(trial.endData().size()-1);
final double[] ranking = undoData == null ? new double[game.players().size()] : undoData.ranking();
final int[] phases = undoData == null ? new int[game.players().size()] : undoData.phases();
final Status status = undoData == null ? null : undoData.status();
final TIntArrayList winners = undoData == null ? new TIntArrayList(game.players().count()) : undoData.winners();
final TIntArrayList losers = undoData == null ? new TIntArrayList(game.players().count()) : undoData.losers();
final TIntHashSet pendingValues = undoData == null ? new TIntHashSet() : undoData.pendingValues();
final int previousCounter = undoData == null ? Constants.UNDEFINED : undoData.counter();
final TLongArrayList previousStateWithinATurn = undoData == null ? null : undoData.previousStateWithinATurn();
final TLongArrayList previousState = undoData == null ? null : undoData.previousState();
final int prev = undoData == null ? 1 : undoData.prev();
final int currentMover = undoData == null ? 1 : undoData.mover();
final int next = undoData == null ? 1 : undoData.next();
final int numTurn = undoData == null ? 0 : undoData.numTurn();
final int numTurnSamePlayer = undoData == null ? 0 : undoData.numTurnSamePlayer();
final int numConsecutivePasses = undoData == null ? 0 : undoData.numConsecutivePasses();
final FastTIntArrayList remainingDominoes = undoData == null ? null : undoData.remainingDominoes();
final BitSet visited = undoData == null ? null : undoData.visited();
final TIntArrayList sitesToRemove = undoData == null ? null : undoData.sitesToRemove();
final OnTrackIndices onTrackIndices = undoData == null ? null : undoData.onTrackIndices();
final Owned owned = undoData == null ? null : undoData.owned();
final int isDecided = undoData == null ? Constants.UNDEFINED : undoData.isDecided();
int active = 0;
if(undoData != null)
active = undoData.active();
else
{
for (int p = 1; p <= game.players().count(); ++p)
{
final int whoBit = (1 << (p - 1));
active |= whoBit;
}
}
final int[] scores = undoData == null ? new int[game.players().size()] : undoData.scores();
final double[] payoffs = undoData == null ? new double[game.players().size()] : undoData.payoffs();
final int numLossesDecided = undoData == null ? 0: undoData.numLossesDecided();
final int numWinsDecided = undoData == null ? 0: undoData.numWinsDecided();
// Restore the previous end data.
for(int i = 0; i < ranking.length; i++)
trial.ranking()[i] = ranking[i];
trial.setStatus(status);
if(winners != null)
{
context.winners().clear();
for(int i = 0; i < winners.size(); i++)
context.winners().add(winners.get(i));
}
if(losers != null)
{
context.losers().clear();
for(int i = 0; i < losers.size(); i++)
context.losers().add(losers.get(i));
}
context.setActive(active);
if(context.scores() != null)
for(int i = 0; i < context.scores().length; i++)
context.scores()[i] = scores[i];
if(context.payoffs() != null)
for(int i = 0; i < context.payoffs().length; i++)
context.payoffs()[i] = payoffs[i];
context.setNumLossesDecided(numLossesDecided);
context.setNumWinsDecided(numWinsDecided);
for(int pid = 1; pid < phases.length; pid++)
context.state().setPhase(pid, phases[pid]);
trial.removeLastEndData();
// Step 3: update the state data.
if(previousStateWithinATurn != null)
{
trial.previousStateWithinATurn().clear();
for(int i = 0; i < previousStateWithinATurn.size(); i++)
trial.previousStateWithinATurn().add(previousStateWithinATurn.get(i));
}
if(previousState != null)
{
trial.previousState().clear();
for(int i = 0; i < previousState.size(); i++)
trial.previousState().add(previousState.get(i));
}
if(remainingDominoes != null)
{
currentState.remainingDominoes().clear();
for(int i = 0; i < remainingDominoes.size(); i++)
currentState.remainingDominoes().add(remainingDominoes.get(i));
}
if(visited != null)
{
currentState.reInitVisited();
for(int site = 0; site < visited.size(); site++)
if(visited.get(site))
currentState.visit(site);
}
if(sitesToRemove != null)
{
currentState.sitesToRemove().clear();
for(int i = 0; i < sitesToRemove.size(); i++)
currentState.sitesToRemove().add(sitesToRemove.get(i));
}
// Undo the list of actions
for (int i = actions.size() - 1; i >= 0; i--)
{
final Action action = actions.get(i);
action.undo(context, false);
}
// Discard the move if necessary
trial.removeLastMove();
currentState.setPrev(prev);
currentState.setMover(currentMover);
currentState.setNext(next);
currentState.setNumTurn(numTurn);
currentState.setTurnSamePlayer(numTurnSamePlayer);
currentState.setNumConsecutivesPasses(numConsecutivePasses);
currentState.setOnTrackIndices(onTrackIndices);
currentState.setOwned(owned);
currentState.setIsDecided(isDecided);
// Step 5: To update the sum of the dice container.
if (game.hasHandDice())
{
for (int i = 0; i < game.handDice().size(); i++)
{
final Dice dice = game.handDice().get(i);
final ContainerState cs = context.containerState(dice.index());
final int siteFrom = context.sitesFrom()[dice.index()];
final int siteTo = context.sitesFrom()[dice.index()] + dice.numSites();
int sum = 0;
for (int site = siteFrom; site < siteTo; site++)
{
sum += context.components()[cs.whatCell(site)].getFaces()[cs.stateCell(site)];
// context.state().currentDice()[i][site - siteFrom] =
// context.components().get(cs.what(site))
// .getFaces()[cs.state(site)];
}
currentState.sumDice()[i] = sum;
}
}
// Step 6: restore some data in the state.
currentState.restorePending(pendingValues);
currentState.setCounter(previousCounter);
trial.clearLegalMoves();
// Make sure our "real" context's RNG actually gets used and progresses
// For temporary copies of context, we need not do this
if (!(context instanceof TempContext) && !trial.over() && context.game().isStochasticGame())
context.game().moves(context);
}
else
{
// Undo the list of actions
for (int i = actions.size() - 1; i >= 0; i--)
{
final Action action = actions.get(i);
action.undo(context, false);
}
}
return this;
}
//-------------------------------------------------------------------------
/**
* @param actionsList
* @return True if the list of actions to apply contains SetNextPlayer.
*/
@SuppressWarnings("static-method")
public boolean containsReplayAction(final List<Action> actionsList)
{
for (final Action action : actionsList)
if (action instanceof ActionSetNextPlayer)
return true;
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean isPass()
{
boolean foundPass = false;
for (final Action a : actions)
{
if (a.isDecision() && !a.isPass())
return false;
else
foundPass = foundPass || a.isPass();
}
return foundPass;
}
@Override
public boolean isForfeit()
{
boolean foundForfeit = false;
for (final Action a : actions)
{
if (a.isDecision() && !a.isForfeit())
return false;
else
foundForfeit = foundForfeit || a.isForfeit();
}
return foundForfeit;
}
@Override
public boolean isSwap()
{
boolean foundSwap = false;
for (final Action a : actions)
{
if (a.isDecision() && !a.isSwap())
return false;
else
foundSwap = foundSwap || a.isSwap();
}
return foundSwap;
}
@Override
public boolean isVote()
{
boolean foundVote = false;
for (final Action a : actions)
{
if (a.isDecision() && !a.isVote())
return false;
else
foundVote = foundVote || a.isVote();
}
return foundVote;
}
@Override
public boolean isPropose()
{
boolean foundPropose = false;
for (final Action a : actions)
{
if (a.isDecision() && !a.isPropose())
return false;
else
foundPropose = foundPropose || a.isPropose();
}
return foundPropose;
}
@Override
public boolean isAlwaysGUILegal()
{
for (final Action a : actions)
if (a.isDecision() && a.isAlwaysGUILegal())
return true;
return false;
}
@Override
public int playerSelected()
{
for (final Action a : actions)
if (a.isDecision())
return a.playerSelected();
return Constants.UNDEFINED;
}
@Override
public boolean isOtherMove()
{
boolean foundOtherMove = false;
for (final Action a : actions)
{
if (a.isDecision() && !a.isOtherMove())
return false;
else
foundOtherMove = foundOtherMove || a.isOtherMove();
}
return foundOtherMove;
}
@Override
public boolean containsNextInstance()
{
for (final Action a : actions)
{
if (a.containsNextInstance())
return true;
}
return false;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
for (final Action a : actions)
{
if (sb.length() > 0)
sb.append(", ");
sb.append(a.toString());
}
if (actions.size() > 1)
{
sb.insert(0, '[');
sb.append(']');
}
else if (actions.isEmpty())
{
sb.append("[Empty Move]");
}
if (then.size() > 0)
{
sb.append(then.toString());
}
return sb.toString();
}
@Override
public String toTurnFormat(final Context context, final boolean useCoords)
{
final StringBuilder sb = new StringBuilder();
for (final Action a : actions)
{
if (sb.length() > 0)
sb.append(", ");
sb.append(a.toTurnFormat(context, useCoords));
}
if (actions.size() > 1)
{
sb.insert(0, '[');
sb.append(']');
}
else if (actions.isEmpty())
{
sb.append("[Empty Move]");
}
if (then.size() > 0)
{
sb.append(then.toString());
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public int from()
{
for (final Action a : actions)
if (a.isDecision())
return a.from();
return Constants.UNDEFINED;
}
@Override
public ActionType actionType()
{
for (final Action a : actions)
if (a.isDecision())
return a.actionType();
return null;
}
/**
* @return The from site after applying the subsequents.
*/
public int fromAfterSubsequents()
{
if (actions.size() > 0)
{
int i = 1;
while (actions.get(actions.size() - i).from() == Constants.OFF)
{
i++;
if ((actions.size() - i) < 0)
return Constants.OFF;
}
return actions.get(actions.size() - i).from();
}
return Constants.UNDEFINED;
}
/**
* @return The from site after applying the subsequents.
*/
public int levelFromAfterSubsequents()
{
if (actions.size() > 0)
{
int i = 1;
while (actions.get(actions.size() - i).from() == Constants.OFF)
{
i++;
if ((actions.size() - i) < 0)
return Constants.OFF;
}
return actions.get(actions.size() - i).levelFrom();
}
return Constants.UNDEFINED;
}
@Override
public int levelFrom()
{
for (final Action a : actions)
if (a.isDecision())
return a.levelFrom();
return 0;
}
@Override
public int to()
{
for (final Action a : actions)
if (a.isDecision())
return a.to();
return Constants.UNDEFINED;
}
/**
* @return The to site after applying the subsequents.
*/
public int toAfterSubsequents()
{
if (actions.size() > 0)
{
int i = 1;
while (actions.get(actions.size() - i).to() == Constants.OFF)
{
i++;
if ((actions.size() - i) < 0)
return Constants.OFF;
}
return actions.get(actions.size() - i).to();
}
return Constants.UNDEFINED;
}
/**
* @return The to site after applying the subsequents.
*/
public int levelToAfterSubsequents()
{
if (actions.size() > 0)
{
int i = 1;
while (actions.get(actions.size() - i).to() == Constants.OFF)
{
i++;
if ((actions.size() - i) < 0)
return Constants.OFF;
}
return actions.get(actions.size() - i).levelTo();
}
return Constants.UNDEFINED;
}
@Override
public int levelTo()
{
for (final Action a : actions)
if (a.isDecision())
return a.levelTo();
return 0;
}
@Override
public int what()
{
for (final Action a : actions)
if (a.isDecision())
return a.what();
return Constants.NO_PIECE;
}
@Override
public int state()
{
for (final Action a : actions)
if (a.isDecision())
return a.state();
return 0;
}
@Override
public int count()
{
for (final Action a : actions)
if (a.isDecision())
return a.count();
return 1;
}
@Override
public boolean isStacking()
{
for (final Action a : actions)
if (a.isDecision())
return a.isStacking();
return false;
}
@Override
public boolean[] hidden()
{
for (final Action a : actions)
if (a.isDecision())
return a.hidden();
return null;
}
@Override
public int who()
{
for (final Action a : actions)
if (a.isDecision())
return a.who();
return 0;
}
@Override
public boolean isDecision()
{
for (final Action a : actions)
if (a.isDecision())
return true;
return false;
}
@Override
public boolean isForced()
{
for (final Action a : actions)
if (a.isForced())
return true;
return false;
}
@Override
public final void setDecision(final boolean decision)
{
for(final Action a : actions())
a.setDecision(decision);
}
@Override
public final Move withDecision(final boolean dec)
{
return this;
}
@Override
public boolean matchesUserMove(final int siteA, final int levelA, final SiteType graphElementTypeA, final int siteB,
final int levelB, final SiteType graphElementTypeB)
{
return (fromNonDecision() == siteA && levelFrom() == levelA && fromType() == graphElementTypeA && toNonDecision() == siteB
&& levelTo() == levelB && toType() == graphElementTypeB);
}
/**
* @return The from site of the move whatever the decision action.
*/
public int fromNonDecision()
{
return from;
}
/**
* To set the from site of the move what the decision action.
*
* @param from The new from site.
*/
public void setFromNonDecision(final int from)
{
this.from = from;
}
/**
* @return The to site of the move whatever the decision action.
*/
public int toNonDecision()
{
return to;
}
/**
* To set the to site of the move whatever the decision action.
*
* @param to The new to site.
*/
public void setToNonDecision(final int to)
{
this.to = to;
}
/**
* @return The between sites of the move whatever the decision action.
*/
public TIntArrayList betweenNonDecision()
{
return between;
}
/**
* To set the between sites of the move whatever the decision action.
*
* @param between The new between sites.
*/
public void setBetweenNonDecision(final TIntArrayList between)
{
this.between = between;
}
/**
* @param fromW The new from
* @return The move.
*/
public Move withFrom(final int fromW)
{
from = fromW;
return this;
}
/**
* @param toW The new to.
* @return The move.
*/
public Move withTo(final int toW)
{
to = toW;
return this;
}
/**
* @param m New mover
* @return The move.
*/
public Move withMover(final int m)
{
mover = m;
return this;
}
/**
* @return The minimum level of the move whatever the decision action.
*/
public int levelMinNonDecision()
{
return levelMin;
}
/**
* Set the minimum level of the move whatever the decision action.
*
* @param levelMin The minimum level.
*/
public void setLevelMinNonDecision(final int levelMin)
{
this.levelMin = levelMin;
}
/**
* @return The maximum level of the move whatever the decision action.
*/
public int levelMaxNonDecision()
{
return levelMax;
}
/**
* Set the maximum level of the move whatever the decision action.
*
* @param levelMax The maximum level.
*/
public void setLevelMaxNonDecision(final int levelMax)
{
this.levelMax = levelMax;
}
/**
* @return True if the move is oriented.
*/
public boolean isOrientedMove()
{
return oriented;
}
/**
* To set the move to be an edge move.
*
* @param edge The value.
*/
public void setEdgeMove(final int edge)
{
this.edge = edge;
}
/**
* @return True if the move is an edge move.
*/
public int isEdgeMove()
{
return edge;
}
/**
* Set the state value of the move whatever the decision action.
*
* @param state The new value.
*/
public void setStateNonDecision(final int state)
{
this.state = state;
}
/**
* @return The state value of the move whatever if the decision action.
*/
public int stateNonDecision()
{
return state;
}
/**
* Set the orientation of the move.
*
* @param oriented True if the move has to be oriented.
*/
public void setOrientedMove(final boolean oriented)
{
this.oriented = oriented;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((actions == null) ? 0 : actions.hashCode());
result = prime * result + ((then == null) ? 0 : then.hashCode());
result = prime * result + (from + to); // from and to added here due to use of oriented in equals()
result = prime * result + levelMax;
result = prime * result + levelMin;
result = prime * result + state;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof Move))
return false;
final Move other = (Move) obj;
if (actions == null)
{
if (other.actions != null)
return false;
}
else
{
if (!actions.equals(other.actions))
{
return false;
}
}
if (then == null)
{
if (other.then != null)
return false;
}
else if (!then.equals(other.then))
{
return false;
}
if (oriented || other.oriented)
{
return (from == other.from &&
levelMax == other.levelMax &&
levelMin == other.levelMin &&
to == other.to &&
state == other.state);
}
else
{
return ((from == other.from || from == other.to) &&
levelMax == other.levelMax &&
levelMin == other.levelMin &&
(to == other.from || to == other.to) &&
state == other.state);
}
}
//-------------------------------------------------------------------------
@Override
public String toTrialFormat(final Context context)
{
final StringBuilder sb = new StringBuilder();
sb.append("[Move:");
sb.append("mover=" + mover);
if (from != Constants.UNDEFINED)
sb.append(",from=" + from);
if (to != Constants.UNDEFINED)
sb.append(",to=" + to);
if (state != Constants.UNDEFINED)
sb.append(",state=" + state);
if (oriented == false)
sb.append(",oriented=" + oriented);
if (edge != Constants.UNDEFINED)
sb.append(",edge=" + edge);
if (levelMin != Constants.GROUND_LEVEL && levelMax != Constants.GROUND_LEVEL)
{
sb.append(",levelMin=" + levelMin);
sb.append(",levelMax=" + levelMax);
}
final List<Action> allActions = (context == null) ? actions : getActionsWithConsequences(context);
sb.append(",actions=");
for (int i = 0; i < allActions.size(); ++i)
{
sb.append(allActions.get(i).toTrialFormat(context));
if (i < allActions.size() - 1)
sb.append(",");
}
sb.append(']');
return sb.toString();
}
@Override
public String getDescription()
{
return "Move";
}
//-------------------------------------------------------------------------
@Override
public int rotation()
{
for (final Action a : actions)
if (a.isDecision())
return a.rotation();
return 0;
}
@Override
public SiteType fromType()
{
for (final Action a : actions)
if (a.isDecision())
return a.fromType();
for (final Action a : actions)
if (a.fromType() != null)
return a.fromType();
return SiteType.Cell;
}
@Override
public SiteType toType()
{
for (final Action a : actions)
if (a.isDecision())
return a.toType();
for (final Action a : actions)
if (a.toType() != null)
return a.toType();
return SiteType.Cell;
}
//-------------------------------------------------------------------------
/**
* @return The from full location.
*/
public FullLocation getFromLocation()
{
return new FullLocation(from, levelFrom(), fromType());
}
/**
* @return The to full location.
*/
public FullLocation getToLocation()
{
return new FullLocation(to, levelTo(), toType());
}
//-------------------------------------------------------------------------
/**
* @param topo The topology.
* @return The direction of the move if that move has one.
*/
public Direction direction(final Topology topo)
{
// No direction if in the same site, or in no site, or not the site type.
if (from == to || from == Constants.UNDEFINED || to == Constants.UNDEFINED || !fromType().equals(toType()))
return null;
final SiteType type = toType();
// No direction if not in the board.
if (from >= topo.getGraphElements(type).size())
return null;
// No direction if not in the board.
if (to >= topo.getGraphElements(type).size())
return null;
final TopologyElement fromElement = topo.getGraphElement(type, from);
final TopologyElement toElement = topo.getGraphElement(type, to);
final List<DirectionFacing> directionsSupported = topo.supportedDirections(RelationType.All, type);
for (final DirectionFacing direction : directionsSupported)
{
final AbsoluteDirection absDirection = direction.toAbsolute();
final List<Radial> radials = topo.trajectories().radials(type, fromElement.index(), absDirection);
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length; toIdx++)
{
final int toRadial = radial.steps()[toIdx].id();
if (toRadial == toElement.index())
{
return absDirection;
}
}
}
}
return null;
}
//-------------------------------------------------------------------------
/**
* @return The Moves concepts computed thanks to the action concepts.
*/
@Override
public BitSet concepts(final Context context, final Moves ludeme)
{
final BitSet moveConcepts = new BitSet();
for (final Action action : getActionsWithConsequences(context))
moveConcepts.or(action.concepts(context, ludeme));
return moveConcepts;
}
/**
* @param context The Context.
* @return The Moves concepts computed thanks to the action/move concepts.
*/
public BitSet moveConcepts(final Context context)
{
final BitSet moveConcepts = new BitSet();
for (final Action action : getActionsWithConsequences(context))
moveConcepts.or(action.concepts(context, movesLudeme));
return moveConcepts;
}
/**
* @param context The Context.
* @return The values associated with the Moves concepts computed thanks to the action/move concepts.
*/
public TIntArrayList moveConceptsValue(final Context context)
{
final TIntArrayList moveConceptsValues = new TIntArrayList();
for(int i = 0; i < Concept.values().length; i++)
moveConceptsValues.add(0);
for (final Action action : getActionsWithConsequences(context))
{
BitSet actionConcepts = action.concepts(context, movesLudeme);
for(int i = 0; i < Concept.values().length; i++)
if(actionConcepts.get(i))
moveConceptsValues.set(i, moveConceptsValues.get(i) + 1);
}
//
// System.out.println("Move is " + this);
//
// for(int i = 0; i < Concept.values().length; i++)
// if(moveConceptsValues.get(i) != 0)
// System.out.println("Concept = " + Concept.values()[i] + " value = " + moveConceptsValues.get(i));
//
// System.out.println();
return moveConceptsValues;
}
/**
* @return The move ludemes.
*/
public Moves movesLudeme()
{
return movesLudeme;
}
/**
* To set the moves ludemes.
*
* @param movesLudeme The moves.
*/
public void setMovesLudeme(final Moves movesLudeme)
{
this.movesLudeme = movesLudeme;
}
//-------------------------------------------------------------------------
/**
* @return A short string representation of this move's action descriptions.
*/
public String actionDescriptionStringShort()
{
String actionString = "";
for (final Action a : actions())
actionString += a.getDescription() + ", ";
actionString = actionString.substring(0, actionString.length()-2);
return actionString;
}
/**
* @param context
* @param useCoords
* @return A long string representation of this move's action descriptions.
*/
public String actionDescriptionStringLong(final Context context, final boolean useCoords)
{
String actionString = "";
for (final Action a : actions())
{
String moveLocations = a.toTurnFormat(context, useCoords);
if (moveLocations.endsWith("-"))
moveLocations = moveLocations.substring(0, moveLocations.length()-1);
actionString += a.getDescription() + " (" + moveLocations + "), ";
}
actionString = actionString.substring(0, actionString.length()-2);
return actionString;
}
//-------------------------------------------------------------------------
}
| 45,231 | 25.175926 | 124 | java |
Ludii | Ludii-master/Core/src/other/move/MoveScore.java | package other.move;
/**
* Record of a move and its estimated score.
* @author cambolbro
*/
public class MoveScore
{
private final Move move;
private final float score;
/**
* @param move The move.
* @param score The score.
*/
public MoveScore(final Move move, final float score)
{
this.move = move;
this.score = score;
}
@Override
public String toString() {
return move.toString() + " score:" + score;
}
/**
* @return The move.
*/
public Move move()
{
return move;
}
/**
* @return The score.
*/
public float score()
{
return score;
}
}
| 592 | 12.477273 | 53 | java |
Ludii | Ludii-master/Core/src/other/move/MoveSequence.java | package other.move;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Represents, and provides views of, a sequence of moves. Every Move object
* is expected to be immutable, and MoveSequences are expected to never shrink
* (but they can grow). A MoveSequence does not necessarily store all of the moves
* in a list itself, but may also point to a parent MoveSequence which stores the
* initial part of a sequence.
*
* By allowing links to parent MoveSequences, we can avoid time-consuming copying
* and excessive memory consumption when dealing with very long MoveSequences.
*
* @author Dennis Soemers
*/
public class MoveSequence implements Serializable
{
//-----------------------------------------------------------------------------
private static final long serialVersionUID = 1L;
//-----------------------------------------------------------------------------
/** Our parent MoveSequence */
protected final MoveSequence parent;
/** List of move objects */
private final List<Move> moves;
/**
* Are we a parent of a different Move Sequence?
* (if we are, we'll no longer be allowed to append moves to our list)
*/
private boolean isParent = false;
/** Number of moves in the complete chain of parent sequences, or 0 if no parent */
private final int cumulativeParentSize;
//-----------------------------------------------------------------------------
/**
* Constructor
* @param parent
*/
public MoveSequence(final MoveSequence parent)
{
this.parent = parent;
this.moves = new ArrayList<Move>(1);
if (parent != null)
{
cumulativeParentSize = parent.movesList().size() + parent.cumulativeParentSize;
parent.isParent = true;
}
else
{
cumulativeParentSize = 0;
}
}
/**
* Constructor which allows for invalidation
* @param parent
* @param allowInvalidation
*/
public MoveSequence(final MoveSequence parent, final boolean allowInvalidation)
{
this.parent = parent;
this.moves = new ArrayList<Move>(1); // Very often only need to add 1 move after (temp) copy
if (parent != null)
{
cumulativeParentSize = parent.movesList().size() + parent.cumulativeParentSize;
if (!allowInvalidation)
parent.isParent = true;
}
else
{
cumulativeParentSize = 0;
}
}
//-----------------------------------------------------------------------------
/**
* Adds the given move to end of sequence, and returns updated move sequence.
* @param move
* @return Updated MoveSequence. NOTE: this may be a different object altogether,
* this object may remain unchanged if it already is a parent of other sequences!
*/
public MoveSequence add(final Move move)
{
if (isParent)
{
final MoveSequence newSeq = new MoveSequence(this);
newSeq.add(move);
return newSeq;
}
moves.add(move);
return this;
}
/**
* @param idx
* @return Move at given index in sequence
*/
public Move getMove(final int idx)
{
final List<MoveSequence> parents = new ArrayList<MoveSequence>();
MoveSequence nextParent = parent;
while (nextParent != null)
{
parents.add(nextParent);
nextParent = nextParent.parent;
}
int sublistIdx = idx;
for (int i = parents.size() - 1; i >= 0; --i)
{
final List<Move> sublist = parents.get(i).movesList();
if (sublistIdx < sublist.size())
return sublist.get(sublistIdx);
else
sublistIdx -= sublist.size();
}
return moves.get(sublistIdx);
}
/**
* Replaces the last move in this sequence with the given new move
* @param move
*/
public void replaceLastMove(final Move move)
{
moves.set(moves.size() - 1, move);
}
//-----------------------------------------------------------------------------
/**
* @return The last move in this sequence, or null if it's empty
*/
public Move removeLastMove()
{
final int size = moves.size();
if (size != 0)
{
final Move move = moves.get(size -1);
moves.remove(moves.size()-1);
return move;
}
return null;
}
/**
* @return The last move in this sequence, or null if it's empty
*/
public Move lastMove()
{
final int size = moves.size();
if (size != 0)
return moves.get(size - 1);
if (parent != null)
return parent.lastMove();
return null;
}
/**
* @param pid The index of the player.
* @return Last move of a specific player.
*/
public Move lastMove(final int pid)
{
for (int i = moves.size() - 1; i >= 0; i--)
{
final Move m = moves.get(i);
if (m.mover() == pid)
return m;
}
if (parent != null)
return parent.lastMove(pid);
return null;
}
/**
* @return Number of moves in complete sequence (including chain of parents)
*/
public int size()
{
return moves.size() + cumulativeParentSize;
}
//-----------------------------------------------------------------------------
/**
* Generates a complete list of all the moves
* @return Complete list of moves
*/
public List<Move> generateCompleteMovesList()
{
final List<MoveSequence> parents = new ArrayList<MoveSequence>();
MoveSequence nextParent = parent;
while (nextParent != null)
{
parents.add(nextParent);
nextParent = nextParent.parent;
}
final List<Move> completeMovesList = new ArrayList<Move>();
for (int i = parents.size() - 1; i >= 0; --i)
{
completeMovesList.addAll(parents.get(i).movesList());
}
completeMovesList.addAll(moves);
return completeMovesList;
}
//-----------------------------------------------------------------------------
/**
* @return An iterator that iterates through all the moves in reverse order
*/
public Iterator<Move> reverseMoveIterator()
{
return new Iterator<Move>()
{
private MoveSequence currSeq = MoveSequence.this;
private int currIdx = currSeq.movesList().size() - 1;
@Override
public boolean hasNext()
{
return currIdx >= 0;
}
@Override
public Move next()
{
final Move move = currSeq.movesList().get(currIdx--);
updateCurrSeq();
return move;
}
protected Iterator<Move> updateCurrSeq()
{
while (currIdx < 0)
{
currSeq = currSeq.parent;
if (currSeq == null)
break;
currIdx = currSeq.movesList().size() - 1;
}
return this;
}
}.updateCurrSeq();
}
//-----------------------------------------------------------------------------
/**
* @return List of moves stored in just this part of the sequence
*/
protected List<Move> movesList()
{
return moves;
}
//-----------------------------------------------------------------------------
}
| 6,730 | 22.130584 | 94 | java |
Ludii | Ludii-master/Core/src/other/move/MoveUtilities.java | package other.move;
import annotations.Hide;
import game.rules.play.moves.Moves;
import game.rules.play.moves.nonDecision.effect.Then;
import main.collections.FastArrayList;
import other.context.Context;
/**
* Helper functions for dealing with the complexity of moves
*
* @author mrraow and Dennis Soemers
*/
@Hide
public final class MoveUtilities
{
/** Utility class - do not construct */
private MoveUtilities()
{
}
/**
* This code hides all the complexity of chaining a series of rules into a
* single call. It is safe to call even if next or current action is empty. It
* will avoid adding unnecessary ActionCompound wrappers. Result will be cross
* product of currentAction and generated list from next, but we will add
* currentAction alone if the generated list is empty.
*
* @param context
* @param ourActions parent list which will be returned
* @param nextRule may be null if there are no further actions in the chain
* @param currentAction after which we are calling 'next' - may be null if we
* are delegating
* @param prepend new action goes before passed in action if true
*/
public static void chainRuleCrossProduct
(
final Context context, final Moves ourActions, final Moves nextRule,
final Move currentAction, final boolean prepend
)
{
// 0. Sanity check and cleaner code
if (nextRule == null)
{
if (currentAction != null)
ourActions.moves().add(currentAction);
return;
}
// 1. Get the list
final Moves generated = nextRule.eval(context);
// 2. Generate the cross product
if (currentAction == null)
{
ourActions.moves().addAll(generated.moves());
}
else //if (generated.moves().size() == 0 && currentAction != null)
{
assert (generated.moves().isEmpty());
ourActions.moves().add(currentAction);
}
}
/**
* This code hides all the complexity of chaining a series of rules into a
* single call. It is safe to call even if next or current action is empty. It
* will avoid adding unnecessary ActionCompound wrappers. Result will be cross
* product of currentAction and generated list from next, but we will add
* currentAction alone if the generated list is empty.
*
* @param context
* @param nextRule may be null if there are no further actions in the chain
* @param currentAction after which we are calling 'next' - may be null if we
* are delegating
* @param prepend new action goes before passed in action if true
* @param decision True if this is a decision.
* @return single compound action
*/
public static Move chainRuleWithAction
(
final Context context, final Moves nextRule,
final Move currentAction, final boolean prepend, final boolean decision
)
{
// 0. Sanity check and cleaner code
if (nextRule == null)
return currentAction;
// 1. Get the list
final Moves generated = nextRule.eval(context);
if (generated.moves().isEmpty())
return currentAction;
if (generated.moves().size() > 1)
{
if (!decision)
for (final Move m : generated.moves())
{
m.setFromNonDecision(m.actions().get(0).from());
m.setToNonDecision(m.actions().get(0).to());
m.setDecision(false);
}
return prepend ? new Move(generated.moves(), currentAction)
: new Move(currentAction, generated.moves());
}
final Move m = generated.moves().get(0);
if (!decision)
m.setDecision(false);
// 2. Generate the cross product
if (currentAction == null)
return m;
return prepend ? new Move(m, currentAction)
: new Move(currentAction, generated.moves().get(0));
}
//-------------------------------------------------------------------------
/**
* Sets relevant data from the given generating Moves ludeme for each of the moves
* in the given list of generated moves.
* @param moves
* @param generatingLudeme
*/
public static void setGeneratedMovesData(final FastArrayList<Move> moves, final Moves generatingLudeme)
{
final Then cons = generatingLudeme.then();
if (cons != null)
{
for (int i = 0; i < moves.size(); ++i)
{
final Move m = moves.get(i);
m.then().add(cons.moves());
m.setMovesLudeme(generatingLudeme);
}
}
else
{
for (int i = 0; i < moves.size(); ++i)
{
final Move m = moves.get(i);
m.setMovesLudeme(generatingLudeme);
}
}
}
/**
* Sets relevant data from the given generating Moves ludeme for each of the moves
* in the given list of generated moves.
* @param moves
* @param generatingLudeme
* @param mover Also set the mover of the generated moves to given mover
*/
public static void setGeneratedMovesData(final FastArrayList<Move> moves, final Moves generatingLudeme, final int mover)
{
final Then cons = generatingLudeme.then();
if (cons != null)
{
for (int i = 0; i < moves.size(); ++i)
{
final Move m = moves.get(i);
m.then().add(cons.moves());
m.setMovesLudeme(generatingLudeme);
m.setMover(mover);
}
}
else
{
for (int i = 0; i < moves.size(); ++i)
{
final Move m = moves.get(i);
m.setMovesLudeme(generatingLudeme);
m.setMover(mover);
}
}
}
//-------------------------------------------------------------------------
}
| 5,269 | 27.333333 | 121 | java |
Ludii | Ludii-master/Core/src/other/move/MovesIterator.java | package other.move;
import java.util.Iterator;
import java.util.function.BiPredicate;
import other.context.Context;
/**
* Abstract class for iterators over moves. Includes the additional abstract "canMoveConditionally"
* method for optimisation purposes, on top of the standard Iterator interface.
*
* @author Dennis Soemers
*/
public abstract class MovesIterator implements Iterator<Move>
{
/**
* NOTE: this is used because it allows us to return true as soon as we find one move
* that satisfies the given condition, and don't need to also generate the next legal
* move after that as we typically would in a normal iterator-based implementation.
*
* @param predicate
* @return True if this moves iterator contains at least one move that
* satisfies the given condition for a given context.
*/
public abstract boolean canMoveConditionally(final BiPredicate<Context, Move> predicate);
}
| 919 | 30.724138 | 99 | java |
Ludii | Ludii-master/Core/src/other/playout/HeuristicMoveSelector.java | package other.playout;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import main.collections.FastArrayList;
import metadata.ai.heuristics.Heuristics;
import other.RankUtils;
import other.context.Context;
import other.context.TempContext;
import other.move.Move;
/**
* Heuristic-based playout move selector
*
* @author Dennis Soemers
*/
public class HeuristicMoveSelector extends PlayoutMoveSelector
{
/** Big constant, probably bigger than any heuristic score */
protected final float TERMINAL_SCORE_MULT = 100000.f;
/** Heuristic function to use */
protected Heuristics heuristicValueFunction = null;
/**
* Default constructor; will have to make sure to call setHeuristics() before using this,
* and also make sure that the heuristics are initialised.
*/
public HeuristicMoveSelector()
{
// Do nothing
}
/**
* Constructor with heuristic value function to use already passed in at construction time.
* This constructor will also ensure that the heuristic is initialised for the given game.
*
* @param heuristicValueFunction
* @param game
*/
public HeuristicMoveSelector(final Heuristics heuristicValueFunction, final Game game)
{
this.heuristicValueFunction = heuristicValueFunction;
heuristicValueFunction.init(game);
}
@Override
public Move selectMove
(
final Context context,
final FastArrayList<Move> maybeLegalMoves,
final int p,
final IsMoveReallyLegal isMoveReallyLegal
)
{
final Game game = context.game();
final List<Move> bestMoves = new ArrayList<Move>();
float bestValue = Float.NEGATIVE_INFINITY;
// boolean foundLegalMove = false;
for (final Move move : maybeLegalMoves)
{
if (isMoveReallyLegal.checkMove(move))
{
// foundLegalMove = true;
final TempContext copyContext = new TempContext(context);
game.apply(copyContext, move);
float heuristicScore = 0.f;
if (copyContext.trial().over() || !copyContext.active(p))
{
// terminal node (at least for maximising player)
heuristicScore = (float) RankUtils.agentUtilities(copyContext)[p] * TERMINAL_SCORE_MULT;
}
else
{
for (int player = 1; player <= game.players().count(); ++player)
{
if (copyContext.active(player))
{
final float playerScore = heuristicValueFunction.computeValue(copyContext, player, 0.f);
if (player == p)
{
// Need to add this score
heuristicScore += playerScore;
}
else
{
// Need to subtract
heuristicScore -= playerScore;
}
}
}
}
if (heuristicScore > bestValue)
{
bestValue = heuristicScore;
bestMoves.clear();
bestMoves.add(move);
}
else if (heuristicScore == bestValue)
{
bestMoves.add(move);
}
}
}
if (bestMoves.size() > 0)
return bestMoves.get(ThreadLocalRandom.current().nextInt(bestMoves.size()));
else
return null;
}
/**
* @return Heuristic function to use
*/
public Heuristics heuristicValueFunction()
{
return heuristicValueFunction;
}
/**
* Set the heuristics to use
* @param heuristics
*/
public void setHeuristics(final Heuristics heuristics)
{
this.heuristicValueFunction = heuristics;
}
}
| 3,295 | 22.542857 | 95 | java |
Ludii | Ludii-master/Core/src/other/playout/HeuristicSamplingMoveSelector.java | package other.playout;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import main.collections.FastArrayList;
import metadata.ai.heuristics.Heuristics;
import other.context.Context;
import other.move.Move;
import other.move.MoveScore;
/**
* Heuristic-based playout move selector using Heuristic Sampling.
*
* @author Eric.Piette (based on code of Dennis Soemers and Cameron Browne)
*/
public class HeuristicSamplingMoveSelector extends PlayoutMoveSelector
{
/** Big constant, probably bigger than any heuristic score */
protected final float TERMINAL_SCORE_MULT = 100000.f;
/** Score we give to winning opponents in paranoid searches in states where game is still going (> 2 players) */
private static final float PARANOID_OPP_WIN_SCORE = 10000.f;
private static final float WIN_SCORE = 10000.f;
/** We skip computing heuristics with absolute weight value lower than this */
public static final float ABS_HEURISTIC_WEIGHT_THRESHOLD = 0.01f;
/** Denominator of heuristic threshold fraction, i.e. 1/2, 1/4, 1/8, etc. */
private int fraction = 8;
/** Whether to apply same-turn continuation. */
private boolean continuation = true;
/** Our heuristic value function estimator */
private Heuristics heuristicValueFunction = null;
/**
* Default constructor; will have to make sure to call setHeuristics() before using this,
* and also make sure that the heuristics are initialised.
*/
public HeuristicSamplingMoveSelector()
{
}
/**
* Constructor with heuristic value function to use already passed in at construction time.
* This constructor will also ensure that the heuristic is initialised for the given game.
*
* @param heuristicValueFunction The heuristics to use.
* @param game The game.
*/
public HeuristicSamplingMoveSelector(final Heuristics heuristicValueFunction, final Game game)
{
this.heuristicValueFunction = heuristicValueFunction;
heuristicValueFunction.init(game);
}
//-------------------------------------------------------------------------
@Override
public Move selectMove
(
final Context context,
final FastArrayList<Move> maybeLegalMoves,
final int p,
final IsMoveReallyLegal isMoveReallyLegal
)
{
final MoveScore moveScore = evaluateMoves(context.game(), context);
final Move move = moveScore.move();
if (move == null)
System.out.println("** No best move.");
return move;
}
//-------------------------------------------------------------------------
/**
* @param player The player.
* @param context The context.
*
* @return Opponents of given player
*/
@SuppressWarnings("static-method")
public int[] opponents(final int player, final Context context)
{
final int numPlayersInGame = context.game().players().count();
final int[] opponents = new int[numPlayersInGame - 1];
int idx = 0;
if (context.game().requiresTeams())
{
final int tid = context.state().getTeam(player);
for (int p = 1; p <= numPlayersInGame; p++)
if (context.state().getTeam(p) != tid)
opponents[idx++] = p;
}
else
{
for (int p = 1; p <= numPlayersInGame; ++p)
{
if (p != player)
opponents[idx++] = p;
}
}
return opponents;
}
//-------------------------------------------------------------------------
/**
* @param game Current game.
* @param context Current context.
* @param fraction Number of moves to select.
* @return Randomly chosen subset of moves.
*/
public static FastArrayList<Move> selectMoves(final Game game, final Context context, final int fraction)
{
FastArrayList<Move> playerMoves = game.moves(context).moves();
FastArrayList<Move> selectedMoves = new FastArrayList<Move>();
final int target = Math.max(2, (playerMoves.size() + 1) / fraction);
if (target >= playerMoves.size())
return playerMoves;
while (selectedMoves.size() < target)
{
final int r = ThreadLocalRandom.current().nextInt(playerMoves.size());
selectedMoves.add(playerMoves.get(r));
playerMoves.remove(r);
}
return selectedMoves;
}
//-------------------------------------------------------------------------
/**
* @param game The game.
* @param context The context.
* @return The score and the move.
*/
public MoveScore evaluateMoves(final Game game, final Context context)
{
FastArrayList<Move> moves = selectMoves(game, context, fraction);
float bestScore = Float.NEGATIVE_INFINITY;
Move bestMove = moves.get(0);
final int mover = context.state().mover();
//Context contextCurrent = context;
for (Move move: moves)
{
final Context contextCopy = new Context(context);
game.apply(contextCopy, move);
if (contextCopy.trial().status() != null)
{
// Check if move is a winner
final int winner = contextCopy.state().playerToAgent(contextCopy.trial().status().winner());
if (winner == mover)
return new MoveScore(move, WIN_SCORE); // return winning move immediately
if (winner != 0)
continue; // skip losing move
}
float score = 0;
if (continuation && contextCopy.state().mover() == mover)
{
//System.out.println("Recursing...");
return new MoveScore(move, evaluateMoves(game, contextCopy).score());
}
else
{
score = heuristicValueFunction.computeValue
(
contextCopy, mover, ABS_HEURISTIC_WEIGHT_THRESHOLD
);
for (final int opp : opponents(mover, context))
{
if (context.active(opp))
score -= heuristicValueFunction.computeValue(contextCopy, opp, ABS_HEURISTIC_WEIGHT_THRESHOLD);
else if (context.winners().contains(opp))
score -= PARANOID_OPP_WIN_SCORE;
}
score += (float)(ThreadLocalRandom.current().nextInt(1000) / 1000000.0);
}
if (score > bestScore)
{
bestScore = score;
bestMove = move;
}
}
return new MoveScore(bestMove, bestScore);
}
//-------------------------------------------------------------------------
/**
* @return Heuristic function to use
*/
public Heuristics heuristicValueFunction()
{
return heuristicValueFunction;
}
/**
* Set the heuristics to use
* @param heuristics
*/
public void setHeuristics(final Heuristics heuristics)
{
this.heuristicValueFunction = heuristics;
}
}
| 6,271 | 26.508772 | 113 | java |
Ludii | Ludii-master/Core/src/other/playout/Playout.java | package other.playout;
import java.util.List;
import java.util.Random;
import other.AI;
import other.context.Context;
import other.trial.Trial;
//-----------------------------------------------------------------------------
/**
* Custom playout types.
*
* @author cambolbro
*/
public interface Playout
{
//-------------------------------------------------------------------------
/**
* Play out game to conclusion from current state.
*
* @param context
* @param ais
* @param thinkingTime The maximum number of seconds that AIs are allowed
* to spend per turn
* @param playoutMoveSelector A playout move selector to select moves non-uniformly
* @param maxNumBiasedActions Maximum number of actions for which to bias
* selection using features (-1 for no limit)
* @param maxNumPlayoutActions Maximum number of actions to be applied,
* after which we will simply return a null result (-1 for no limit)
* @param random RNG for selecting actions
* @return Fully played-out Trial object.
*/
public abstract Trial playout
(
final Context context,
final List<AI> ais,
final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector,
final int maxNumBiasedActions,
final int maxNumPlayoutActions,
final Random random
);
/**
* @return Should return true if the playout implementation still calls
* game.moves() to compute the list of legal moves in every game state,
* or false otherwise.
*/
public abstract boolean callsGameMoves();
//-------------------------------------------------------------------------
}
| 1,593 | 26.482759 | 84 | java |
Ludii | Ludii-master/Core/src/other/playout/PlayoutAddToEmpty.java | package other.playout;
import java.util.List;
import java.util.Random;
import game.Game;
import game.functions.ints.IntConstant;
import game.rules.phase.Phase;
import game.rules.play.moves.Moves;
import game.rules.play.moves.decision.MoveSwapType;
import game.rules.play.moves.nonDecision.effect.state.swap.SwapPlayersType;
import game.types.board.SiteType;
import main.Constants;
import main.collections.FastArrayList;
import other.AI;
import other.Sites;
import other.action.Action;
import other.action.move.ActionAdd;
import other.context.Context;
import other.move.Move;
import other.trial.Trial;
//-----------------------------------------------------------------------------
/**
* @author cambolbro
*/
public class PlayoutAddToEmpty implements Playout
{
//-------------------------------------------------------------------------
/** Move cache (indexed by component first, site second) */
private Move[][] moveCache = null;
/** The Site Type we want to add to */
private final SiteType type;
//-------------------------------------------------------------------------
/**
* Constructor
* @param type
*/
public PlayoutAddToEmpty(final SiteType type)
{
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public Trial playout
(
final Context context,
final List<AI> ais,
final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector,
final int maxNumBiasedActions,
final int maxNumPlayoutActions,
final Random random
)
{
final Game currentGame = context.game();
// make sure we have an action cache
if (moveCache == null)
{
moveCache = new Move[currentGame.players().count() + 1][currentGame.board().topology().numSites(type)];
}
// Get empty board region
// convert to Sites representation because we can more efficiently
// fetch random entries from that representation
final Sites sites = new Sites(context.state().containerStates()[0].emptyRegion(type).sites());
final Phase startPhase = currentGame.rules().phases()[context.state().currentPhase(context.state().mover())];
int numActionsApplied = 0;
double probSwap = 0.0;
final Trial trial = context.trial();
while (!trial.over() && (maxNumPlayoutActions < 0 || maxNumPlayoutActions > numActionsApplied))
{
final int remaining = sites.count();
final int mover = context.state().mover();
final Phase currPhase = currentGame.rules().phases()[context.state().currentPhase(mover)];
if (currPhase != startPhase)
{
// May have to switch over to new playout implementation
return trial;
}
if (remaining < 1)
{
// No more moves: automatic pass
if (context.active())
context.state().setStalemated(mover, true);
// System.out.println("Game.playout(): No legal moves for player " +
// context.trial().state().mover() + ".");
currentGame.apply(context, Game.createPassMove(context,true));
++numActionsApplied;
continue;
}
else
{
if (context.active())
context.state().setStalemated(mover, false);
}
final boolean canSwap = (context.game().metaRules().usesSwapRule()
&& trial.moveNumber() == currentGame.players().count() - 1);
if (canSwap)
{
probSwap = 1.0 / (remaining + 1);
}
AI ai = null;
if (ais != null)
{
ai = ais.get(context.state().playerToAgent(mover));
}
final Move move;
if (ai != null)
{
// make AI move
move = ai.selectAction(context.game(), ai.copyContext(context), thinkingTime, -1, -1);
if (!move.isSwap())
sites.remove(move.from());
}
else
{
final Move[] playerMoveCache = moveCache[mover];
if
(
playoutMoveSelector == null
||
(maxNumBiasedActions >= 0 && maxNumBiasedActions < numActionsApplied)
||
playoutMoveSelector.wantsPlayUniformRandomMove()
)
{
// Select move uniformly at random
final int n = random.nextInt(remaining);
final int site = sites.nthValue(n);
if (playerMoveCache[site] == null)
{
final Action actionAdd = new ActionAdd(type, site, mover, 1, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, null);
actionAdd.setDecision(true);
move = new Move(actionAdd);
move.setFromNonDecision(site);
move.setToNonDecision(site);
move.setMover(mover);
if (type == SiteType.Edge)
{
move.setOrientedMove(false);
move.setEdgeMove(site);
}
assert (currPhase.play().moves().then() == null);
playerMoveCache[site] = move;
}
else
{
move = playerMoveCache[site];
}
sites.removeNth(n);
}
else
{
// Let our playout move selector pick a move
final FastArrayList<Move> legalMoves = new FastArrayList<Move>(remaining + 1);
for (int i = 0; i < remaining; ++i)
{
final int site = sites.nthValue(i);
if (playerMoveCache[site] == null)
{
final Action actionAdd = new ActionAdd(type, site, mover, 1, Constants.UNDEFINED,
Constants.UNDEFINED, Constants.UNDEFINED, null);
actionAdd.setDecision(true);
final Move m = new Move(actionAdd);
m.setFromNonDecision(site);
m.setToNonDecision(site);
m.setMover(mover);
assert (currPhase.play().moves().then() == null);
playerMoveCache[site] = m;
legalMoves.add(m);
}
else
{
legalMoves.add(playerMoveCache[site]);
}
}
if (canSwap)
{
// Add a swap move
final int moverLastTurn = context.trial().lastTurnMover(mover);
if(mover != moverLastTurn && moverLastTurn != Constants.UNDEFINED)
{
final Moves swapMove = game.rules.play.moves.decision.Move.construct(
MoveSwapType.Swap,
SwapPlayersType.Players,
new IntConstant(mover),
null,
new IntConstant(moverLastTurn),
null,
null // new Then(replay, null)
);
legalMoves.addAll(swapMove.eval(context).moves());
}
}
move = playoutMoveSelector.selectMove(context, legalMoves, mover, (final Move m) -> {return true;});
if (move.isSwap())
{
// Since we're already executing the swap move here,
// set prob of swapping at end of playout to 0
assert (canSwap);
probSwap = 0.0;
}
else
{
sites.remove(move.to());
}
}
}
currentGame.apply(context, move);
++numActionsApplied;
}
if (random.nextDouble() < probSwap)
{
// we actually should have swapped players in turn 2, do so now
assert (currentGame.players().count() == 2);
context.state().swapPlayerOrder(1, 2);
}
return trial;
}
@Override
public boolean callsGameMoves()
{
return false;
}
}
| 6,915 | 25.098113 | 111 | java |
Ludii | Ludii-master/Core/src/other/playout/PlayoutFilter.java | package other.playout;
import java.util.List;
import java.util.Random;
import game.Game;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntConstant;
import game.rules.phase.Phase;
import game.rules.play.Play;
import game.rules.play.moves.Moves;
import game.rules.play.moves.decision.MoveSwapType;
import game.rules.play.moves.nonDecision.effect.requirement.Do;
import game.rules.play.moves.nonDecision.effect.state.swap.SwapPlayersType;
import main.Constants;
import main.collections.FastArrayList;
import other.AI;
import other.context.Context;
import other.move.Move;
import other.playout.PlayoutMoveSelector.IsMoveReallyLegal;
import other.trial.Trial;
/**
* Optimised playout strategy for alternating-move games with a Filter rule.
* Also support for Filter as "else" component of an outer If, because
* we often have this in many chess-like games (for promotion).
*
* @author Dennis Soemers
*/
public class PlayoutFilter implements Playout
{
@Override
public Trial playout
(
final Context context,
final List<AI> ais,
final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector,
final int maxNumBiasedActions,
final int maxNumPlayoutActions,
final Random random
)
{
final Game currentGame = context.game();
final Phase startPhase = currentGame.rules().phases()[context.state().currentPhase(context.state().mover())];
final Play playRules = startPhase.play();
final Do doRule;
final game.rules.play.moves.nonDecision.operators.logical.If ifRule;
final game.rules.play.moves.nonDecision.effect.Pass passRule;
final game.rules.play.moves.nonDecision.operators.logical.Or orRule;
if (playRules.moves() instanceof Do)
{
doRule = (Do) playRules.moves();
ifRule = null;
passRule = null;
orRule = null;
}
else if (playRules.moves() instanceof game.rules.play.moves.nonDecision.operators.logical.If)
{
ifRule = (game.rules.play.moves.nonDecision.operators.logical.If) playRules.moves();
passRule = null;
orRule = null;
if (ifRule.elseList() instanceof Do)
{
doRule = (Do) ifRule.elseList();
}
else
{
throw new UnsupportedOperationException
(
"Cannot use FilterPlayout for phase with else-rules of type: "
+
ifRule.elseList().getClass()
);
}
}
else if (playRules.moves() instanceof game.rules.play.moves.nonDecision.operators.logical.Or)
{
orRule = (game.rules.play.moves.nonDecision.operators.logical.Or) playRules.moves();
ifRule = null;
if
(
orRule.list().length == 2 &&
orRule.list()[0] instanceof Do &&
orRule.list()[1] instanceof game.rules.play.moves.nonDecision.effect.Pass
)
{
doRule = (Do) orRule.list()[0];
passRule = (game.rules.play.moves.nonDecision.effect.Pass) orRule.list()[1];
}
else
{
throw new UnsupportedOperationException("Invalid Or-rules for FilterPlayout!");
}
}
else
{
throw new UnsupportedOperationException(
"Cannot use FilterPlayout for phase with play rules of type: " + playRules.moves().getClass());
}
final Moves priorMoves;
final Moves mainMovesGenerator;
if (doRule.after() == null)
{
priorMoves = null;
mainMovesGenerator = doRule.prior();
}
else
{
priorMoves = doRule.prior();
mainMovesGenerator = doRule.after();
}
final BooleanFunction condition = doRule.ifAfter();
int numActionsApplied = 0;
final Trial trial = context.trial();
while
(
!trial.over()
&&
(maxNumPlayoutActions < 0 || maxNumPlayoutActions > numActionsApplied)
)
{
Move move = null;
AI ai = null;
final int mover = context.state().mover();
final Phase currPhase = currentGame.rules().phases()[context.state().currentPhase(mover)];
if (currPhase != startPhase)
{
// May have to switch over to new playout implementation
return trial;
}
if (ais != null)
{
ai = ais.get(context.state().playerToAgent(mover));
}
if (ai != null)
{
// Make AI move
move = ai.selectAction(currentGame, ai.copyContext(context), thinkingTime, -1, -1);
}
else
{
// Compute list of maybe-legal-moves and functor to filter out illegal ones
final boolean mustCheckCondition;
final boolean ifConditionIsTrue;
final boolean usedDoRule;
final Moves legalMoves;
final Context movesGenContext;
if (ifRule != null && ifRule.cond().eval(context))
{
// We should play according to if-rules (non-checkmove)
legalMoves = ifRule.list().eval(context);
mustCheckCondition = false;
ifConditionIsTrue = true;
usedDoRule = false;
movesGenContext = context;
if (ifRule.then() != null)
for (int j = 0; j < legalMoves.moves().size(); j++)
legalMoves.moves().get(j).then().add(ifRule.then().moves());
}
else
{
// We should play according to checkmove rules
final Moves priorMovesGenerated;
if (priorMoves != null)
{
movesGenContext = new Context(context);
priorMovesGenerated = doRule.generateAndApplyPreMoves(context, movesGenContext);
}
else
{
movesGenContext = context;
priorMovesGenerated = null;
}
legalMoves = mainMovesGenerator.eval(movesGenContext);
mustCheckCondition = !(condition.autoSucceeds());
ifConditionIsTrue = false;
usedDoRule = true;
if (priorMovesGenerated != null)
Do.prependPreMoves(priorMovesGenerated, legalMoves, movesGenContext);
}
if (passRule != null)
{
// Add pass move
legalMoves.moves().addAll(passRule.eval(movesGenContext).moves());
}
if (orRule != null)
{
// Add Or rule consequents
if (orRule.then() != null)
for (int j = 0; j < legalMoves.moves().size(); j++)
legalMoves.moves().get(j).then().add(orRule.then().moves());
}
if (context.game().metaRules().usesSwapRule()
&& trial.moveNumber() == movesGenContext.game().players().count() - 1)
{
final int moverLastTurn = context.trial().lastTurnMover(mover);
if (mover != moverLastTurn && moverLastTurn != Constants.UNDEFINED)
{
final Moves swapMove = game.rules.play.moves.decision.Move.construct(
MoveSwapType.Swap,
SwapPlayersType.Players,
new IntConstant(mover),
null,
new IntConstant(moverLastTurn),
null,
null
);
legalMoves.moves().addAll(swapMove.eval(movesGenContext).moves());
}
}
final FastArrayList<Move> moves = legalMoves.moves();
// Functor to filter out illegal moves
final IsMoveReallyLegal isMoveReallyLegal = (final Move m) -> {
if (!mustCheckCondition)
return true;
if (passRule != null && m.isPass())
return true;
if (m.isSwap())
return true;
return doRule.movePassesCond(m, movesGenContext, true);
};
if
(
playoutMoveSelector == null
||
(maxNumBiasedActions >= 0 && maxNumBiasedActions < numActionsApplied)
||
playoutMoveSelector.wantsPlayUniformRandomMove()
)
{
// Select move uniformly at random
move = PlayoutMoveSelector.selectUniformlyRandomMove(context, moves, isMoveReallyLegal, random);
}
else
{
// Let our playout move selector pick a move
move = playoutMoveSelector.selectMove(context, moves, mover, isMoveReallyLegal);
}
if (move == null)
{
// couldn't find a legal move, so will have to pass
move = Game.createPassMove(context,true);
if (context.active())
context.state().setStalemated(mover, true);
}
else
{
// Add consequents (which shouldn't have been included yet in condition check)
if (usedDoRule && doRule.then() != null)
move.then().add(doRule.then().moves());
if (ifRule != null && ifRule.then() != null && !ifConditionIsTrue)
move.then().add(ifRule.then().moves());
if (context.active())
context.state().setStalemated(mover, false);
}
}
if (move == null)
{
System.err.println("FilterPlayout.playout(): No move found.");
break;
}
// final FastArrayList<Move> legalMoves = applyGame.moves(context).moves();
// boolean foundLegal = false;
// for (final Move legal : legalMoves)
// {
// if (legal.getAllActions(context).equals(move.getAllActions(context)))
// {
// foundLegal = true;
// break;
// }
// }
//
// if (!foundLegal)
// {
// System.out.println("tried applying illegal move: " + move);
// return trial;
// }
currentGame.apply(context, move);
++numActionsApplied;
}
return trial;
}
@Override
public boolean callsGameMoves()
{
return false;
}
}
| 8,762 | 25.716463 | 111 | java |
Ludii | Ludii-master/Core/src/other/playout/PlayoutMoveSelector.java | package other.playout;
import java.util.Random;
import main.collections.FastArrayList;
import other.context.Context;
import other.move.Move;
/**
* Abstract class for an object that can efficiently select moves in playouts
* (including custom, optimised playout strategies)
*
* @author Dennis Soemers
*/
public abstract class PlayoutMoveSelector
{
//-------------------------------------------------------------------------
/**
* Method which should be overridden to return a move to play.
*
* NOTE: this method is allowed to modify the maybeLegalMoves list
*
* @param context
* @param maybeLegalMoves
* @param p Player for which to make a move
* @param isMoveReallyLegal If not null, a functor that tells us if a move is REALLY legal
* @return Move to play. Should return null if no legal move is found
*/
public abstract Move selectMove
(
final Context context,
final FastArrayList<Move> maybeLegalMoves,
final int p,
final IsMoveReallyLegal isMoveReallyLegal
);
//-------------------------------------------------------------------------
/**
* Can be implemented to return true if a MoveSelector wants to play a move
* selected uniformly at random. When this happens, a playout implementation
* may be able to implement this more efficiently that the MoveSelector itself
* would.
*
* @return True if the MoveSelector wants to select a move uniformly at random.
*/
@SuppressWarnings("static-method")
public boolean wantsPlayUniformRandomMove()
{
return false;
}
//-------------------------------------------------------------------------
/**
* Selects a move uniformly at random. NOTE: this method may modify the
* given list of maybe-legal-moves.
*
* @param context
* @param maybeLegalMoves
* @param isMoveReallyLegal If not null, a functor that tells us if a move is REALLY legal
* @param random Random number generator to use for selecting moves
* @return Move selected uniformly at random, or null if no legal move found.
*/
public static Move selectUniformlyRandomMove
(
final Context context,
final FastArrayList<Move> maybeLegalMoves,
final IsMoveReallyLegal isMoveReallyLegal,
final Random random
)
{
while (!maybeLegalMoves.isEmpty())
{
final int moveIdx = random.nextInt(maybeLegalMoves.size());
final Move move = maybeLegalMoves.removeSwap(moveIdx);
if (isMoveReallyLegal.checkMove(move))
return move;
}
return null;
}
//-------------------------------------------------------------------------
/**
* Interface for a functor that can be used to check if a move is really legal
* Normally used for moves that are already likely to be legal, but may turn out
* to be illegal due to some expensive-to-evaluate test (like IsThreatened stuff)
*
* @author Dennis Soemers
*/
public interface IsMoveReallyLegal
{
/**
* The function
*
* @param move
* @return True if the move is really legal
*/
boolean checkMove(final Move move);
}
//-------------------------------------------------------------------------
}
| 3,101 | 27.2 | 91 | java |
Ludii | Ludii-master/Core/src/other/playout/PlayoutNoRepetition.java | package other.playout;
import java.util.List;
import java.util.Random;
import game.Game;
import game.functions.ints.IntConstant;
import game.rules.meta.no.repeat.NoRepeat;
import game.rules.phase.Phase;
import game.rules.play.moves.Moves;
import game.rules.play.moves.decision.MoveSwapType;
import game.rules.play.moves.nonDecision.effect.state.swap.SwapPlayersType;
import main.Constants;
import main.collections.FastArrayList;
import other.AI;
import other.context.Context;
import other.move.Move;
import other.playout.PlayoutMoveSelector.IsMoveReallyLegal;
import other.trial.Trial;
/**
* Optimised playout strategy for alternating-move games with
* no-repetition rules.
*
* @author Dennis Soemers
*/
public class PlayoutNoRepetition implements Playout
{
@Override
public Trial playout
(
final Context context,
final List<AI> ais,
final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector,
final int maxNumBiasedActions,
final int maxNumPlayoutActions,
final Random random
)
{
final Game currentGame = context.game();
final Phase startPhase = currentGame.rules().phases()[context.state().currentPhase(context.state().mover())];
final Moves movesRule = startPhase.play().moves();
int numActionsApplied = 0;
final Trial trial = context.trial();
while (!trial.over() && (maxNumPlayoutActions < 0 || maxNumPlayoutActions > numActionsApplied))
{
Move move = null;
AI ai = null;
final int mover = context.state().mover();
final Phase currPhase = currentGame.rules().phases()[context.state().currentPhase(mover)];
if (currPhase != startPhase)
{
// May have to switch over to new playout implementation
return trial;
}
if (ais != null)
{
ai = ais.get(context.state().playerToAgent(mover));
}
if (ai != null)
{
// Make AI move
move = ai.selectAction(currentGame, ai.copyContext(context), thinkingTime, -1, -1);
}
else
{
// Compute list of maybe-legal-moves
final Moves legalMoves = movesRule.eval(context);
if
(
context.game().metaRules().usesSwapRule()
&&
trial.moveNumber() == context.game().players().count() - 1
)
{
final int moverLastTurn = context.trial().lastTurnMover(mover);
if (mover != moverLastTurn && moverLastTurn != Constants.UNDEFINED)
{
final Moves swapMove =
game.rules.play.moves.decision.Move.construct
(
MoveSwapType.Swap,
SwapPlayersType.Players,
new IntConstant(mover),
null,
new IntConstant(moverLastTurn),
null,
null
);
legalMoves.moves().addAll(swapMove.eval(context).moves());
}
}
final FastArrayList<Move> moves = legalMoves.moves();
// Functor to filter out illegal moves
final IsMoveReallyLegal isMoveReallyLegal =
(final Move m) ->
{
return NoRepeat.apply(context, m);
};
if
(
playoutMoveSelector == null
||
(maxNumBiasedActions >= 0 && maxNumBiasedActions < numActionsApplied)
||
playoutMoveSelector.wantsPlayUniformRandomMove()
)
{
// Select move uniformly at random
move = PlayoutMoveSelector.selectUniformlyRandomMove(context, moves, isMoveReallyLegal, random);
}
else
{
// Let our playout move selector pick a move
move = playoutMoveSelector.selectMove(context, moves, mover, isMoveReallyLegal);
}
if (move == null)
{
// Couldn't find a legal move, so will have to pass
move = Game.createPassMove(context,true);
if (context.active())
context.state().setStalemated(mover, true);
}
else
{
if (context.active())
context.state().setStalemated(mover, false);
}
}
if (move == null)
{
System.err.println("NoRepetitionPlayout.playout(): No move found.");
break;
}
currentGame.apply(context, move);
++numActionsApplied;
}
return trial;
}
@Override
public boolean callsGameMoves()
{
return false;
}
}
| 4,082 | 23.896341 | 111 | java |
Ludii | Ludii-master/Core/src/other/state/CopyOnWriteState.java | package other.state;
import other.state.track.OnTrackIndices;
import other.state.track.OnTrackIndicesCOW;
/**
* A subclass of State, with copy-on-write optimisations. Note
* that changes to the state that we copy from may seep through
* into this copy.
*
* @author Dennis Soemers
*/
public final class CopyOnWriteState extends State
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Copy constructor (with some copy-on-write behaviour)
* @param other
*/
public CopyOnWriteState(final State other)
{
super(other);
}
//-------------------------------------------------------------------------
@Override
protected OnTrackIndices copyOnTrackIndices(final OnTrackIndices otherOnTrackIndices)
{
return otherOnTrackIndices == null ? null : new OnTrackIndicesCOW(otherOnTrackIndices);
}
//-------------------------------------------------------------------------
}
| 1,069 | 23.883721 | 89 | java |
Ludii | Ludii-master/Core/src/other/state/OwnedIndexMapper.java | package other.state;
import java.io.Serializable;
import java.util.Arrays;
import game.Game;
import game.equipment.component.Component;
import main.Constants;
/**
* A helper object for Owned structures, which allows us to map from
* player + component indices into player + array indices, where the
* array indices are in a smaller range than the component indices
* (always starting from 0, always contiguous, only have legal mappings
* for components that are actually owned by the corresponding player index).
*
* @author Dennis Soemers
*/
public final class OwnedIndexMapper implements Serializable
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* For (playerIdx, componentIdx), gives us the index that Owned should
* use as a replacement for componentIdx
*/
private final int[][] mappedIndices;
/**
* A reverse map (giving us original component index back)
*/
private final int[][] reverseMap;
//-------------------------------------------------------------------------
/**
* Constructor
* @param game
*/
public OwnedIndexMapper(final Game game)
{
final Component[] components = game.equipment().components();
final int fullPlayersDim = game.players().count() + 2;
final int fullCompsDim = components.length;
mappedIndices = new int[fullPlayersDim][fullCompsDim];
reverseMap = new int[fullPlayersDim][];
for (int p = 0; p < fullPlayersDim; ++p)
{
int nextIndex = 0;
Arrays.fill(mappedIndices[p], Constants.UNDEFINED);
for (int e = 0; e < fullCompsDim; ++e)
{
final Component comp = components[e];
if (comp != null && comp.owner() == p)
mappedIndices[p][e] = nextIndex++;
}
reverseMap[p] = new int[nextIndex];
for (int i = 0; i < mappedIndices[p].length; ++i)
{
if (mappedIndices[p][i] >= 0)
reverseMap[p][mappedIndices[p][i]] = i;
}
}
}
//-------------------------------------------------------------------------
/**
* @param playerIdx
* @param origCompIdx
* @return Index that we should use for given original comp index, for given player index.
*/
public final int compIndex(final int playerIdx, final int origCompIdx)
{
return mappedIndices[playerIdx][origCompIdx];
}
/**
* @param playerIdx
* @return Array of indices we should use for all possible components for given player index.
*/
public final int[] playerCompIndices(final int playerIdx)
{
return mappedIndices[playerIdx];
}
/**
* @param playerIdx
* @return Number of valid component indices for given player index.
*/
public final int numValidIndices(final int playerIdx)
{
return reverseMap[playerIdx].length;
}
/**
* @param playerIdx
* @param mappedIndex
* @return Reverses a mapped index back into a component index.
*/
public final int reverseMap(final int playerIdx, final int mappedIndex)
{
return reverseMap[playerIdx][mappedIndex];
}
//-------------------------------------------------------------------------
}
| 3,155 | 25.521008 | 94 | java |
Ludii | Ludii-master/Core/src/other/state/State.java | package other.state;
import java.io.Serializable;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import annotations.Hide;
import game.Game;
import game.Game.StateConstructorLock;
import game.equipment.container.Container;
import game.equipment.container.other.Dice;
import game.functions.ints.last.LastFrom;
import game.functions.ints.last.LastTo;
import game.rules.phase.Phase;
import game.types.board.SiteType;
import game.types.play.ModeType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.equipment.Region;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.set.hash.TIntHashSet;
import main.Constants;
import main.collections.FastTIntArrayList;
import other.context.Context;
import other.state.container.ContainerState;
import other.state.container.ContainerStateFactory;
import other.state.owned.Owned;
import other.state.owned.OwnedFactory;
import other.state.symmetry.SymmetryValidator;
import other.state.track.OnTrackIndices;
import other.state.zhash.ZobristHashGenerator;
import other.state.zhash.ZobristHashUtilities;
/**
* Game state.
*
* @author Eric.Piette and cambolbro
*/
@Hide
public class State implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private static final int TURN_MAX_HASH = 1024;
private static final int SCORE_MAX_HASH = 1024;
private static final int AMOUNT_MAX_HASH = 1024;
//-------------------------------------------------------------------------
/** Current player to move. */
private int mover = 0;
/** Next player to move (if no special rules override this). */
private int next = 0;
/** Previous player to move. */
private int prev = 0;
/** For every player, a bit indicating whether some condition is triggered (e.g. checkmate). */
private int triggered = 0;
/** For every player, a bit indicating whether they are stalemated. */
private int stalemated = 0;
/** Individual container states. */
private ContainerState[] containerStates;
/** Variable for using a counter associated to the state (possibly reSet at 0 by a consequence of an action) */
private int counter = Constants.UNDEFINED;
/** Variable to store a value between two states. */
private int tempValue = Constants.UNDEFINED;
/**
* The pending values of a state. These values are cleared when another state is
* reached.
*/
private TIntHashSet pendingValues = null;
/** Amount belonging to each player, e.g. money. */
private int[] amount = null;
/** The money pot. */
private int moneyPot = 0;
/** Current Phase for each player. */
private int[] currentPhase;
/** The sum of each Dice container */
private int[] sumDice;
/** The current dice values of each set of dice. */
private int[][] currentDice;
// The variable stored between different state.
private TObjectIntMap<String> valueMap = null;
/**
* To know when the dice are rolled if they are all equals. Note: Even if one
* die is used we know when the dice were rolled they were equal.
*/
private boolean diceAllEqual = false;
/** The number of turns played successively by the same player. */
private int numTurnSamePlayer = 0;
/** The number of times the mover has been switched to a different player. */
private int numTurn = 1;
/** The trump suit of the game (for cards games). */
private int trumpSuit = Constants.OFF;
/** The propositions (represented as ints). */
private TIntArrayList propositions;
/** The votes (represented as ints). */
private TIntArrayList votes;
/** The values for each player. */
private int[] valuesPlayer;
/** The decision after voting. */
private int isDecided = Constants.UNDEFINED;
/** The values stored in some states to use them in future states. */
private FastTIntArrayList rememberingValues;
/** The values stored in some states to use them in future states and associated to a name. */
private Map<String, FastTIntArrayList> mapRememberingValues = null;
/** The notes sent to each player during the game. */
private TIntObjectMap<TIntObjectMap<String>> notes = null;
/**
* Access to list of sites for each kind of component owned per player. First
* indexed by player index, then by component index.
*
* Will contain null entries for cases where a component cannot be owned by a
* certain player.
*/
protected transient Owned owned;
/** To access where are each type of piece on each track. */
private transient OnTrackIndices onTrackIndices;
/**
* BitSet used to store all the site already visited (from & to) by each move
* done by the player in a sequence of turns played by the same player.
*/
private BitSet visited = null;
/** In case of a sequence of capture to remove (e.g. some draughts games). */
private TIntArrayList sitesToRemove = null;
/** Team that each player belongs to, if any. */
private int[] teams = null;
/**
* Indexed by original player/agent index at game start.
* Gives us the matching player index at current game state (may be different after swaps)
*/
private int[] playerOrder;
/** All the remaining dominoes. */
private FastTIntArrayList remainingDominoes;
/** The state stored temporary by the game. */
private long storedState = 0L;
/** Number of consecutive pass moves */
private int numConsecutivePasses = 0;
/** Assumed cap on number of consecutive pass moves (for hash code purposes) */
private int numConsecutivePassesHashCap;
/*
* -------------------------------------------------------------------------
* Zobrist hashing - attempts to reduce the board state to a 64 bit number
*
* These values are incrementally updated every time the state changes
* For repetition and ko, you'll want the current board state, but this is not the whole story
* The generated move tree from a given node is affected by other factors; player to move,
* your countdown variables, etc. These should be included when searching with transposition
* tables if you want an accurate description of the node score
* -------------------------------------------------------------------------
*/
private long stateHash; // Includes container states and scores
private long moverHash;
private long nextHash;
private long prevHash;
private long activeHash;
private long checkmatedHash;
private long stalematedHash;
private long pendingHash;
private long scoreHash; // Hash value for scores
private long amountHash; // Hash value for amounts
private long[] moverHashes;
private long[] nextHashes;
private long[] prevHashes;
private long[] activeHashes;
private long[] checkmatedHashes;
private long[] stalematedHashes;
private long[][] lowScoreHashes;
private long[][] highScoreHashes;
private long[][] lowAmountHashes;
private long[][] highAmountHashes;
private long[][] phaseHashes;
private long[] isPendingHashes;
private long[] tempHashes;
private long[][] playerOrderHashes;
private long[][] consecutiveTurnHashes;
private long[][] playerSwitchHashes;
private long[][] teamHashes;
private long[][] numConsecutivePassesHashes;
private long[] lastFromHashes;
private long[] lastToHashes;
/** @param delta incremental hash to be xored with value */
public void updateStateHash(final long delta)
{
// final long old = stateHash;
stateHash ^= delta;
// if (old != stateHash)
// {
// final String stacktraceString = Utilities.stackTraceString();
// if
// (
// !stacktraceString.contains("getMoveStringToDisplay")
// &&
// !stacktraceString.contains("other.context.InformationContext.moves")
// &&
// !stacktraceString.contains("game.rules.play.moves.Moves$1.canMoveConditionally(Moves.java:305)")
// )
// {
// System.out.println("Updated stateHash from " + old + " to " + stateHash);
// Utilities.stackTrace();
// }
// }
}
/**
* Performance warning: this is slow, do not use during search!
* Returns the lowest hash from the containers after all symmetries have been applied
* @param validator allows selection of a subset of available symmetries
* @param whoOnly only hash the 'who' values - this is required for games with undifferentiated pieces
* @return state hash value
*/
public long canonicalHash(final SymmetryValidator validator, final boolean whoOnly)
{
final ContainerState boardState = containerStates[0];
final long canonicalBoardHash = boardState.canonicalHash(validator, this, whoOnly);
return canonicalBoardHash == 0 ? stateHash : canonicalBoardHash;
}
// /**
// * @deprecated use canonicalhash(validator,whoOnly) instead
// * @param validator
// * @return state hash value for the whole state
// */
// @Deprecated
// public long canonicalHash(final SymmetryValidator validator)
// {
// return canonicalHash(validator, false);
// }
/** @return state hash value */
public long stateHash() { return stateHash; }
/** @return pending hash value */
protected long pendingHash() { return pendingHash; }
/** @return hash value for number of times turn has remained the same */
protected long consecutiveTurnHash()
{
return numTurnSamePlayer < Constants.MAX_CONSECUTIVES_TURNS ?
consecutiveTurnHashes[0][numTurnSamePlayer] :
consecutiveTurnHashes[1][numTurnSamePlayer % Constants.MAX_CONSECUTIVES_TURNS];
}
/** @return hash value for number of times turn has changed */ // TODO why is this not in full hash?
protected long playerNumSwitchesHash()
{
return numTurn < TURN_MAX_HASH ? playerSwitchHashes[0][numTurn] : playerSwitchHashes[1][numTurn % TURN_MAX_HASH];
}
/**
* @return Hash value for number of consecutive passes
*/
protected long numConsecutivePassesHash()
{
return numConsecutivePasses < numConsecutivePassesHashCap ?
numConsecutivePassesHashes[0][numConsecutivePasses] :
numConsecutivePassesHashes[1][numConsecutivePasses % numConsecutivePassesHashCap];
}
/** @return full hash value containing all fields */
public long fullHash()
{
return moverHash ^
nextHash ^
prevHash ^
activeHash ^
checkmatedHash ^
stalematedHash ^
pendingHash() ^
stateHash() ^
consecutiveTurnHash() ^
scoreHash ^
amountHash ^
numConsecutivePassesHash()
;
}
private static final LastFrom LAST_FROM_LUDEME = new LastFrom(null);
private static final LastTo LAST_TO_LUDEME = new LastTo(null);
/**
* @param context
* @return Full hash value
*/
public long fullHash(final Context context)
{
final int lastFrom = LAST_FROM_LUDEME.eval(context) + 1;
final int lastTo = LAST_TO_LUDEME.eval(context) + 1;
long hash = fullHash();
if (lastFrom < lastFromHashes.length)
hash ^= lastFromHashes[lastFrom];
else
hash ^= lastFromHashes[lastFrom % lastFromHashes.length];
if (lastTo < lastToHashes.length)
hash ^= lastToHashes[lastTo];
else
hash ^= lastToHashes[lastTo % lastToHashes.length];
return hash;
}
//-------------------------------------------------------------------------
/**
* Default constructor.
*
* This constructor is really expensive and should only ever be called
* (ideally once) by the Game. Any other callers should instead copy
* the Game's reference state!
*
* @param game
* @param stateConstructorLock Dummy object
*/
public State(final Game game, final StateConstructorLock stateConstructorLock)
{
Objects.requireNonNull
(
stateConstructorLock,
"Only Game.java should call this constructor! Other callers can copy the game's stateReference instead using the copy constructor."
);
final int numPlayers = game.players().count();
//-------------- Hash initialisation ----------------
final ZobristHashGenerator generator = ZobristHashUtilities.getHashGenerator();
lowScoreHashes = ((game.gameFlags() & GameType.HashScores) != 0L)
? ZobristHashUtilities.getSequence(generator, numPlayers + 1, SCORE_MAX_HASH + 1)
: null;
highScoreHashes = ((game.gameFlags() & GameType.HashScores) != 0L)
? ZobristHashUtilities.getSequence(generator, numPlayers + 1, SCORE_MAX_HASH + 1)
: null;
lowAmountHashes = ((game.gameFlags() & GameType.HashAmounts) != 0L)
? ZobristHashUtilities.getSequence(generator, numPlayers + 1, SCORE_MAX_HASH + 1)
: null;
highAmountHashes = ((game.gameFlags() & GameType.HashAmounts) != 0L)
? ZobristHashUtilities.getSequence(generator, numPlayers + 1, SCORE_MAX_HASH + 1)
: null;
phaseHashes = ((game.gameFlags() & GameType.HashPhases) != 0L)
? ZobristHashUtilities.getSequence(generator, numPlayers + 1, Constants.MAX_PHASES + 1)
: null;
moverHashes = ZobristHashUtilities.getSequence(generator, numPlayers + 1);
nextHashes = ZobristHashUtilities.getSequence(generator, numPlayers + 1);
prevHashes = ZobristHashUtilities.getSequence(generator, numPlayers + 1);
activeHashes = ZobristHashUtilities.getSequence(generator, numPlayers + 1);
checkmatedHashes = ZobristHashUtilities.getSequence(generator, numPlayers + 1);
stalematedHashes = ZobristHashUtilities.getSequence(generator, numPlayers + 1);
tempHashes = ZobristHashUtilities.getSequence(generator, game.equipment().totalDefaultSites() * Math.max(1, game.maxCount()) + Constants.CONSTANT_RANGE + 1); // could be negative
playerOrderHashes = ZobristHashUtilities.getSequence(generator, numPlayers + 1, numPlayers + 1);
consecutiveTurnHashes = ZobristHashUtilities.getSequence(generator, 2, Constants.MAX_CONSECUTIVES_TURNS);
playerSwitchHashes = ZobristHashUtilities.getSequence(generator, 2, TURN_MAX_HASH);
teamHashes = (game.requiresTeams())
? ZobristHashUtilities.getSequence(generator, numPlayers + 1, Constants.MAX_PLAYER_TEAM + 1)
: null;
numConsecutivePassesHashCap = 2 * numPlayers + 1;
numConsecutivePassesHashes = ZobristHashUtilities.getSequence(generator, 2, numConsecutivePassesHashCap);
isPendingHashes = ZobristHashUtilities.getSequence(generator, game.equipment().totalDefaultSites() + 2);
lastFromHashes = ZobristHashUtilities.getSequence(generator, game.equipment().totalDefaultSites() + 2);
lastToHashes = ZobristHashUtilities.getSequence(generator, game.equipment().totalDefaultSites() + 2);
stateHash = ZobristHashUtilities.INITIAL_VALUE;
scoreHash = ZobristHashUtilities.INITIAL_VALUE;
amountHash = ZobristHashUtilities.INITIAL_VALUE;
//-------------- on with the plot ----------------
playerOrder = new int[numPlayers + 1];
for (int i = 1; i < playerOrder.length; i++)
{
playerOrder[i] = i;
updateStateHash(playerOrderHashes[i][playerOrder[i]]);
}
assert (!game.hasSubgames());
moneyPot = 0;
containerStates = new ContainerState[game.equipment().containers().length];
if (game.usesPendingValues())
pendingValues = new TIntHashSet();
if (game.requiresBet())
amount = new int[numPlayers + 1];
int id = 0;
for (final Container container : game.equipment().containers())
containerStates[id++] = ContainerStateFactory.createStateForContainer(generator, game, container);
initPhase(game);
if (game.hasHandDice())
{
sumDice = new int[game.handDice().size()];
currentDice = new int[game.handDice().size()][];
for (int i = 0; i < game.handDice().size(); i++)
{
final Dice d = game.handDice().get(i);
currentDice[i] = new int[d.numLocs()];
}
}
owned = OwnedFactory.createOwned(game);
if (game.requiresVisited())
visited = new BitSet(game.board().numSites());
if (game.hasSequenceCapture())
sitesToRemove = new TIntArrayList();
if (game.requiresTeams())
teams = new int[game.players().size()];
if (game.usesVote())
{
propositions = new TIntArrayList();
votes = new TIntArrayList();
}
else
{
propositions = null;
votes = null;
}
valuesPlayer = new int[game.players().size() + 1];
Arrays.fill(valuesPlayer, Constants.UNDEFINED);
if (game.usesNote())
notes = new TIntObjectHashMap<TIntObjectMap<String>>();
if (game.hasTrack() && game.hasInternalLoopInTrack())
onTrackIndices = new OnTrackIndices(game.board().tracks(), game.equipment().components().length);
if (game.hasDominoes())
remainingDominoes = new FastTIntArrayList();
rememberingValues = new FastTIntArrayList();
if (game.usesRememberingValues())
mapRememberingValues = new HashMap<String, FastTIntArrayList>();
if (game.usesValueMap())
valueMap = new TObjectIntHashMap<String>();
}
/**
* Copy constructor.
*
* @param other
*/
public State(final State other)
{
// NOTE: these can be copied by reference, because immutable once initialised
lowScoreHashes = other.lowScoreHashes;
highScoreHashes = other.highScoreHashes;
lowAmountHashes = other.lowAmountHashes;
highAmountHashes = other.highAmountHashes;
phaseHashes = other.phaseHashes;
isPendingHashes = other.isPendingHashes;
lastFromHashes = other.lastFromHashes;
lastToHashes = other.lastToHashes;
moverHashes = other.moverHashes;
nextHashes = other.nextHashes;
prevHashes = other.prevHashes;
activeHashes = other.activeHashes;
checkmatedHashes = other.checkmatedHashes;
stalematedHashes = other.stalematedHashes;
tempHashes = other.tempHashes;
playerOrderHashes = other.playerOrderHashes;
consecutiveTurnHashes = other.consecutiveTurnHashes;
playerSwitchHashes = other.playerSwitchHashes;
teamHashes = other.teamHashes;
numConsecutivePassesHashCap = other.numConsecutivePassesHashCap;
numConsecutivePassesHashes = other.numConsecutivePassesHashes;
playerOrder = Arrays.copyOf(other.playerOrder, other.playerOrder.length);
moneyPot = other.moneyPot;
// Back to the plot
trumpSuit = other.trumpSuit;
mover = other.mover;
next = other.next;
prev = other.prev;
triggered = other.triggered;
stalemated = other.stalemated;
if (other.containerStates == null)
{
containerStates = null;
}
else
{
containerStates = new ContainerState[other.containerStates.length];
for (int is = 0; is < containerStates.length; is++)
if (other.containerStates[is] == null)
containerStates[is] = null;
else
containerStates[is] = other.containerStates[is].deepClone();
}
counter = other.counter;
tempValue = other.tempValue;
if (other.pendingValues != null)
pendingValues = new TIntHashSet(other.pendingValues);
if (other.amount != null)
amount = Arrays.copyOf(other.amount, other.amount.length);
if (other.currentPhase != null)
currentPhase = Arrays.copyOf(other.currentPhase, other.currentPhase.length);
if (other.sumDice != null)
sumDice = Arrays.copyOf(other.sumDice, other.sumDice.length);
if (other.currentDice != null)
{
currentDice = new int[other.currentDice.length][];
for (int i = 0; i < currentDice.length; ++i)
{
currentDice[i] = Arrays.copyOf(other.currentDice[i], other.currentDice[i].length);
}
}
if (other.visited != null)
visited = (BitSet) other.visited.clone();
if (other.sitesToRemove != null)
sitesToRemove = new TIntArrayList(other.sitesToRemove);
if (other.teams != null)
teams = Arrays.copyOf(other.teams, other.teams.length);
if (other.votes != null)
{
votes = new TIntArrayList(other.votes);
propositions = new TIntArrayList(other.propositions);
isDecided = other.isDecided;
}
else
{
votes = null;
propositions = null;
isDecided = other.isDecided;
}
valuesPlayer = new int[other.valuesPlayer.length];
System.arraycopy(other.valuesPlayer, 0, valuesPlayer, 0, other.valuesPlayer.length);
if (other.notes != null)
notes = new TIntObjectHashMap<TIntObjectMap<String>>(other.notes);
numTurnSamePlayer = other.numTurnSamePlayer;
numTurn = other.numTurn;
if (other.owned == null)
owned = null;
else
owned = other.owned.copy();
diceAllEqual = other.diceAllEqual;
onTrackIndices = copyOnTrackIndices(other.onTrackIndices);
if (other.remainingDominoes != null)
remainingDominoes = new FastTIntArrayList(other.remainingDominoes);
if (other.rememberingValues != null)
rememberingValues = new FastTIntArrayList(other.rememberingValues);
if (other.mapRememberingValues != null)
{
mapRememberingValues = new HashMap<String, FastTIntArrayList>();
for (final Entry<String, FastTIntArrayList> entry : other.mapRememberingValues.entrySet())
{
final String key = entry.getKey();
final FastTIntArrayList rememberingList = entry.getValue();
final FastTIntArrayList copyRememberingList = new FastTIntArrayList(rememberingList);
mapRememberingValues.put(key, copyRememberingList);
}
}
storedState = other.storedState;
numConsecutivePasses = other.numConsecutivePasses;
if (other.valueMap != null)
valueMap = new TObjectIntHashMap<String>(other.valueMap);
stateHash = other.stateHash;
moverHash = other.moverHash;
nextHash = other.nextHash;
prevHash = other.prevHash;
activeHash = other.activeHash;
checkmatedHash = other.checkmatedHash;
stalematedHash = other.stalematedHash;
pendingHash = other.pendingHash;
scoreHash = other.scoreHash;
amountHash = other.amountHash;
}
//-------------------------------------------------------------------------
/**
* @return List of container states
*/
public ContainerState[] containerStates()
{
return containerStates;
}
//-------------------------------------------------------------------------
/**
* @return Number of players in the game of which this is a state.
*/
public int numPlayers()
{
return playerOrder.length - 1;
}
/**
* @return Current mover.
*/
public int mover()
{
return mover;
}
/**
* @param who
*/
public void setMover(final int who)
{
moverHash ^= moverHashes[mover];
mover = who;
moverHash ^= moverHashes[mover];
}
/**
* @return Next active mover.
*/
public int next()
{
return next;
}
/**
* To set the next player.
*
* @param who
*/
public void setNext(final int who)
{
nextHash ^= nextHashes[next];
next = who;
nextHash ^= nextHashes[next];
}
/**
* @return Previous mover.
*/
public int prev()
{
return prev;
}
/**
* To set the previous player.
*
* @param who
*/
public void setPrev(final int who)
{
prevHash ^= prevHashes[prev];
prev = who;
prevHash ^= prevHashes[prev];
}
/**
* Sets a player to be active or inactive.
*
* @param who Which player to set value for
* @param newActive New active value (true or false for active or inactive)
* @param active The int with bits set for currently active players
*
* @return Returns the modified int with bits set for active players
*/
public int setActive
(
final int who,
final boolean newActive,
final int active
)
{
int ret = active;
final int whoBit = (1 << (who - 1));
final boolean wasActive = (active & whoBit) != 0;
if (wasActive && !newActive)
{
activeHash ^= activeHashes[who];
ret &= ~whoBit;
}
else if (!wasActive && newActive)
{
activeHash ^= activeHashes[who];
ret |= whoBit;
}
return ret;
}
/**
* Updates the zobrist hash if all players have been set to inactive in one go.
*
* WARNING: This should only ever be called from Trial
*/
public void updateHashAllPlayersInactive()
{
activeHash = 0;
}
/**
* @param event The event triggered.
* @param who The player related to the event.
* @return Whether player is triggered.
*/
public boolean isTriggered(final String event, final int who)
{
return (triggered & (1 << (who - 1))) != 0;
}
/**
* @param who
* @param triggerValue
*/
public void triggers
(
final int who,
final boolean triggerValue
)
{
final int whoBit = (1 << (who - 1));
final boolean wasCheckmated = (triggered & whoBit) != 0;
if (wasCheckmated && !triggerValue)
{
checkmatedHash ^= checkmatedHashes[who];
triggered &= ~whoBit;
}
else if (!wasCheckmated && triggerValue)
{
checkmatedHash ^= checkmatedHashes[who];
triggered |= whoBit;
}
}
/**
* Clear all checkmates.
*/
public void clearTriggers()
{
checkmatedHash = 0;
triggered = 0;
}
/**
* @param who
* @return Whether player is in stalemate.
*/
public boolean isStalemated(final int who)
{
return (stalemated & (1 << (who - 1))) != 0;
}
/**
* TODO - branching - splitting to setStalemated(who) and clearStalemated(who) would probably be clearer and more efficient
* To set a player in stalemate (or not).
*
* @param who
* @param newStalemated
*/
public void setStalemated
(
final int who,
final boolean newStalemated
)
{
final int whoBit = (1 << (who - 1));
final boolean wasStalemated = (stalemated & whoBit) != 0;
if (wasStalemated && !newStalemated)
{
stalematedHash ^= stalematedHashes[who];
stalemated &= ~whoBit;
}
else if (!wasStalemated && newStalemated)
{
stalematedHash ^= stalematedHashes[who];
stalemated |= whoBit;
}
}
/**
* Clear all stalemates.
*/
public void clearStalemates()
{
stalematedHash = 0;
stalemated = 0;
}
/**
* Helper method to convert a given "player index" (i.e. colour) into
* an "agent index" -- index of the "agent" (might be AI or human) who
* is currently playing this colour.
*
* Normally, this will just return playerIdx again.
*
* If players 1 and 2 swapped (e.g. in Hex), it will return an agent index
* of 1 for player index 2, and agent index of 2 for player index 1. This
* is because, after swapping, the agent who originally played as Player 1
* got swapped into playing as Player 2, and the agent who originally
* played as Player 2 got swapped into playing as Player 1.
*
* @param playerIdx
* @return Index of agent.
*/
public int playerToAgent(final int playerIdx)
{
// For players >= numPlayers, we just return the given playerIdx
if (playerIdx >= playerOrder.length)
return playerIdx;
// Fast return for what should be by far the most common case
if (playerOrder[playerIdx] == playerIdx)
return playerIdx;
for (int p = 1; p < playerOrder.length; ++p)
{
if (playerOrder[p] == playerIdx)
return p;
}
return Constants.UNDEFINED;
}
//-------------------------------------------------------------------------
/**
* To reset the state with another.
*
* @param other
* @param game
*/
public void resetStateTo(final State other, final Game game)
{
// NOTE: these can be copied by reference, because immutable once initialised
lowScoreHashes = other.lowScoreHashes;
highScoreHashes = other.highScoreHashes;
lowAmountHashes = other.lowAmountHashes;
highAmountHashes = other.highAmountHashes;
phaseHashes = other.phaseHashes;
isPendingHashes = other.isPendingHashes;
lastFromHashes = other.lastFromHashes;
lastToHashes = other.lastToHashes;
moverHashes = other.moverHashes;
nextHashes = other.nextHashes;
prevHashes = other.prevHashes;
activeHashes = other.activeHashes;
checkmatedHashes = other.checkmatedHashes;
stalematedHashes = other.stalematedHashes;
tempHashes = other.tempHashes;
playerOrderHashes = other.playerOrderHashes;
consecutiveTurnHashes = other.consecutiveTurnHashes;
playerSwitchHashes = other.playerSwitchHashes;
teamHashes = other.teamHashes;
numConsecutivePassesHashCap = other.numConsecutivePassesHashCap;
numConsecutivePassesHashes = other.numConsecutivePassesHashes;
playerOrder = Arrays.copyOf(other.playerOrder, other.playerOrder.length);
moneyPot = other.moneyPot;
// Back to the plot
trumpSuit = other.trumpSuit;
mover = other.mover;
next = other.next;
prev = other.prev;
triggered = other.triggered;
stalemated = other.stalemated;
if (other.containerStates == null)
{
containerStates = null;
}
else
{
containerStates = new ContainerState[other.containerStates.length];
for (int is = 0; is < containerStates.length; is++)
if (other.containerStates[is] == null)
containerStates[is] = null;
else
containerStates[is] = other.containerStates[is].deepClone();
}
counter = other.counter;
tempValue = other.tempValue;
if (other.pendingValues != null)
pendingValues = new TIntHashSet(other.pendingValues);
if (other.amount != null)
amount = Arrays.copyOf(other.amount, other.amount.length);
if (other.currentPhase != null)
currentPhase = Arrays.copyOf(other.currentPhase, other.currentPhase.length);
if (other.sumDice != null)
sumDice = Arrays.copyOf(other.sumDice, other.sumDice.length);
if (other.currentDice != null)
{
currentDice = new int[other.currentDice.length][];
for (int i = 0; i < currentDice.length; ++i)
{
currentDice[i] = Arrays.copyOf(other.currentDice[i], other.currentDice[i].length);
}
}
if (other.visited != null)
visited = (BitSet) other.visited.clone();
if (other.sitesToRemove != null)
sitesToRemove = new TIntArrayList(other.sitesToRemove);
if (other.teams != null)
teams = Arrays.copyOf(other.teams, other.teams.length);
if (other.votes != null)
{
votes = new TIntArrayList(other.votes);
propositions = new TIntArrayList(other.propositions);
isDecided = other.isDecided;
}
else
{
votes = null;
propositions = null;
isDecided = other.isDecided;
}
valuesPlayer = new int[other.valuesPlayer.length];
System.arraycopy(other.valuesPlayer, 0, valuesPlayer, 0, other.valuesPlayer.length);
if (other.notes != null)
notes = new TIntObjectHashMap<TIntObjectMap<String>>(other.notes);
numTurnSamePlayer = other.numTurnSamePlayer;
numTurn = other.numTurn;
if (other.owned == null)
owned = null;
else
owned = other.owned.copy();
diceAllEqual = other.diceAllEqual;
onTrackIndices = copyOnTrackIndices(other.onTrackIndices);
if (other.remainingDominoes != null)
remainingDominoes = new FastTIntArrayList(other.remainingDominoes);
if (other.rememberingValues != null)
rememberingValues = new FastTIntArrayList(other.rememberingValues);
if (other.mapRememberingValues != null)
{
mapRememberingValues = new HashMap<String, FastTIntArrayList>();
for (final Entry<String, FastTIntArrayList> entry : other.mapRememberingValues.entrySet())
{
final String key = entry.getKey();
final FastTIntArrayList rememberingList = entry.getValue();
final FastTIntArrayList copyRememberingList = new FastTIntArrayList(rememberingList);
mapRememberingValues.put(key, copyRememberingList);
}
}
storedState = other.storedState;
numConsecutivePasses = other.numConsecutivePasses;
if (other.valueMap != null)
valueMap = new TObjectIntHashMap<String>(other.valueMap);
if (game.isBoardless() && containerStates[0].isEmpty(game.board().topology().centre(SiteType.Cell).get(0).index(), SiteType.Cell))
containerStates[0].setPlayable(this, game.board().topology().centre(SiteType.Cell).get(0).index(), true);
stateHash = other.stateHash;
moverHash = other.moverHash;
nextHash = other.nextHash;
prevHash = other.prevHash;
activeHash = other.activeHash;
checkmatedHash = other.checkmatedHash;
stalematedHash = other.stalematedHash;
pendingHash = other.pendingHash;
scoreHash = other.scoreHash;
amountHash = other.amountHash;
}
//-------------------------------------------------------------------------
/**
* Method for copying another OnTrackIndices structure.
*
* NOTE: we override this for optimisations in CopyOnWriteState.
*
* @param otherOnTrackIndices
*/
@SuppressWarnings("static-method")
protected OnTrackIndices copyOnTrackIndices(final OnTrackIndices otherOnTrackIndices)
{
return otherOnTrackIndices == null ? null : new OnTrackIndices(otherOnTrackIndices);
}
/**
* To set on track indices.
* @param otherOnTrackIndices The on track indices to set.
*/
public void setOnTrackIndices(final OnTrackIndices otherOnTrackIndices)
{
this.onTrackIndices = (otherOnTrackIndices == null ? null : new OnTrackIndices(otherOnTrackIndices));
}
//-------------------------------------------------------------------------
/**
* Initialise this state for use.
*
* @param game
*/
public void initialise(final Game game)
{
moverHash = ZobristHashUtilities.INITIAL_VALUE;
nextHash = ZobristHashUtilities.INITIAL_VALUE;
prevHash = ZobristHashUtilities.INITIAL_VALUE;
activeHash = ZobristHashUtilities.INITIAL_VALUE;
checkmatedHash = ZobristHashUtilities.INITIAL_VALUE;
stalematedHash = ZobristHashUtilities.INITIAL_VALUE;
pendingHash = ZobristHashUtilities.INITIAL_VALUE;
stateHash = ZobristHashUtilities.INITIAL_VALUE;
scoreHash = ZobristHashUtilities.INITIAL_VALUE;
amountHash = ZobristHashUtilities.INITIAL_VALUE;
mover = 0;
next = 0;
prev = 0;
triggered = 0;
stalemated = 0;
moneyPot = 0;
final int numPlayers = game.players().count();
if (game.mode().mode() != ModeType.Simulation)
{
setMover(1);
if (numPlayers > 1)
setNext(2);
else
setNext(1);
setPrev(0);
}
else
{
setMover(0);
setNext(0);
setPrev(0);
}
for (final ContainerState is : containerStates)
if (is != null)
is.reset(this, game);
if (amount != null)
{
for (int index = 0; index < amount.length; index++)
amount[index] = 0;
}
Arrays.fill(valuesPlayer, Constants.UNDEFINED);
if (game.usesNote())
notes = new TIntObjectHashMap<TIntObjectMap<String>>();
initPhase(game);
if (game.usesVote())
{
isDecided = Constants.UNDEFINED;
votes.clear();
propositions.clear();
}
// We init the team to each player to it self
if (teams != null)
for (int i = 1; i < teams.length; i++)
teams[i] = i;
diceAllEqual = false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "info: mvr=" + mover() + ", nxt=" + next() + ", prv=" + prev() + ".\n";
str += Arrays.toString(containerStates) + "\n";
return str;
}
//-------------------------------------------------------------------------
/**
* @param player
* @return the amount of a player.
*/
public int amount(final int player)
{
if(amount != null)
return amount[player];
return 0;
}
/**
* @return the pot.
*/
public int pot()
{
return moneyPot;
}
/**
* To modify the pot.
*
* @param pot The pot value.
*/
public void setPot(final int pot)
{
moneyPot = pot;
}
/**
* To set a value for a specific player.
*
* @param player The player
* @param value The value
*/
public void setValueForPlayer(final int player, final int value)
{
valuesPlayer[player] = value;
}
/**
* @param player The player
* @return The value of a specific player.
*/
public int getValue(final int player)
{
return valuesPlayer[player];
}
/**
* Add a value to the map.
*
* @param key The key of the map.
* @param value The value.
*/
public void setValue(final String key, final int value)
{
valueMap.put(key, value);
}
/**
* remove a key from the map.
*
* @param key The key of the map.
*/
public void removeKeyValue(final String key)
{
valueMap.remove(key);
}
/**
* @param key The key of the map.
* @return value for this key, or Constants.OFF if not found
*/
public int getValue(final String key)
{
if (!valueMap.containsKey(key))
return Constants.OFF;
return valueMap.get(key);
}
/**
* @return To get the value map.
*/
public TObjectIntMap<String> getValueMap()
{
return valueMap;
}
/**
* To add a note to the list of note.
*
* @param move The index of the move.
* @param player The index of the player.
* @param message The note to add.
*/
public void addNote(final int move, final int player, final String message)
{
if (notes == null)
{
System.out.println("** State.addNote(): Null notes.");
return;
}
final TIntObjectMap<String> notesForMove = notes.get(move);
if (notesForMove == null)
notes.put(move, new TIntObjectHashMap<String>());
notes.get(move).put(player, message);
}
/**
* @param move The index of the move.
* @param player The index of the player.
*
* @return The note of send to a player at a specific move.
*/
public String getNote(final int move, final int player)
{
final TIntObjectMap<String> notesForMove = notes.get(move);
if (notesForMove == null)
return null;
return notes.get(move).get(player);
}
/**
* @return the notes.
*/
public TIntObjectMap<TIntObjectMap<String>> getNotes()
{
return notes;
}
/**
* Modify the amount of a player.
*
* @param player
* @param newAmount
*/
public void setAmount(final int player, final int newAmount)
{
if (player > 0 && player < amount.length)
{
updateAmountHash(player);
amount[player] = newAmount;
updateAmountHash(player);
}
}
private void updateAmountHash(final int player)
{
if (lowAmountHashes != null) // Otherwise, amount hashes are not used for this game even if amounts are
{
if (amount[player] <= AMOUNT_MAX_HASH)
amountHash ^= lowAmountHashes[player][amount[player]];
else
amountHash ^= highAmountHashes[player][amount[player] % AMOUNT_MAX_HASH];
}
}
/**
* Modify the score of a player.
*
* WARNING: this should only be called directly from Context!
*
* @param player
* @param score
* @param scoreArray The array of scores that we wish to modify
*/
public void setScore(final int player, final int score, final int[] scoreArray)
{
updateScoreHash(player, scoreArray);
scoreArray[player] = score;
updateScoreHash(player, scoreArray);
}
/**
* Modify the payoff of a player.
*
* WARNING: this should only be called directly from Context!
*
* @param player
* @param payoff
* @param payoffsArray The array of payoffs that we wish to modify
*/
@SuppressWarnings("static-method")
public void setPayoff(final int player, final double payoff, final double[] payoffsArray)
{
payoffsArray[player] = payoff;
}
private void updateScoreHash(final int player, final int[] scoreArray)
{
if (lowScoreHashes != null) // Otherwise, score hashes are not used for this game even if scores are
{
if (scoreArray[player] > SCORE_MAX_HASH)
scoreHash ^= highScoreHashes[player][(scoreArray[player]) % SCORE_MAX_HASH];
else if (scoreArray[player] < 0)
scoreHash ^= highScoreHashes[player][(-scoreArray[player]) % SCORE_MAX_HASH];
else
scoreHash ^= lowScoreHashes[player][scoreArray[player]];
}
}
private void updatePendingHash(final int pendingVal)
{
final int idx = pendingVal + 1;
if (idx < isPendingHashes.length)
pendingHash ^= isPendingHashes[idx];
else
pendingHash ^= isPendingHashes[idx % isPendingHashes.length];
}
/**
* Update number of consecutive passes
* @param lastMoveWasPass
*/
public void updateNumConsecutivePasses(final boolean lastMoveWasPass)
{
if (lastMoveWasPass)
++numConsecutivePasses;
else
numConsecutivePasses = 0;
}
/**
* @return Number of consecutive pass moves.
*/
public int numConsecutivesPasses()
{
return this.numConsecutivePasses;
}
/**
* To set the number of consecutive pass moves.
* @param numConsecutivesPasses Number of consecutive pass moves.
*/
public void setNumConsecutivesPasses(final int numConsecutivesPasses)
{
this.numConsecutivePasses = numConsecutivesPasses;
}
/**
* @return Counter.
*/
public int counter()
{
return counter;
}
/**
* To increment the counter.
*/
public void incrCounter()
{
counter++;
}
/**
* To decrement the counter.
*/
public void decrCounter()
{
counter--;
}
/**
* Sets counter.
* @param counter
*/
public void setCounter(final int counter)
{
this.counter = counter;
}
/**
* @return tempValue.
*/
public int temp()
{
return tempValue;
}
/**
* Sets the temp value.
* @param tempValue
*/
public void setTemp(final int tempValue)
{
updateStateHash(tempHashes[this.tempValue + Constants.CONSTANT_RANGE + 1]); // Allows tempValue to be Off or End
this.tempValue = tempValue;
updateStateHash(tempHashes[this.tempValue + Constants.CONSTANT_RANGE + 1]);
}
/**
* @return The pending values.
*/
public TIntHashSet pendingValues()
{
return pendingValues;
}
/**
* @return The propositions.
*/
public TIntArrayList propositions()
{
return propositions;
}
/**
* Clear the propositions.
*/
public void clearPropositions()
{
propositions.clear();
}
/**
* Clear the votes.
*/
public void clearVotes()
{
votes.clear();
}
/**
* @return The votes (represented as ints).
*/
public TIntArrayList votes()
{
return votes;
}
/**
* @return The decision of the vote.
*/
public int isDecided()
{
return isDecided;
}
/**
* To set the decision of the vote.
*
* @param isDecided The message.
*/
public void setIsDecided(final int isDecided)
{
this.isDecided = isDecided;
}
/**
* To add a pending value
*
* @param value The value to put in pending.
*/
public void setPending(final int value)
{
final int pendingValue = (value == Constants.UNDEFINED) ? 1 : value;
updatePendingHash(pendingValue);
if(pendingValues != null)
pendingValues.add(pendingValue);
}
/**
* @return True if the state is in pending.
*/
public boolean isPending()
{
return (pendingValues == null) ? false : !pendingValues.isEmpty();
}
/**
* @param value The value to remove from the pending values
*/
public void removePendingValue(final int value)
{
pendingValues.remove(value);
}
/**
* To clear the pending values
*/
public void rebootPending()
{
if (pendingValues != null)
{
final TIntIterator it = pendingValues.iterator();
while (it.hasNext())
{
updatePendingHash(it.next());
}
pendingValues.clear();
}
}
/**
* To restore the pending values.
* @param values The pending values.
*/
public void restorePending(final TIntHashSet values)
{
if(values != null)
{
rebootPending();
final TIntIterator it = values.iterator();
while (it.hasNext())
{
setPending(it.next());
}
}
}
/**
* @param indexPlayer
* @return current index of the phase of a player.
*/
public int currentPhase(final int indexPlayer)
{
// Matches have null for currentPhase
return currentPhase != null ? currentPhase[indexPlayer] : 0;
}
/**
* To set the current phase of a player
* @param indexPlayer
* @param newPhase
*/
public void setPhase(final int indexPlayer, final int newPhase)
{
if (phaseHashes != null)
updateStateHash(phaseHashes[indexPlayer][currentPhase[indexPlayer]]);
currentPhase[indexPlayer] = newPhase;
if (phaseHashes != null)
updateStateHash(phaseHashes[indexPlayer][currentPhase[indexPlayer]]);
}
/**
* To return the sum of the dice of a Dice container.
*
* @param index
* @return Sum of dice
*/
public int sumDice(final int index)
{
return sumDice[index];
}
/**
* For the copy constructor.
* @return Sum of dice array
*/
public int[] sumDice()
{
return sumDice;
}
/**
* @param sumDice
*/
public void setSumDice(final int[] sumDice)
{
this.sumDice = sumDice;
}
/**
* To reinit the sum of the dice.
*/
public void reinitSumDice()
{
for (int i = 0; i < sumDice.length; i++)
sumDice[i] = 0;
}
/**
* To return the current dice of a Dice container.
*
* @param index
* @return Current dice for (container?) index
*/
public int[] currentDice(final int index)
{
return currentDice[index];
}
/**
* To set the boolean diceAllEqual
*
* @param value
*/
public void setDiceAllEqual(final boolean value)
{
diceAllEqual = value;
}
/**
* @return If the dice are all equal when they are rolled.
*/
public boolean isDiceAllEqual()
{
return diceAllEqual;
}
/**
* For the copy constructor.
*
* @return All current dice
*/
public int[][] currentDice()
{
return currentDice;
}
/**
* @param currentDice
*/
public void setCurrentDice(final int[][] currentDice)
{
this.currentDice = currentDice;
}
/**
* To reinit the current dice.
*/
public void reinitCurrentDice()
{
for (int i = 0; i < currentDice.length; i++)
{
for (int j = 0; j < currentDice[i].length; j++)
{
currentDice[i][j] = 0;
}
}
}
/**
* Set the owned structure.
* @param owned The owned structure.
*/
public void setOwned(final Owned owned)
{
this.owned = owned.copy();
}
/**
* @return Owned sites per component
*/
public Owned owned()
{
return owned;
}
/**
* To update the sumDice of the dice container.
*
* @param dieValue
* @param indexHand
*/
public void updateSumDice(final int dieValue, final int indexHand)
{
sumDice[indexHand] += dieValue;
}
/**
* To update the current dice of the dice container.
*
* @param dieValue
* @param dieIndex
* @param indexHand
*/
public void updateCurrentDice(final int dieValue, final int dieIndex, final int indexHand)
{
currentDice[indexHand][dieIndex] = dieValue;
}
/**
* To reinit the visited BitSet.
*/
public void reInitVisited()
{
visited.clear();
}
/**
* @param site
* @return true if the site is already visited
*/
public boolean isVisited(final int site)
{
return visited.get(site);
}
/**
* To update the visited bitSet with the site visited.
*
* @param site
*/
public void visit(final int site)
{
if(visited.size() > site && site >= 0)
visited.set(site, true);
}
/**
* To unvi the visited bitSet with the site visited.
*
* @param site
*/
public void unvisit(final int site)
{
if(visited.size() > site && site >= 0)
visited.set(site, false);
}
/**
* @return visited sites.
*/
public BitSet visited()
{
return visited;
}
/**
* To reinit the visited BitSet.
*/
public void reInitCapturedPiece()
{
sitesToRemove.clear();
}
/**
* To add the site of the piece to remove to the pieceToRemove bitSet.
*
* @param site The site of the piece.
*/
public void addSitesToRemove(final int site)
{
sitesToRemove.add(site);
}
/**
* To remove the site of the piece to remove from the pieceToRemove bitSet.
*
* @param site The site of the piece.
*/
public void removeSitesToRemove(final int site)
{
sitesToRemove.remove(site);
}
/**
* @return List of sites from which to remove pieces (e.g. after finishing a sequence of
* capturing hops in International Draughts)
*/
public TIntArrayList sitesToRemove()
{
return sitesToRemove;
}
/**
* @param pid
* @param tid
* @return true if the player pid is in the team tid
*/
public boolean playerInTeam(final int pid, final int tid)
{
if (teams == null || pid >= teams.length)
return false;
return teams[pid] == tid;
}
/**
* To put a player in a team
*
* @param pid
* @param tid
*/
public void setPlayerToTeam(final int pid, final int tid)
{
updateStateHash(teamHashes[pid][teams[pid]]);
teams[pid] = tid;
updateStateHash(teamHashes[pid][teams[pid]]);
}
/**
* @param pid
* @return The index of the team of the player pid
*/
public int getTeam(final int pid)
{
if (teams == null || pid >= teams.length)
return Constants.UNDEFINED;
return teams[pid];
}
/**
* All the pieces to remove.
*
* @return Region containing all sites to remove
*/
public Region regionToRemove()
{
if (sitesToRemove == null)
return new Region();
return new Region(sitesToRemove.toArray());
}
/**
* @return sameTurnPlayed.
*/
public int numTurnSamePlayer()
{
return numTurnSamePlayer;
}
/**
* To reinit the number of turn played by the same player
*/
public void reinitNumTurnSamePlayer()
{
numTurnSamePlayer = 0;
++numTurn;
}
/**
* @param numTurnSamePlayer The number of moves of the same player so far in the turn.
*/
public void setTurnSamePlayer(final int numTurnSamePlayer)
{
this.numTurnSamePlayer = numTurnSamePlayer;
}
/**
* to increment the number of turn played by the same player
*/
public void incrementNumTurnSamePlayer()
{
numTurnSamePlayer++;
}
/**
* @return How often did we switch over to a new player as mover?
*/
public int numTurn()
{
return numTurn;
}
/**
* @param numTurn The number of turns.
*/
public void setNumTurn(final int numTurn)
{
this.numTurn = numTurn;
}
//-------------------------------------------------------------------------
@Override
public boolean equals(final Object other)
{
if (!(other instanceof State))
{
return false;
}
final State otherState = (State) other;
return fullHash() == otherState.fullHash();
}
@Override
public int hashCode()
{
return (int)(fullHash()&0xFF_FF_FF_FF); // Bottom 32 bits of full hash
}
/**
* To init the phase of the initial state.
*
* @param game
*/
public void initPhase(final Game game)
{
if (game.rules() != null && game.rules().phases() != null)
{
currentPhase = new int[game.players().count() + 1];
for (int pid = 1; pid <= game.players().count(); pid++)
{
for (int indexPhase = 0; indexPhase < game.rules().phases().length; indexPhase++)
{
final Phase phase = game.rules().phases()[indexPhase];
final RoleType roleType = phase.owner();
if (roleType == null)
continue;
final int phaseOwner = roleType.owner();
if (phaseOwner == pid || roleType == RoleType.Shared)
{
currentPhase[pid] = indexPhase;
break;
}
}
}
// System.out.println("INIT PHASES:");
// for (int i = 1; i <= currentPhase.length; i++)
// System.out.println("Player " + i + " Phase = " + currentPhase[i - 1]);
}
}
/**
* @return The current suit trump.
*/
public int trumpSuit()
{
return trumpSuit;
}
/**
* To set the trump suit.
*
* @param trumpSuit
*/
public void setTrumpSuit(final int trumpSuit)
{
this.trumpSuit = trumpSuit;
}
/**
* @return The structure to get the indices of each element on the track.
*/
public OnTrackIndices onTrackIndices()
{
return onTrackIndices;
}
//-------------------------------------------------------------------------
/**
* To swap the player in the list.
*
* @param player1 The first player.
* @param player2 The second player.
*/
public void swapPlayerOrder(final int player1, final int player2)
{
int currentIndex1 = 0, currentindex2 = 0;
for (int i = 1; i < playerOrder.length; i++)
{
if (playerOrder[i] == player1)
currentIndex1 = i;
if (playerOrder[i] == player2)
currentindex2 = i;
}
final int temp = playerOrder[currentIndex1];
updateStateHash(playerOrderHashes[currentIndex1][playerOrder[currentIndex1]]);
playerOrder[currentIndex1] = playerOrder[currentindex2];
updateStateHash(playerOrderHashes[currentIndex1][playerOrder[currentIndex1]]);
updateStateHash(playerOrderHashes[currentindex2][playerOrder[currentindex2]]);
playerOrder[currentindex2] = temp;
updateStateHash(playerOrderHashes[currentindex2][playerOrder[currentindex2]]);
}
/**
* @param playerId The player.
* @return The index in the order of a player.
*/
public int currentPlayerOrder(final int playerId)
{
return playerOrder[playerId];
}
/**
* @param playerId The player.
* @return The index of the player in the original order.
*/
public int originalPlayerOrder(final int playerId)
{
for (int p = 1; p < playerOrder.length; p++)
if (playerOrder[p] == playerId)
return p;
for (int po = 0; po < playerOrder.length; po++)
System.out.println("playerOrder[" + po + "] = " + playerOrder[po]);
throw new RuntimeException("Player " + playerId + " has disappeared after swapping!");
//return Constants.UNDEFINED;
}
/**
* @return True if the order has changed.
*/
public boolean orderHasChanged()
{
for (int p = 1; p < playerOrder.length; p++)
if (playerOrder[p] != p)
return true;
return false;
}
//-------------------------------------------------------------------------
/**
* @return The remaining dominoes
*/
public FastTIntArrayList remainingDominoes()
{
return remainingDominoes;
}
//-------------------------------------------------------------------------
/**
* @return The values stored in previous states.
*/
public FastTIntArrayList rememberingValues()
{
return rememberingValues;
}
/**
* @return The values stored in previous states and associated to a name.
*/
public Map<String, FastTIntArrayList> mapRememberingValues()
{
return mapRememberingValues;
}
//-------------------------------------------------------------------------
/**
* @return The state stored in the game.
*/
public long storedState()
{
return storedState;
}
/**
* To store a state of the game
*
* @param state The state to store.
*/
public void storeCurrentState(final State state)
{
storedState = state.stateHash();
}
/**
* To restore a state of the game
*
* @param value The state hash value to restore.
*/
public void restoreCurrentState(final long value)
{
storedState = value;
}
//-------------------------------------------------------------------------
/**
* @param context The current context.
* @return The concepts involved in this specific state.
*/
@SuppressWarnings("static-method")
public BitSet concepts(final Context context)
{
// TODO CHECK LEGAL MOVES CONCEPT, CHECK ONLY PIECES CONCEPT ON BOARD, BUT NEED TO DISCUSS WITH MATTHEW BEFORE TO FINISH THAT CODE.
final Game game = context.game();
final BitSet concepts = new BitSet();
// Accumulate concepts over the players.
concepts.or(game.players().concepts(game));
// Accumulate concepts for all the containers.
for (int i = 0; i < game.equipment().containers().length; i++)
concepts.or(game.equipment().containers()[i].concepts(game));
// Accumulate concepts for all the components.
for (int i = 1; i < game.equipment().components().length; i++)
concepts.or(game.equipment().components()[i].concepts(game));
// // Accumulate concepts for all the regions.
// for (int i = 0; i < equipment().regions().length; i++)
// concept.or(equipment().regions()[i].concepts(this));
//
// // Accumulate concepts for all the maps.
// for (int i = 0; i < equipment().maps().length; i++)
// concept.or(equipment().maps()[i].concepts(this));
//
// // Look if the game uses hints.
// if (equipment().vertexHints().length != 0 || equipment().cellsWithHints().length != 0
// || equipment().edgesWithHints().length != 0)
// concept.set(Concept.Hints.id(), true);
//
// // Check if some regions are defined.
// if (equipment().regions().length != 0)
// concept.set(Concept.Region.id(), true);
//
// // Accumulate concepts over meta rules
// if (rules.meta() != null)
// for (final MetaRule meta : rules.meta().rules())
// concept.or(meta.concepts(this));
//
// // Accumulate concepts over the ending rules.
// if (rules.end() != null)
// concept.or(rules.end().concepts(this));
//
// // Look if the game uses a stack state.
// if (isStacking())
// {
// concept.set(Concept.StackState.id(), true);
// concept.set(Concept.Stack.id(), true);
// }
//
// // Look the graph element types used.
// concept.or(SiteType.concepts(board().defaultSite()));
return concepts;
}
}
| 55,690 | 23.984747 | 180 | java |
Ludii | Ludii-master/Core/src/other/state/container/BaseContainerState.java | package other.state.container;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.util.equipment.Region;
import other.Sites;
import other.state.State;
import other.state.symmetry.SymmetryType;
import other.state.symmetry.SymmetryUtils;
import other.state.symmetry.SymmetryValidator;
/**
* Global State for a container item.
*
* @author cambolbro, mrraow and tahmina(UF)
*/
public abstract class BaseContainerState implements ContainerState
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Reference to corresponding source container. */
private transient Container container;
/**
* Name of container. Often actually left at null, only need it when reading
* item states from files.
*/
private transient String nameFromFile = null;
/** Lookup containing all symmetry hashes */
private final Map<Long, Long> canonicalHashLookup;
/** Which slots are empty. */
protected final Region empty;
/** Offset for this state's container */
protected final int offset;
//-------------------------------------------------------------------------
/**
* Constructor.
* @param game
* @param container
* @param numSites
*/
public BaseContainerState
(
final Game game,
final Container container,
final int numSites
)
{
this.container = container;
final int realNumsites = container.index() == 0 ? game.board().topology().cells().size() : numSites;
this.empty = new Region(realNumsites);
this.offset = game.equipment().sitesFrom()[container.index()];
canonicalHashLookup = new HashMap<>();
}
/**
* Copy constructor.
*
* @param other
*/
public BaseContainerState(final BaseContainerState other)
{
container = other.container;
empty = new Region(other.empty);
this.offset = other.offset;
this.canonicalHashLookup = other.canonicalHashLookup;
}
//-------------------------------------------------------------------------
/**
* @param trialState The state.
* @param other The containerState to copy.
*/
public void deepCopy(final State trialState, final BaseContainerState other)
{
this.container = other.container;
empty.set(other.empty);
}
/**
* Reset this state.
*/
@Override
public void reset(final State trialState, final Game game)
{
final int numSites = container.numSites();
final int realNumsites = container.index() == 0 ? game.board().topology().cells().size() : numSites;
empty.set(realNumsites);
}
//-------------------------------------------------------------------------
@Override
public String nameFromFile()
{
return nameFromFile;
}
@Override
public Container container()
{
return container;
}
@Override
public void setContainer(final Container cont)
{
container = cont;
}
//-------------------------------------------------------------------------
@Override
public Sites emptySites()
{
return new Sites(empty.sites());
}
@Override
public int numEmpty()
{
return empty.count();
}
@Override
public boolean isEmpty(final int site, final SiteType type)
{
if (type == null || type == SiteType.Cell || container().index() != 0)
return isEmptyCell(site);
else if (type.equals(SiteType.Edge))
return isEmptyEdge(site);
else
return isEmptyVertex(site);
}
@Override
public boolean isEmptyVertex(final int vertex)
{
return true;
}
@Override
public boolean isEmptyEdge(final int edge)
{
return true;
}
@Override
public boolean isEmptyCell(final int site)
{
return empty.contains(site - offset);
}
@Override
public Region emptyRegion(final SiteType type)
{
return empty;
}
@Override
public void addToEmptyCell(final int site)
{
empty.add(site - offset);
}
@Override
public void removeFromEmptyCell(final int site)
{
empty.remove(site - offset);
}
@Override
public void addToEmptyVertex(final int site)
{
// Nothing to do.
}
@Override
public void removeFromEmptyVertex(final int site)
{
// Nothing to do.
}
@Override
public void addToEmptyEdge(final int site)
{
// Nothing to do.
}
@Override
public void removeFromEmptyEdge(final int site)
{
// Nothing to do.
}
@Override
public void addToEmpty(final int site, final SiteType graphType)
{
if (graphType == null || graphType == SiteType.Cell || container().index() != 0)
addToEmptyCell(site);
else if (graphType.equals(SiteType.Edge))
addToEmptyEdge(site);
else
addToEmptyVertex(site);
}
@Override
public void removeFromEmpty(final int site, final SiteType graphType)
{
if (graphType == null || graphType == SiteType.Cell || container().index() != 0)
removeFromEmptyCell(site);
else if (graphType.equals(SiteType.Edge))
removeFromEmptyEdge(site);
else
removeFromEmptyVertex(site);
}
//-------------------------------------------------------------------------
/**
* Serializes the ItemState
* @param out
* @throws IOException
*/
private void writeObject(final ObjectOutputStream out) throws IOException
{
// Use default writer to write all fields of subclasses, like ChunkSets
// this will not include our container, because it's transient
out.defaultWriteObject();
// now write just the name of the container
out.writeUTF(container.name());
}
/**
* Deserializes the ItemState
* @param in
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(final ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// Use default reader to read all fields of subclasses, like ChunkSets
// This will not include our container, because it's transient
in.defaultReadObject();
// now read the name of our container
nameFromFile = in.readUTF();
}
@Override
public void setPlayable(final State trialState, final int site, final boolean on)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (empty.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (!(obj instanceof BaseContainerState))
return false;
final BaseContainerState other = (BaseContainerState) obj;
if (!empty.equals(other.empty))
return false;
return true;
}
@Override
public int what(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whatCell(site);
else if (graphElementType == SiteType.Edge)
return whatEdge(site);
else
return whatVertex(site);
}
@Override
public int who(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whoCell(site);
else if (graphElementType == SiteType.Edge)
return whoEdge(site);
else
return whoVertex(site);
}
@Override
public int count(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return countCell(site);
else if (graphElementType == SiteType.Edge)
return countEdge(site);
else
return countVertex(site);
}
@Override
public int sizeStack(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return sizeStackCell(site);
else if (graphElementType == SiteType.Edge)
return whatEdge(site) == 0 ? 0 : 1;
else
return whatVertex(site) == 0 ? 0 : 1;
}
@Override
public int state(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return stateCell(site);
else if (graphElementType == SiteType.Edge)
return stateEdge(site);
else
return stateVertex(site);
}
@Override
public int rotation(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return rotationCell(site);
else if (graphElementType == SiteType.Edge)
return rotationEdge(site);
else
return rotationVertex(site);
}
@Override
public int value(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return valueCell(site);
else if (graphElementType == SiteType.Edge)
return valueEdge(site);
else
return valueVertex(site);
}
//-------------------Methods with levels---------------------
@Override
public int what(final int site, final int level,
final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whatCell(site, level);
else if (graphElementType == SiteType.Edge)
return whatEdge(site, level);
else
return whatVertex(site, level);
}
@Override
public int who(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whoCell(site, level);
else if (graphElementType == SiteType.Edge)
return whoEdge(site, level);
else
return whoVertex(site, level);
}
@Override
public int state(final int site, final int level,
final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return stateCell(site, level);
else if (graphElementType == SiteType.Edge)
return stateEdge(site, level);
else
return stateVertex(site, level);
}
@Override
public int rotation(final int site, final int level,
final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return rotationCell(site, level);
else if (graphElementType == SiteType.Edge)
return rotationEdge(site, level);
else
return rotationVertex(site, level);
}
@Override
public int value(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return valueCell(site, level);
else if (graphElementType == SiteType.Edge)
return valueEdge(site, level);
else
return valueVertex(site, level);
}
@Override
public void set(final int var, final int value, final SiteType type)
{
// Nothing to do.
}
@Override
public boolean bit(final int index, final int value, final SiteType type)
{
return true;
}
@Override
public boolean isResolvedEdges(final int site)
{
return false;
}
@Override
public boolean isResolvedCell(final int site)
{
return false;
}
@Override
public boolean isResolvedVerts(final int site)
{
return false;
}
@Override
public boolean isResolved(final int site, final SiteType type)
{
return false;
}
@Override
public final long canonicalHash(final SymmetryValidator validator, final State gameState, final boolean whoOnly)
{
// Lazy initialisation
if (container().topology().cellRotationSymmetries()==null)
Container.createSymmetries(container().topology());
final List<Long> allHashes = new ArrayList<>();
final int[][] cellRotates = container().topology().cellRotationSymmetries();
final int[][] cellReflects = container().topology().cellReflectionSymmetries();
final int[][] edgeRotates = container().topology().edgeRotationSymmetries();
final int[][] edgeReflects = container().topology().edgeReflectionSymmetries();
final int[][] vertexRotates = container().topology().vertexRotationSymmetries();
final int[][] vertexReflects = container().topology().vertexReflectionSymmetries();
final int[][] playerPermutations = SymmetryUtils.playerPermutations(gameState.numPlayers());
long canonicalHash = Long.MAX_VALUE;
// Note that the permutations include the identity mapping
for (int playerIdx = 0; playerIdx < playerPermutations.length; playerIdx++)
{
if (!validator.isValid(SymmetryType.SUBSTITUTIONS, playerIdx, playerPermutations.length)) continue;
for (int rotateIdx = 0; rotateIdx < cellRotates.length; rotateIdx++)
{
if (!validator.isValid(SymmetryType.ROTATIONS, rotateIdx, cellRotates.length)) continue;
// Rotate without reflection...
{
final long hash = calcCanonicalHash(cellRotates[rotateIdx], edgeRotates[rotateIdx], vertexRotates[rotateIdx], playerPermutations[playerIdx], whoOnly);
canonicalHash = Math.min(canonicalHash,hash);
final Long key = Long.valueOf(hash);
// Try a shortcut on the first pass only; we may already have cached this state
// if (playerIdx == 0 && rotateIdx==0)
// {
// final Long smallest = canonicalHashLookup.get(key);
// if (smallest != null) return smallest.longValue();
// }
allHashes.add(key);
}
// --- then combination of rotates and reflections
// Note that the first rotation is always the identity (0 degrees), so no need for reflects without rotates
for (int reflectIdx = 0; reflectIdx < cellReflects.length; reflectIdx++)
{
if (!validator.isValid(SymmetryType.REFLECTIONS, reflectIdx, cellReflects.length)) continue;
final int[] siteRemap = SymmetryUtils.combine(cellReflects[reflectIdx], cellRotates[rotateIdx]);
final int[] edgeRemap = SymmetryUtils.combine(edgeReflects[reflectIdx], edgeRotates[rotateIdx]);
final int[] vertexRemap = SymmetryUtils.combine(vertexReflects[reflectIdx], vertexRotates[rotateIdx]);
final long hash = calcCanonicalHash(siteRemap, edgeRemap, vertexRemap, playerPermutations[playerIdx], whoOnly);
canonicalHash = Math.min(canonicalHash,hash);
allHashes.add(Long.valueOf(hash));
}
}
}
// Store the hashes, to save time next time...
final Long smallest = Long.valueOf(canonicalHash);
for (final Long key : allHashes)
canonicalHashLookup.put(key, smallest);
return canonicalHash;
}
protected abstract long calcCanonicalHash(int[] siteRemap, int[] edgeRemap, int[] vertexRemap, int[] playerRemap, boolean whoOnly);
@Override
public BitSet values(final SiteType type, final int var)
{
return new BitSet();
}
}
| 14,608 | 25.370036 | 155 | java |
Ludii | Ludii-master/Core/src/other/state/container/ContainerFlatEdgeState.java | package other.state.container;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.equipment.Region;
import main.Constants;
import main.collections.ChunkSet;
import other.Sites;
import other.state.State;
import other.state.zhash.HashedBitSet;
import other.state.zhash.HashedChunkSet;
import other.state.zhash.ZobristHashGenerator;
/**
* Global State for a container item using only edges.
*
* @author Eric.Piette
*/
public class ContainerFlatEdgeState extends BaseContainerState
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Owner of an edge. */
private final HashedChunkSet whoEdge;
/** Type of Item on an edge. */
private final HashedChunkSet whatEdge;
/** Count of an edge. */
private final HashedChunkSet countEdge;
/** State of an edge. */
private final HashedChunkSet stateEdge;
/** Rotation of a edge. */
private final HashedChunkSet rotationEdge;
/** Value of the piece on an edge. */
private final HashedChunkSet valueEdge;
/** Which edge has some hidden properties for each player. */
private final HashedBitSet[] hiddenEdge;
/** Which edge has the what information hidden for each player. */
private final HashedBitSet[] hiddenWhatEdge;
/** Which edge has the who information hidden for each player. */
private final HashedBitSet[] hiddenWhoEdge;
/** Which edge has the count information hidden for each player. */
private final HashedBitSet[] hiddenCountEdge;
/** Which edge has the state information hidden for each player. */
private final HashedBitSet[] hiddenStateEdge;
/** Which edge has the rotation information hidden for each player. */
private final HashedBitSet[] hiddenRotationEdge;
/** Which edge has the value information hidden for each player. */
private final HashedBitSet[] hiddenValueEdge;
/** Which edge slots are empty. */
private final Region emptyEdge;
//-------------------------------------------------------------------------
/**
* Constructor of a flat container.
*
* @param generator
* @param game
* @param container
* @param maxWhatVal
* @param maxStateVal
* @param maxCountVal
* @param maxRotationVal
* @param maxPieceValue
*/
public ContainerFlatEdgeState
(
final ZobristHashGenerator generator,
final Game game,
final Container container,
final int maxWhatVal,
final int maxStateVal,
final int maxCountVal,
final int maxRotationVal,
final int maxPieceValue
)
{
super
(
game,
container,
container.numSites()
);
final int numPlayers = game.players().count();
final int numEdges = game.board().topology().edges().size();
if ((game.gameFlags() & GameType.HiddenInfo) == 0L)
{
hiddenEdge = null;
hiddenWhatEdge = null;
hiddenWhoEdge = null;
hiddenCountEdge = null;
hiddenStateEdge = null;
hiddenRotationEdge = null;
hiddenValueEdge = null;
}
else
{
hiddenEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenEdge[i] = new HashedBitSet(generator, numEdges);
hiddenWhatEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWhatEdge[i] = new HashedBitSet(generator, numEdges);
hiddenWhoEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWhoEdge[i] = new HashedBitSet(generator, numEdges);
hiddenCountEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenCountEdge[i] = new HashedBitSet(generator, numEdges);
hiddenStateEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenStateEdge[i] = new HashedBitSet(generator, numEdges);
hiddenRotationEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenRotationEdge[i] = new HashedBitSet(generator, numEdges);
hiddenValueEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenValueEdge[i] = new HashedBitSet(generator, numEdges);
}
this.whoEdge = new HashedChunkSet(generator, numPlayers + 1, numEdges);
whatEdge = maxWhatVal > 0 ? new HashedChunkSet(generator, maxWhatVal, numEdges) : null;
countEdge = maxCountVal > 0 ? new HashedChunkSet(generator, maxCountVal, numEdges) : null;
stateEdge = maxStateVal > 0 ? new HashedChunkSet(generator, maxStateVal, numEdges) : null;
rotationEdge = maxRotationVal > 0 ? new HashedChunkSet(generator, maxRotationVal, numEdges) : null;
valueEdge = maxPieceValue > 0 ? new HashedChunkSet(generator, maxPieceValue, numEdges) : null;
this.emptyEdge = new Region(numEdges);
}
/**
* Copy constructor.
*
* @param other
*/
public ContainerFlatEdgeState(final ContainerFlatEdgeState other)
{
super(other);
if (other.hiddenEdge != null)
{
hiddenEdge = new HashedBitSet[other.hiddenEdge.length];
for (int i = 1; i < other.hiddenEdge.length; i++)
hiddenEdge[i] = (other.hiddenEdge[i] == null) ? null : other.hiddenEdge[i].clone();
hiddenWhatEdge = new HashedBitSet[other.hiddenWhatEdge.length];
for (int i = 1; i < other.hiddenWhatEdge.length; i++)
hiddenWhatEdge[i] = (other.hiddenWhatEdge[i] == null) ? null : other.hiddenWhatEdge[i].clone();
hiddenWhoEdge = new HashedBitSet[other.hiddenWhoEdge.length];
for (int i = 1; i < other.hiddenWhoEdge.length; i++)
hiddenWhoEdge[i] = (other.hiddenWhoEdge[i] == null) ? null : other.hiddenWhoEdge[i].clone();
hiddenCountEdge = new HashedBitSet[other.hiddenCountEdge.length];
for (int i = 1; i < other.hiddenCountEdge.length; i++)
hiddenCountEdge[i] = (other.hiddenCountEdge[i] == null) ? null : other.hiddenCountEdge[i].clone();
hiddenStateEdge = new HashedBitSet[other.hiddenStateEdge.length];
for (int i = 1; i < other.hiddenStateEdge.length; i++)
hiddenStateEdge[i] = (other.hiddenStateEdge[i] == null) ? null : other.hiddenStateEdge[i].clone();
hiddenRotationEdge = new HashedBitSet[other.hiddenRotationEdge.length];
for (int i = 1; i < other.hiddenRotationEdge.length; i++)
hiddenRotationEdge[i] = (other.hiddenRotationEdge[i] == null) ? null
: other.hiddenRotationEdge[i].clone();
hiddenValueEdge = new HashedBitSet[other.hiddenValueEdge.length];
for (int i = 1; i < other.hiddenValueEdge.length; i++)
hiddenValueEdge[i] = (other.hiddenValueEdge[i] == null) ? null : other.hiddenValueEdge[i].clone();
}
else
{
hiddenEdge = null;
hiddenWhatEdge = null;
hiddenWhoEdge = null;
hiddenCountEdge = null;
hiddenRotationEdge = null;
hiddenValueEdge = null;
hiddenStateEdge = null;
}
this.whoEdge = (other.whoEdge == null) ? null : other.whoEdge.clone();
this.whatEdge = (other.whatEdge == null) ? null : other.whatEdge.clone();
this.countEdge = (other.countEdge == null) ? null : other.countEdge.clone();
this.stateEdge = (other.stateEdge == null) ? null : other.stateEdge.clone();
this.rotationEdge = (other.rotationEdge == null) ? null : other.rotationEdge.clone();
this.valueEdge = (other.valueEdge == null) ? null : other.valueEdge.clone();
this.emptyEdge = (other.emptyEdge == null) ? null : new Region(other.emptyEdge);
}
@Override
public ContainerFlatEdgeState deepClone()
{
return new ContainerFlatEdgeState(this);
}
//-------------------------------------------------------------------------
@Override
protected long calcCanonicalHash(final int[] siteRemap, final int[] edgeRemap, final int[] vertexRemap,
final int[] playerRemap, final boolean whoOnly)
{
long hash = 0;
if (vertexRemap != null && vertexRemap.length > 0)
{
if (whoEdge != null)
hash ^= whoEdge.calculateHashAfterRemap(vertexRemap, playerRemap);
if (!whoOnly)
{
if (whatEdge != null)
hash ^= whatEdge.calculateHashAfterRemap(vertexRemap, null);
if (countEdge != null)
hash ^= countEdge.calculateHashAfterRemap(vertexRemap, null);
if (stateEdge != null)
hash ^= stateEdge.calculateHashAfterRemap(vertexRemap, null);
if (rotationEdge != null)
hash ^= rotationEdge.calculateHashAfterRemap(vertexRemap, null);
if (hiddenEdge != null)
{
for (int i = 1; i < hiddenEdge.length; i++)
hash ^= hiddenEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhatEdge != null)
{
for (int i = 1; i < hiddenWhatEdge.length; i++)
hash ^= hiddenWhatEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhoEdge != null)
{
for (int i = 1; i < hiddenWhoEdge.length; i++)
hash ^= hiddenWhoEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenCountEdge != null)
{
for (int i = 1; i < hiddenCountEdge.length; i++)
hash ^= hiddenCountEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenRotationEdge != null)
{
for (int i = 1; i < hiddenRotationEdge.length; i++)
hash ^= hiddenRotationEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenValueEdge != null)
{
for (int i = 1; i < hiddenValueEdge.length; i++)
hash ^= hiddenValueEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenStateEdge != null)
{
for (int i = 1; i < hiddenStateEdge.length; i++)
hash ^= hiddenStateEdge[i].calculateHashAfterRemap(siteRemap, false);
}
}
}
return hash;
}
//-------------------------------------------------------------------------
/**
* Reset this state.
*/
@Override
public void reset(final State trialState, final Game game)
{
super.reset(trialState, game);
final int numEdge = game.board().topology().edges().size();
super.reset(trialState, game);
if (whoEdge != null)
whoEdge.clear(trialState);
if (whatEdge != null)
whatEdge.clear(trialState);
if (countEdge != null)
countEdge.clear(trialState);
if (stateEdge != null)
stateEdge.clear(trialState);
if (rotationEdge != null)
rotationEdge.clear(trialState);
if (valueEdge != null)
valueEdge.clear(trialState);
if (hiddenEdge != null)
for (int i = 1; i < hiddenEdge.length; i++)
hiddenEdge[i].clear(trialState);
if (hiddenWhatEdge != null)
for (int i = 1; i < hiddenWhatEdge.length; i++)
hiddenWhatEdge[i].clear(trialState);
if (hiddenWhoEdge != null)
for (int i = 1; i < hiddenWhoEdge.length; i++)
hiddenWhoEdge[i].clear(trialState);
if (hiddenCountEdge != null)
for (int i = 1; i < hiddenCountEdge.length; i++)
hiddenCountEdge[i].clear(trialState);
if (hiddenRotationEdge != null)
for (int i = 1; i < hiddenRotationEdge.length; i++)
hiddenRotationEdge[i].clear(trialState);
if (hiddenValueEdge != null)
for (int i = 1; i < hiddenValueEdge.length; i++)
hiddenValueEdge[i].clear(trialState);
if (hiddenStateEdge != null)
for (int i = 1; i < hiddenStateEdge.length; i++)
hiddenStateEdge[i].clear(trialState);
if (emptyEdge != null)
emptyEdge.set(numEdge);
}
//-------------------------------------------------------------------------
@Override
public boolean isHidden(final int player, final int site, final int level, final SiteType type)
{
if (hiddenEdge == null)
return false;
if (player < 1 || player > (hiddenEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hidden ...) in the containerState. Player = "
+ player);
return this.hiddenEdge[player].get(site);
}
@Override
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType type)
{
if (hiddenWhatEdge == null)
return false;
if (player < 1 || player > (hiddenWhatEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenWhat ...) in the containerState. Player = "
+ player);
return this.hiddenWhatEdge[player].get(site);
}
@Override
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType type)
{
if (hiddenWhoEdge == null)
return false;
if (player < 1 || player > (hiddenWhoEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenWho ...) in the containerState. Player = "
+ player);
return this.hiddenWhoEdge[player].get(site);
}
@Override
public boolean isHiddenState(final int player, final int site, final int level, final SiteType type)
{
if (hiddenStateEdge == null)
return false;
if (player < 1 || player > (hiddenStateEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenState ...) in the containerState. Player = "
+ player);
return this.hiddenStateEdge[player].get(site);
}
@Override
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType type)
{
if (hiddenRotationEdge == null)
return false;
if (player < 1 || player > (hiddenRotationEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenRotation ...) in the containerState. Player = "
+ player);
return this.hiddenRotationEdge[player].get(site);
}
@Override
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType type)
{
if (hiddenValueEdge == null)
return false;
if (player < 1 || player > (hiddenValueEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenValue ...) in the containerState. Player = "
+ player);
return this.hiddenValueEdge[player].get(site);
}
@Override
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType type)
{
if (hiddenCountEdge == null)
return false;
if (player < 1 || player > (hiddenCountEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenCount ...) in the containerState. Player = "
+ player);
return this.hiddenCountEdge[player].get(site);
}
@Override
public void setHidden(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (hiddenEdge == null)
throw new UnsupportedOperationException("No Hidden information, but the method (setHidden ...) was called");
if (player < 1 || player > (hiddenEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHidden ...) in the containerState. Player = "
+ player);
this.hiddenEdge[player].set(state, site, on);
}
@Override
public void setHiddenWhat(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (hiddenWhatEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWhat ...) was called");
if (player < 1 || player > (hiddenWhatEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWhat ...) in the containerState. Player = "
+ player);
this.hiddenWhatEdge[player].set(state, site, on);
}
@Override
public void setHiddenWho(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (hiddenWhoEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWho ...) was called");
if (player < 1 || player > (hiddenWhoEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWho ...) in the containerState. Player = "
+ player);
this.hiddenWhoEdge[player].set(state, site, on);
}
@Override
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenStateEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenState ...) was called");
if (player < 1 || player > (hiddenStateEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenState ...) in the containerState. Player = "
+ player);
this.hiddenStateEdge[player].set(state, site, on);
}
@Override
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenRotationEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenRotation ...) was called");
if (player < 1 || player > (hiddenRotationEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenRotation ...) in the containerState. Player = "
+ player);
this.hiddenRotationEdge[player].set(state, site, on);
}
@Override
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenValueEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenValue ...) was called");
if (player < 1 || player > (hiddenValueEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenValue ...) in the containerState. Player = "
+ player);
this.hiddenValueEdge[player].set(state, site, on);
}
@Override
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenCountEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenCount ...) was called");
if (player < 1 || player > (hiddenCountEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenCount ...) in the containerState. Player = "
+ player);
this.hiddenCountEdge[player].set(state, site, on);
}
//-------------------------------------------------------------------------
@Override
public boolean isPlayable(final int site)
{
return true;
}
@Override
public void setPlayable(final State trialState, final int site, final boolean on)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public boolean isOccupied(final int site)
{
return countEdge(site) != 0;
}
//-------------------------------------------------------------------------
@Override
public void setSite(final State trialState, final int site, final int whoVal, final int whatVal, final int countVal,
final int stateVal, final int rotationVal, final int valueVal, final SiteType type)
{
final boolean wasEmpty = !isOccupied(site);
if (whoVal != Constants.UNDEFINED)
whoEdge.setChunk(trialState, site, whoVal);
if (whatVal != Constants.UNDEFINED)
defaultIfNull(whatEdge).setChunk(trialState, site, whatVal);
if (countVal != Constants.UNDEFINED)
{
if (countEdge != null)
countEdge.setChunk(trialState, site, (countVal < 0 ? 0 : countVal));
else if (countEdge == null && countVal > 1)
throw new UnsupportedOperationException(
"This game does not support counts, but a count > 1 has been set. countVal=" + countVal);
}
if (stateVal != Constants.UNDEFINED)
{
if (stateEdge != null)
stateEdge.setChunk(trialState, site, stateVal);
else if (stateVal != 0)
throw new UnsupportedOperationException(
"This game does not support states, but a state has been set. stateVal=" + stateVal);
}
if (rotationVal != Constants.UNDEFINED)
{
if (rotationEdge != null)
rotationEdge.setChunk(trialState, site, rotationVal);
else if (rotationVal != 0)
throw new UnsupportedOperationException(
"This game does not support rotations, but a rotation has been set. rotationVal="
+ rotationVal);
}
if (valueVal != Constants.UNDEFINED)
{
if (valueEdge != null)
valueEdge.setChunk(trialState, site, valueVal);
else if (valueVal != 0)
throw new UnsupportedOperationException(
"This game does not support piece values, but a value has been set. valueVal=" + valueVal);
}
final boolean isEmpty = !isOccupied(site);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
{
addToEmptyCell(site);
}
else
{
removeFromEmptyCell(site);
}
}
//-------------------------------------------------------------------------
@Override
public int whoCell(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public int whatCell(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public int stateCell(final int site)
{
return 0;
}
@Override
public int rotationCell(final int site)
{
return 0;
}
@Override
public int valueCell(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public int countCell(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public int remove(final State trialState, final int site, final SiteType type)
{
final int whatIdx = what(site, type);
setSite(trialState, site, 0, 0, 0, 0, 0, 0, type);
return whatIdx;
}
@Override
public int remove(final State trialState, final int site, final int level, final SiteType type)
{
return remove(trialState, site, type);
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((hiddenEdge == null) ? 0 : hiddenEdge.hashCode());
result = prime * result + ((hiddenWhatEdge == null) ? 0 : hiddenWhatEdge.hashCode());
result = prime * result + ((hiddenWhoEdge == null) ? 0 : hiddenWhoEdge.hashCode());
result = prime * result + ((hiddenStateEdge == null) ? 0 : hiddenStateEdge.hashCode());
result = prime * result + ((hiddenRotationEdge == null) ? 0 : hiddenRotationEdge.hashCode());
result = prime * result + ((hiddenValueEdge == null) ? 0 : hiddenValueEdge.hashCode());
result = prime * result + ((hiddenStateEdge == null) ? 0 : hiddenStateEdge.hashCode());
result = prime * result + ((whoEdge == null) ? 0 : whoEdge.hashCode());
result = prime * result + ((countEdge == null) ? 0 : countEdge.hashCode());
result = prime * result + ((whatEdge == null) ? 0 : whatEdge.hashCode());
result = prime * result + ((stateEdge == null) ? 0 : stateEdge.hashCode());
result = prime * result + ((rotationEdge == null) ? 0 : rotationEdge.hashCode());
result = prime * result + ((valueEdge == null) ? 0 : valueEdge.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (!(obj instanceof ContainerFlatEdgeState))
return false;
if (!super.equals(obj))
return false;
final ContainerFlatEdgeState other = (ContainerFlatEdgeState) obj;
if (hiddenEdge != null)
{
for (int i = 1; i < hiddenEdge.length; i++)
if (!bitSetsEqual(hiddenEdge[i], other.hiddenEdge[i]))
return false;
}
if (hiddenWhatEdge != null)
{
for (int i = 1; i < hiddenWhatEdge.length; i++)
if (!bitSetsEqual(hiddenWhatEdge[i], other.hiddenWhatEdge[i]))
return false;
}
if (hiddenWhoEdge != null)
{
for (int i = 1; i < hiddenWhoEdge.length; i++)
if (!bitSetsEqual(hiddenWhoEdge[i], other.hiddenWhoEdge[i]))
return false;
}
if (hiddenRotationEdge != null)
{
for (int i = 1; i < hiddenRotationEdge.length; i++)
if (!bitSetsEqual(hiddenRotationEdge[i], other.hiddenRotationEdge[i]))
return false;
}
if (hiddenStateEdge != null)
{
for (int i = 1; i < hiddenStateEdge.length; i++)
if (!bitSetsEqual(hiddenStateEdge[i], other.hiddenStateEdge[i]))
return false;
}
if (hiddenValueEdge != null)
{
for (int i = 1; i < hiddenValueEdge.length; i++)
if (!bitSetsEqual(hiddenValueEdge[i], other.hiddenValueEdge[i]))
return false;
}
if (hiddenValueEdge != null)
{
for (int i = 1; i < hiddenValueEdge.length; i++)
if (!bitSetsEqual(hiddenValueEdge[i], other.hiddenValueEdge[i]))
return false;
}
if (hiddenCountEdge != null)
{
for (int i = 1; i < hiddenCountEdge.length; i++)
if (!bitSetsEqual(hiddenCountEdge[i], other.hiddenCountEdge[i]))
return false;
}
if (!chunkSetsEqual(whoEdge, other.whoEdge))
return false;
if (!chunkSetsEqual(countEdge, other.countEdge))
return false;
if (!chunkSetsEqual(whatEdge, other.whatEdge))
return false;
if (!chunkSetsEqual(stateEdge, other.stateEdge))
return false;
if (!chunkSetsEqual(rotationEdge, other.rotationEdge))
return false;
if (!chunkSetsEqual(valueEdge, other.valueEdge))
return false;
return true;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("ContainerState type = " + this.getClass() + "\n");
if (emptyChunkSetEdge() != null)
sb.append("Empty = " + emptyChunkSetEdge().toChunkString() + "\n");
if (whoEdge != null)
sb.append("Who = " + cloneWhoEdge().toChunkString() + "\n");
if (whatEdge != null)
sb.append("What" + cloneWhatEdge().toChunkString() + "\n");
if (stateEdge != null)
sb.append("State = " + stateEdge.internalStateCopy().toChunkString() + "\n");
if (rotationEdge != null)
sb.append("Rotation = " + rotationEdge.internalStateCopy().toChunkString() + "\n");
if (valueEdge != null)
sb.append("value = " + valueEdge.internalStateCopy().toChunkString() + "\n");
if (countEdge != null)
sb.append("Count = " + countEdge.internalStateCopy().toChunkString() + "\n");
if (hiddenEdge != null)
{
for (int i = 1; i < hiddenEdge.length; i++)
sb.append(
"Hidden for " + " player " + i + " = " + hiddenEdge[i].internalStateCopy().toString() + "\n");
}
if (hiddenWhatEdge != null)
{
for (int i = 1; i < hiddenWhatEdge.length; i++)
sb.append("Hidden What for " + " player " + i + " = "
+ hiddenWhatEdge[i].internalStateCopy().toString() + "\n");
}
if (hiddenWhoEdge != null)
{
for (int i = 1; i < hiddenWhoEdge.length; i++)
sb.append("Hidden Who for " + " player " + i + " = " + hiddenWhoEdge[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenCountEdge != null)
{
for (int i = 1; i < hiddenCountEdge.length; i++)
sb.append("Hidden Count for " + " player " + i + " = "
+ hiddenCountEdge[i].internalStateCopy().toString() + "\n");
}
if (hiddenValueEdge != null)
{
for (int i = 1; i < hiddenValueEdge.length; i++)
sb.append("Hidden Value for " + " player " + i + " = "
+ hiddenValueEdge[i].internalStateCopy().toString() + "\n");
}
if (hiddenStateEdge != null)
{
for (int i = 1; i < hiddenStateEdge.length; i++)
sb.append("Hidden State for " + " player " + i + " = "
+ hiddenStateEdge[i].internalStateCopy().toString() + "\n");
}
if (hiddenRotationEdge != null)
{
for (int i = 1; i < hiddenRotationEdge.length; i++)
sb.append("Hidden Rotation for " + " player " + i + " = "
+ hiddenRotationEdge[i].internalStateCopy().toString() + "\n");
}
return sb.toString();
}
private static final boolean chunkSetsEqual(final HashedChunkSet thisSet, final HashedChunkSet otherSet)
{
if (thisSet == null)
return otherSet == null;
return thisSet.equals(otherSet);
}
private static final boolean bitSetsEqual(final HashedBitSet thisSet, final HashedBitSet otherSet)
{
if (thisSet == null)
return otherSet == null;
return thisSet.equals(otherSet);
}
//-------------------------------------------------------------------------
/**
* @param site
* @return Size of stack.
*/
@Override
public int sizeStackCell(final int site)
{
if (whatCell(site) != 0)
return 1;
return 0;
}
/**
* @param site
* @return Size of stack edge.
*/
@Override
public int sizeStackEdge(final int site)
{
if (whatEdge(site) != 0)
return 1;
return 0;
}
/**
* @param site
* @return Size of stack vertex.
*/
@Override
public int sizeStackVertex(final int site)
{
if (whatVertex(site) != 0)
return 1;
return 0;
}
@Override
public int whoEdge(final int edge)
{
return whoEdge.getChunk(edge);
}
@Override
public int whoVertex(final int vertex)
{
return 0;
}
@Override
public int whatEdge(int site)
{
return whatEdge.getChunk(site);
}
@Override
public int countEdge(int site)
{
if (countEdge != null)
return countEdge.getChunk(site);
if (whoEdge.getChunk(site) != 0 || whatEdge != null && whatEdge.getChunk(site) != 0)
return 1;
return 0;
}
@Override
public int stateEdge(int site)
{
if (stateEdge == null)
return 0;
return stateEdge.getChunk(site);
}
@Override
public int rotationEdge(int site)
{
if (rotationEdge == null)
return 0;
return rotationEdge.getChunk(site);
}
@Override
public int whatVertex(int site)
{
return 0;
}
@Override
public int countVertex(int site)
{
return 0;
}
@Override
public int stateVertex(int site)
{
return 0;
}
@Override
public int rotationVertex(int site)
{
return 0;
}
@Override
public void setValueCell(final State trialState, final int site, final int valueVal)
{
// do nothing
}
@Override
public void setCount(final State trialState, final int site, final int countVal)
{
// do nothing
}
@Override
public void addItem(State trialState, int site, int whatItem, int whoItem, Game game)
{
// do nothing
}
@Override
public void insert(State trialState, SiteType type, int site, int level, int whatItem, int whoItem, final int state,
final int rotation, final int value, Game game)
{
// do nothing
}
@Override
public void insertCell(State trialState, int site, int level, int whatItem, int whoItem, final int state,
final int rotation, final int value, Game game)
{
// do nothing
}
@Override
public void addItem(State trialState, int site, int whatItem, int whoItem, int stateVal, int rotationVal,
int valueval, Game game)
{
// do nothing
}
@Override
public void addItem(State trialState, int site, int whatItem, int whoItem, Game game, boolean[] hiddenItem,
final boolean masked)
{
// do nothing
}
@Override
public void removeStack(State trialState, int site)
{
// do nothing
}
@Override
public int whoCell(int site, int level)
{
return whoCell(site);
}
@Override
public int whatCell(int site, int level)
{
return whatCell(site);
}
@Override
public int stateCell(int site, int level)
{
return stateCell(site);
}
@Override
public int rotationCell(int site, int level)
{
return rotationCell(site);
}
@Override
public int remove(State trialState, int site, int level)
{
return remove(trialState, site, SiteType.Edge);
}
@Override
public void setSite(State trialState, int site, int level, int whoVal, int whatVal, int countVal, int stateVal,
int rotationVal, int valueVal)
{
setSite(trialState, site, whoVal, whatVal, countVal, stateVal, rotationVal, valueVal, SiteType.Edge);
}
@Override
public int whoVertex(int site, int level)
{
return 0;
}
@Override
public int whatVertex(int site, int level)
{
return 0;
}
@Override
public int stateVertex(int site, int level)
{
return 0;
}
@Override
public int rotationVertex(int site, int level)
{
return 0;
}
@Override
public int whoEdge(int site, int level)
{
return whoEdge(site);
}
@Override
public int whatEdge(int site, int level)
{
return whatEdge(site);
}
@Override
public int stateEdge(int site, int level)
{
return stateEdge(site);
}
@Override
public int rotationEdge(int site, int level)
{
return rotationEdge(site);
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing to do.
}
@Override
public void insertVertex(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// Nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal, Game game)
{
// Nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing to do.
}
@Override
public void removeStackVertex(State trialState, int site)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing to do.
}
@Override
public void insertEdge(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal, Game game)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing to do.
}
@Override
public void removeStackEdge(State trialState, int site)
{
// Nothing to do.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game,
SiteType graphElementType)
{
// Do nothing.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal, Game game, SiteType graphElementType)
{
// Do nothing.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked, SiteType graphElementType)
{
// Do nothing.
}
@Override
public void removeStackGeneric(State trialState, int site, SiteType graphElementType)
{
// Do nothing.
}
@Override
public Sites emptySites()
{
return new Sites(emptyEdge.sites());
}
@Override
public int numEmpty()
{
return emptyEdge.count();
}
@Override
public void addToEmpty(final int site, final SiteType graphType)
{
emptyEdge.add(site);
}
@Override
public void removeFromEmpty(final int site, final SiteType graphType)
{
emptyEdge.remove(site);
}
@Override
public boolean isEmptyVertex(final int vertex)
{
return true;
}
@Override
public boolean isEmptyEdge(final int edge)
{
return emptyEdge.contains(edge);
}
@Override
public boolean isEmptyCell(final int site)
{
return true;
}
@Override
public Region emptyRegion(final SiteType type)
{
return emptyEdge;
}
@Override
public void addToEmptyCell(final int site)
{
emptyEdge.add(site);
}
@Override
public void removeFromEmptyCell(final int site)
{
emptyEdge.remove(site);
}
//-------------------------------------------------------------------------
/**
* @param preferred
* @return Given HashChunkSet, or who as a replacement if the argument is null
*/
protected final HashedChunkSet defaultIfNull(final HashedChunkSet preferred)
{
if (preferred != null)
return preferred;
return whoEdge;
}
@Override
public ChunkSet emptyChunkSetCell()
{
return null;
}
@Override
public ChunkSet emptyChunkSetVertex()
{
return null;
}
@Override
public ChunkSet emptyChunkSetEdge()
{
return emptyEdge.bitSet();
}
@Override
public int numChunksWhoCell()
{
return Constants.UNDEFINED;
}
@Override
public int numChunksWhoVertex()
{
return Constants.UNDEFINED;
}
@Override
public int numChunksWhoEdge()
{
return whoEdge.numChunks();
}
@Override
public int chunkSizeWhoCell()
{
return Constants.UNDEFINED;
}
@Override
public int chunkSizeWhoVertex()
{
return Constants.UNDEFINED;
}
@Override
public int chunkSizeWhoEdge()
{
return whoEdge.chunkSize();
}
@Override
public int numChunksWhatCell()
{
return Constants.UNDEFINED;
}
@Override
public int numChunksWhatVertex()
{
return Constants.UNDEFINED;
}
@Override
public int numChunksWhatEdge()
{
return defaultIfNull(whatEdge).numChunks();
}
@Override
public int chunkSizeWhatCell()
{
return Constants.UNDEFINED;
}
@Override
public int chunkSizeWhatVertex()
{
return Constants.UNDEFINED;
}
@Override
public int chunkSizeWhatEdge()
{
return defaultIfNull(whatEdge).chunkSize();
}
@Override
public boolean matchesWhoCell(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean matchesWhoVertex(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean matchesWhoEdge(final ChunkSet mask, final ChunkSet pattern)
{
return whoEdge.matches(mask, pattern);
}
@Override
public boolean violatesNotWhoCell(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern)
{
return whoEdge.violatesNot(mask, pattern);
}
@Override
public boolean violatesNotWhoCell(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return false;
}
@Override
public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return false;
}
@Override
public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return whoEdge.violatesNot(mask, pattern, startWord);
}
@Override
public boolean matchesWhatCell(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean matchesWhatVertex(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean matchesWhatEdge(final ChunkSet mask, final ChunkSet pattern)
{
return defaultIfNull(whatEdge).matches(mask, pattern);
}
@Override
public boolean matchesWhoEdge(final int wordIdx, final long mask, final long matchingWord)
{
return whoEdge.matches(wordIdx, mask, matchingWord);
}
@Override public boolean matchesWhoVertex(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override public boolean matchesWhoCell(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override
public boolean matchesWhatEdge(final int wordIdx, final long mask, final long matchingWord)
{
return defaultIfNull(whatEdge).matches(wordIdx, mask, matchingWord);
}
@Override public boolean matchesWhatVertex(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override public boolean matchesWhatCell(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override
public boolean violatesNotWhatCell(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern)
{
return defaultIfNull(whatEdge).violatesNot(mask, pattern);
}
@Override
public boolean violatesNotWhatCell(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return false;
}
@Override
public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return false;
}
@Override
public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return defaultIfNull(whatEdge).violatesNot(mask, pattern, startWord);
}
@Override
public ChunkSet cloneWhoCell()
{
return null;
}
@Override
public ChunkSet cloneWhoVertex()
{
return null;
}
@Override
public ChunkSet cloneWhoEdge()
{
return whoEdge.internalStateCopy();
}
@Override
public ChunkSet cloneWhatCell()
{
return null;
}
@Override
public ChunkSet cloneWhatVertex()
{
return null;
}
@Override
public ChunkSet cloneWhatEdge()
{
return defaultIfNull(whatEdge).internalStateCopy();
}
@Override
public int valueCell(int site, int level)
{
return valueCell(site);
}
@Override
public int valueVertex(int site)
{
return 0;
}
@Override
public int valueVertex(int site, int level)
{
return 0;
}
@Override
public int valueEdge(int site)
{
if (valueEdge == null)
return 0;
return valueEdge(site);
}
@Override
public int valueEdge(int site, int level)
{
if (valueEdge == null)
return 0;
return valueEdge(site);
}
//-------------------------------------------------------------------------
// Optimised versions of methods with graph element types; we only support
// Edge anyway, so just assume we were passed Edge as type
@Override
public int what(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return whatEdge(site);
}
@Override
public int who(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return whoEdge(site);
}
@Override
public int count(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return countEdge(site);
}
@Override
public int sizeStack(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return sizeStackEdge(site);
}
@Override
public int state(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return stateEdge(site);
}
@Override
public int rotation(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return rotationEdge(site);
}
@Override
public int value(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return valueEdge(site);
}
//-------------------Methods with levels---------------------
@Override
public int what(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return whatEdge(site, level);
}
@Override
public int who(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return whoEdge(site, level);
}
@Override
public int state(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return stateEdge(site, level);
}
@Override
public int rotation(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return rotationEdge(site, level);
}
@Override
public int value(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Edge)
return 0;
return valueEdge(site, level);
}
//-------------------------------------------------------------------------
}
| 43,534 | 24.533724 | 122 | java |
Ludii | Ludii-master/Core/src/other/state/container/ContainerFlatState.java | package other.state.container;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.state.GameType;
import main.Constants;
import main.collections.ChunkSet;
import other.state.State;
import other.state.zhash.HashedBitSet;
import other.state.zhash.HashedChunkSet;
import other.state.zhash.ZobristHashGenerator;
import other.topology.Cell;
/**
* Global State for a container item.
*
* @author cambolbro and Eric.Piette and mrraow
*/
public class ContainerFlatState extends BaseContainerState
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Playable sites (for boardless games). */
protected final HashedBitSet playable;
/** Type of Item on the site. */
protected final HashedChunkSet who;
/** Type of Item on the site. */
protected final HashedChunkSet what;
/** Count of Item on the site. */
protected final HashedChunkSet count;
/** State of Item on the site. */
protected final HashedChunkSet state;
/** Rotation state of Item on the site. */
protected final HashedChunkSet rotation;
/** Value of the piece on a site. */
protected final HashedChunkSet value;
/** Which site has some hidden properties for each player. */
protected final HashedBitSet[] hidden;
/** Which site has the what information hidden for each player. */
protected final HashedBitSet[] hiddenWhat;
/** Which site has the who information hidden for each player. */
protected final HashedBitSet[] hiddenWho;
/** Which site has the count information hidden for each player. */
protected final HashedBitSet[] hiddenCount;
/** Which site has the state information hidden for each player. */
protected final HashedBitSet[] hiddenState;
/** Which site has the rotation information hidden for each player. */
protected final HashedBitSet[] hiddenRotation;
/** Which site has the value information hidden for each player. */
protected final HashedBitSet[] hiddenValue;
//-------------------------------------------------------------------------
/**
* Constructor of a flat container.
*
* @param generator
* @param game
* @param container
* @param numSites
* @param maxWhatVal
* @param maxStateVal
* @param maxCountVal
* @param maxRotationVal
* @param maxPieceValue
*/
public ContainerFlatState
(
final ZobristHashGenerator generator,
final Game game,
final Container container,
final int numSites,
final int maxWhatVal,
final int maxStateVal,
final int maxCountVal,
final int maxRotationVal,
final int maxPieceValue
)
{
super
(
game,
container,
numSites
);
final int numPlayers = game.players().count();
if ((game.gameFlags() & GameType.HiddenInfo) == 0L)
{
hidden = null;
hiddenWhat = null;
hiddenWho = null;
hiddenCount = null;
hiddenRotation = null;
hiddenValue = null;
hiddenState = null;
}
else
{
hidden = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hidden[i] = new HashedBitSet(generator, numSites);
hiddenWhat = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWhat[i] = new HashedBitSet(generator, numSites);
hiddenWho = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWho[i] = new HashedBitSet(generator, numSites);
hiddenCount = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenCount[i] = new HashedBitSet(generator, numSites);
hiddenState = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenState[i] = new HashedBitSet(generator, numSites);
hiddenRotation = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenRotation[i] = new HashedBitSet(generator, numSites);
hiddenValue = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenValue[i] = new HashedBitSet(generator, numSites);
}
if (!game.isBoardless())
playable = null;
else
playable = new HashedBitSet(generator, numSites);
who = new HashedChunkSet(generator, numPlayers + 1, numSites);
what = maxWhatVal > 0 ? new HashedChunkSet(generator, maxWhatVal, numSites) : null;
count = maxCountVal > 0 ? new HashedChunkSet(generator, maxCountVal, numSites) : null;
state = maxStateVal > 0 ? new HashedChunkSet(generator, maxStateVal, numSites) : null;
rotation = maxRotationVal > 0 ? new HashedChunkSet(generator, maxRotationVal, numSites) : null;
value = maxPieceValue > 0 ? new HashedChunkSet(generator, maxPieceValue, numSites) : null;
}
/**
* Copy constructor.
*
* @param other
*/
public ContainerFlatState(final ContainerFlatState other)
{
super(other);
who = (other.who == null) ? null : other.who.clone();
if (other.hidden != null)
{
hidden = new HashedBitSet[other.hidden.length];
for (int i = 1; i < other.hidden.length; i++)
hidden[i] = (other.hidden[i] == null) ? null : other.hidden[i].clone();
hiddenWhat = new HashedBitSet[other.hiddenWhat.length];
for (int i = 1; i < other.hiddenWhat.length; i++)
hiddenWhat[i] = (other.hiddenWhat[i] == null) ? null : other.hiddenWhat[i].clone();
hiddenWho = new HashedBitSet[other.hiddenWho.length];
for (int i = 1; i < other.hiddenWho.length; i++)
hiddenWho[i] = (other.hiddenWho[i] == null) ? null : other.hiddenWho[i].clone();
hiddenCount = new HashedBitSet[other.hiddenCount.length];
for (int i = 1; i < other.hiddenCount.length; i++)
hiddenCount[i] = (other.hiddenCount[i] == null) ? null : other.hiddenCount[i].clone();
hiddenState = new HashedBitSet[other.hiddenState.length];
for (int i = 1; i < other.hiddenState.length; i++)
hiddenState[i] = (other.hiddenState[i] == null) ? null : other.hiddenState[i].clone();
hiddenRotation = new HashedBitSet[other.hiddenRotation.length];
for (int i = 1; i < other.hiddenRotation.length; i++)
hiddenRotation[i] = (other.hiddenRotation[i] == null) ? null : other.hiddenRotation[i].clone();
hiddenValue = new HashedBitSet[other.hiddenValue.length];
for (int i = 1; i < other.hiddenValue.length; i++)
hiddenValue[i] = (other.hiddenValue[i] == null) ? null : other.hiddenValue[i].clone();
}
else
{
hidden = null;
hiddenWhat = null;
hiddenWho = null;
hiddenCount = null;
hiddenRotation = null;
hiddenValue = null;
hiddenState = null;
}
playable = (other.playable == null) ? null : other.playable.clone();
what = (other.what == null) ? null : other.what.clone();
count = (other.count == null) ? null : other.count.clone();
state = (other.state == null) ? null : other.state.clone();
rotation = (other.rotation == null) ? null : other.rotation.clone();
value = (other.value == null) ? null : other.value.clone();
}
@Override
public ContainerFlatState deepClone()
{
return new ContainerFlatState(this);
}
//-------------------------------------------------------------------------
@Override
protected long calcCanonicalHash(final int[] siteRemap, final int[] edgeRemap, final int[] vertexRemap, final int[] playerRemap, final boolean whoOnly)
{
long hash = 0;
// Key fact: who owns the piece
if (who != null) hash ^= who.calculateHashAfterRemap(siteRemap, playerRemap);
if (!whoOnly)
{
if (what != null) hash ^= what.calculateHashAfterRemap(siteRemap, null);
if (playable != null) hash ^= playable.calculateHashAfterRemap(siteRemap, false);
if (count != null) hash ^= count.calculateHashAfterRemap(siteRemap, null);
if (state != null) hash ^= state.calculateHashAfterRemap(siteRemap, null);
if (rotation != null) hash ^= rotation.calculateHashAfterRemap(siteRemap, null);
if (value != null) hash ^= value.calculateHashAfterRemap(siteRemap, null);
if (hidden != null)
{
for (int i = 1; i < hidden.length; i++)
hash ^= hidden[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhat != null)
{
for (int i = 1; i < hiddenWhat.length; i++)
hash ^= hiddenWhat[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWho != null)
{
for (int i = 1; i < hiddenWho.length; i++)
hash ^= hiddenWho[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenCount != null)
{
for (int i = 1; i < hiddenCount.length; i++)
hash ^= hiddenCount[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenRotation != null)
{
for (int i = 1; i < hiddenRotation.length; i++)
hash ^= hiddenRotation[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenValue != null)
{
for (int i = 1; i < hiddenValue.length; i++)
hash ^= hiddenValue[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenState != null)
{
for (int i = 1; i < hiddenState.length; i++)
hash ^= hiddenState[i].calculateHashAfterRemap(siteRemap, false);
}
}
return hash;
}
//-------------------------------------------------------------------------
/**
* Reset this state.
*/
@Override
public void reset(final State trialState, final Game game)
{
super.reset(trialState, game);
if (who != null)
who.clear(trialState);
if (what != null) what.clear(trialState);
if (count != null)
count.clear(trialState);
if (state != null) state.clear(trialState);
if (rotation != null)
rotation.clear(trialState);
if (value != null)
value.clear(trialState);
if (hidden != null)
for (int i = 1; i < hidden.length; i++)
hidden[i].clear(trialState);
if (hiddenWhat != null)
for (int i = 1; i < hiddenWhat.length; i++)
hiddenWhat[i].clear(trialState);
if (hiddenWho != null)
for (int i = 1; i < hiddenWho.length; i++)
hiddenWho[i].clear(trialState);
if (hiddenCount != null)
for (int i = 1; i < hiddenCount.length; i++)
hiddenCount[i].clear(trialState);
if (hiddenRotation != null)
for (int i = 1; i < hiddenRotation.length; i++)
hiddenRotation[i].clear(trialState);
if (hiddenValue != null)
for (int i = 1; i < hiddenValue.length; i++)
hiddenValue[i].clear(trialState);
if (hiddenState != null)
for (int i = 1; i < hiddenState.length; i++)
hiddenState[i].clear(trialState);
}
//-------------------------------------------------------------------------
@Override
public boolean isHidden(final int player, final int site, final int level, final SiteType type)
{
if (hidden == null)
return false;
if(player < 1 || player > (hidden.length-1))
throw new UnsupportedOperationException("A wrong player is set in calling the method (hidden ...) in the containerState. Player = " + player);
return this.hidden[player].get(site - offset);
}
@Override
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType type)
{
if (hiddenWhat == null)
return false;
if(player < 1 || player > (hiddenWhat.length-1))
throw new UnsupportedOperationException("A wrong player is set in calling the method (hiddenWhat ...) in the containerState. Player = " + player);
return this.hiddenWhat[player].get(site - offset);
}
@Override
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType type)
{
if (hiddenWho == null)
return false;
if(player < 1 || player > (hiddenWho.length-1))
throw new UnsupportedOperationException("A wrong player is set in calling the method (hiddenWho ...) in the containerState. Player = " + player);
return this.hiddenWho[player].get(site - offset);
}
@Override
public boolean isHiddenState(final int player, final int site, final int level, final SiteType type)
{
if (hiddenState == null)
return false;
if(player < 1 || player > (hiddenState.length-1))
throw new UnsupportedOperationException("A wrong player is set in calling the method (hiddenState ...) in the containerState. Player = " + player);
return this.hiddenState[player].get(site - offset);
}
@Override
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType type)
{
if (hiddenRotation == null)
return false;
if(player < 1 || player > (hiddenRotation.length-1))
throw new UnsupportedOperationException("A wrong player is set in calling the method (hiddenRotation ...) in the containerState. Player = " + player);
return this.hiddenRotation[player].get(site - offset);
}
@Override
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType type)
{
if (hiddenValue == null)
return false;
if(player < 1 || player > (hiddenValue.length-1))
throw new UnsupportedOperationException("A wrong player is set in calling the method (hiddenValue ...) in the containerState. Player = " + player);
return this.hiddenValue[player].get(site - offset);
}
@Override
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType type)
{
if (hiddenCount == null)
return false;
if(player < 1 || player > (hiddenCount.length-1))
throw new UnsupportedOperationException("A wrong player is set in calling the method (hiddenCount ...) in the containerState. Player = " + player);
return this.hiddenCount[player].get(site - offset);
}
@Override
public void setHidden(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (hidden == null)
throw new UnsupportedOperationException("No Hidden information, but the method (setHidden ...) was called");
if(player < 1 || player > (hidden.length-1))
throw new UnsupportedOperationException("A wrong player is set in calling the method (setHidden ...) in the containerState. Player = " + player);
this.hidden[player].set(state, site - offset, on);
}
@Override
public void setHiddenWhat(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (hiddenWhat == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWhat ...) was called");
if (player < 1 || player > (hiddenWhat.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWhat ...) in the containerState. Player = "
+ player);
this.hiddenWhat[player].set(state, site - offset, on);
}
@Override
public void setHiddenWho(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (hiddenWho == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWho ...) was called");
if (player < 1 || player > (hiddenWho.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWho ...) in the containerState. Player = "
+ player);
this.hiddenWho[player].set(state, site - offset, on);
}
@Override
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenState == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenState ...) was called");
if (player < 1 || player > (hiddenState.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenState ...) in the containerState. Player = "
+ player);
this.hiddenState[player].set(state, site - offset, on);
}
@Override
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenRotation == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenRotation ...) was called");
if (player < 1 || player > (hiddenRotation.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenRotation ...) in the containerState. Player = "
+ player);
this.hiddenRotation[player].set(state, site - offset, on);
}
@Override
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenValue == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenValue ...) was called");
if (player < 1 || player > (hiddenValue.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenValue ...) in the containerState. Player = "
+ player);
this.hiddenValue[player].set(state, site - offset, on);
}
@Override
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenCount == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenCount ...) was called");
if (player < 1 || player > (hiddenCount.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenCount ...) in the containerState. Player = "
+ player);
this.hiddenCount[player].set(state, site - offset, on);
}
//-------------------------------------------------------------------------
@Override
public boolean isPlayable(final int site)
{
if (playable == null)
return true;
return playable.get(site - offset);
}
@Override
public void setPlayable(final State trialState, final int site, final boolean on)
{
if (playable != null)
playable.set(trialState, site, on);
}
//-------------------------------------------------------------------------
@Override
public boolean isOccupied(final int site)
{
return countCell(site) != 0;
}
//-------------------------------------------------------------------------
@Override
public void setSite
(
final State trialState, final int site, final int whoVal, final int whatVal,
final int countVal, final int stateVal, final int rotationVal, final int valueVal, final SiteType type
)
{
final boolean wasEmpty = !isOccupied(site);
if (whoVal != Constants.UNDEFINED)
who.setChunk(trialState, site - offset, whoVal);
if (whatVal != Constants.UNDEFINED)
defaultIfNull(what).setChunk(trialState, site - offset, whatVal);
if (countVal != Constants.UNDEFINED)
{
if (count != null)
count.setChunk(trialState, site - offset, (countVal < 0 ? 0 : countVal));
else if (count == null && countVal > 1)
throw new UnsupportedOperationException("This game does not support counts, but a count > 1 has been set. countVal="+countVal);
}
if (stateVal != Constants.UNDEFINED)
{
if (state != null)
state.setChunk(trialState, site - offset, stateVal);
else if (stateVal != 0)
throw new UnsupportedOperationException("This game does not support states, but a state has been set. stateVal="+stateVal);
}
if (rotationVal != Constants.UNDEFINED)
{
if (rotation != null)
rotation.setChunk(trialState, site - offset, rotationVal);
else if (rotationVal != 0)
throw new UnsupportedOperationException(
"This game does not support rotations, but a rotation has been set. rotationVal="
+ rotationVal);
}
if (valueVal != Constants.UNDEFINED)
{
if (value != null)
value.setChunk(trialState, site - offset, valueVal);
else if (valueVal != 0)
throw new UnsupportedOperationException(
"This game does not support piece values, but a value has been set. valueVal="
+ valueVal);
}
final boolean isEmpty = !isOccupied(site);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
{
addToEmptyCell(site);
if (playable != null && valueVal == Constants.OFF)
{
checkPlayable(trialState, site);
final Cell v = container().topology().cells().get(site - offset);
for (final Cell vNbors : v.adjacent())
checkPlayable(trialState, vNbors.index());
}
}
else
{
removeFromEmptyCell(site);
if (playable != null && valueVal == Constants.OFF)
{
setPlayable(trialState, site - offset, false);
final Cell v = container().topology().cells().get(site - offset);
for (final Cell vNbors : v.adjacent())
if (!isOccupied(vNbors.index()))
setPlayable(trialState, vNbors.index(), true);
}
}
if (playable != null && whatVal == 0 && !wasEmpty)
{
final Cell cell = container().topology().cells().get(site - offset);
final List<Cell> cells = new ArrayList<Cell>();
cells.add(cell);
cells.addAll(cell.adjacent());
for (final Cell cellToCheck : cells)
if (!isOccupied(cellToCheck.index()))
{
boolean findOccupiedNbor = false;
for (final Cell cellNbors : cellToCheck.adjacent())
if (isOccupied(cellNbors.index()))
{
findOccupiedNbor = true;
break;
}
setPlayable(trialState, cellToCheck.index(), findOccupiedNbor);
}
}
}
/**
* To check the playable site in case of modification for boardless.
*
* @param trialState
* @param site
*/
private void checkPlayable(final State trialState, final int site)
{
if (isOccupied(site))
{
setPlayable(trialState, site - offset, false);
return;
}
final Cell v = container().topology().cells().get(site - offset);
for (final Cell vNbors : v.adjacent())
if (isOccupied(vNbors.index()))
{
setPlayable(trialState, site - offset, true);
return;
}
setPlayable(trialState, site - offset, false);
}
//-------------------------------------------------------------------------
@Override
public int whoCell(final int site)
{
return who.getChunk(site - offset);
}
//-------------------------------------------------------------------------
@Override
public int whatCell(final int site)
{
if (what == null)
return whoCell(site);
return what.getChunk(site - offset);
}
//-------------------------------------------------------------------------
@Override
public int stateCell(final int site)
{
if (state == null)
return 0;
return state.getChunk(site - offset);
}
@Override
public int rotationCell(final int site)
{
if (rotation == null)
return 0;
return rotation.getChunk(site - offset);
}
@Override
public int valueCell(final int site)
{
if (value == null)
return 0;
return value.getChunk(site - offset);
}
//-------------------------------------------------------------------------
@Override
public int countCell(final int site)
{
if (count != null)
return count.getChunk(site - offset);
if (who.getChunk(site - offset) != 0 || what != null && what.getChunk(site - offset) != 0)
return 1;
return 0;
}
//-------------------------------------------------------------------------
@Override
public int remove(final State trialState, final int site, final SiteType type)
{
final int whatIdx = what(site, type);
setSite(trialState, site, 0, 0, 0, 0, 0, 0, type);
return whatIdx;
}
@Override
public int remove(final State trialState, final int site, final int level, final SiteType type)
{
return remove(trialState, site, type);
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((hidden == null) ? 0 : hidden.hashCode());
result = prime * result + ((hiddenWhat == null) ? 0 : hiddenWhat.hashCode());
result = prime * result + ((hiddenWho == null) ? 0 : hiddenWho.hashCode());
result = prime * result + ((hiddenState == null) ? 0 : hiddenState.hashCode());
result = prime * result + ((hiddenRotation == null) ? 0 : hiddenRotation.hashCode());
result = prime * result + ((hiddenValue == null) ? 0 : hiddenValue.hashCode());
result = prime * result + ((hiddenState == null) ? 0 : hiddenState.hashCode());
result = prime * result + ((who == null) ? 0 : who.hashCode());
result = prime * result + ((playable == null) ? 0 : playable.hashCode());
result = prime * result + ((count == null) ? 0 : count.hashCode());
result = prime * result + ((what == null) ? 0 : what.hashCode());
result = prime * result + ((state == null) ? 0 : state.hashCode());
result = prime * result + ((rotation == null) ? 0 : rotation.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (!(obj instanceof ContainerFlatState))
return false;
if (!super.equals(obj))
return false;
final ContainerFlatState other = (ContainerFlatState) obj;
if (hidden != null)
{
for (int i = 1; i < hidden.length; i++)
if (!bitSetsEqual(hidden[i], other.hidden[i]))
return false;
}
if (hiddenWhat != null)
{
for (int i = 1; i < hiddenWhat.length; i++)
if (!bitSetsEqual(hiddenWhat[i], other.hiddenWhat[i]))
return false;
}
if (hiddenWho != null)
{
for (int i = 1; i < hiddenWho.length; i++)
if (!bitSetsEqual(hiddenWho[i], other.hiddenWho[i]))
return false;
}
if (hiddenRotation != null)
{
for (int i = 1; i < hiddenRotation.length; i++)
if (!bitSetsEqual(hiddenRotation[i], other.hiddenRotation[i]))
return false;
}
if (hiddenState != null)
{
for (int i = 1; i < hiddenState.length; i++)
if (!bitSetsEqual(hiddenState[i], other.hiddenState[i]))
return false;
}
if (hiddenValue != null)
{
for (int i = 1; i < hiddenValue.length; i++)
if (!bitSetsEqual(hiddenValue[i], other.hiddenValue[i]))
return false;
}
if (hiddenValue != null)
{
for (int i = 1; i < hiddenValue.length; i++)
if (!bitSetsEqual(hiddenValue[i], other.hiddenValue[i]))
return false;
}
if (hiddenCount != null)
{
for (int i = 1; i < hiddenCount.length; i++)
if (!bitSetsEqual(hiddenCount[i], other.hiddenCount[i]))
return false;
}
if (!chunkSetsEqual(who, other.who)) return false;
if (!bitSetsEqual(playable, other.playable)) return false;
if (!chunkSetsEqual(count, other.count)) return false;
if (!chunkSetsEqual(what, other.what)) return false;
if (!chunkSetsEqual(state, other.state)) return false;
if (!chunkSetsEqual(rotation, other.rotation)) return false;
if (!chunkSetsEqual(value, other.value)) return false;
return true;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("ContainerState type = " + this.getClass() + "\n");
if (emptyChunkSetCell() != null)
sb.append("Empty = " + emptyChunkSetCell().toChunkString() + "\n");
if (who != null)
sb.append("Who = " + cloneWhoCell().toChunkString() + "\n");
if (what != null)
sb.append("What" + cloneWhatCell().toChunkString() + "\n");
if (state != null)
sb.append("State = " + state.internalStateCopy().toChunkString() + "\n");
if (rotation != null)
sb.append("Rotation = " + rotation.internalStateCopy().toChunkString() + "\n");
if (value != null)
sb.append("value = " + value.internalStateCopy().toChunkString() + "\n");
if (count != null)
sb.append("Count = " + count.internalStateCopy().toChunkString() + "\n");
if (playable != null)
sb.append("Playable = " + playable.internalStateCopy().toString() + "\n");
if (hidden != null)
{
for (int i = 1; i < hidden.length; i++)
sb.append(
"Hidden for " + " player " + i + " = " + hidden[i].internalStateCopy().toString() + "\n");
}
if (hiddenWhat != null)
{
for (int i = 1; i < hiddenWhat.length; i++)
sb.append("Hidden What for " + " player " + i + " = " + hiddenWhat[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenWho != null)
{
for (int i = 1; i < hiddenWho.length; i++)
sb.append("Hidden Who for " + " player " + i + " = " + hiddenWho[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenCount != null)
{
for (int i = 1; i < hiddenCount.length; i++)
sb.append("Hidden Count for " + " player " + i + " = " + hiddenCount[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenValue != null)
{
for (int i = 1; i < hiddenValue.length; i++)
sb.append("Hidden Value for " + " player " + i + " = " + hiddenValue[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenState != null)
{
for (int i = 1; i < hiddenState.length; i++)
sb.append("Hidden State for " + " player " + i + " = " + hiddenState[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenRotation != null)
{
for (int i = 1; i < hiddenRotation.length; i++)
sb.append("Hidden Rotation for " + " player " + i + " = "
+ hiddenRotation[i].internalStateCopy().toString() + "\n");
}
return sb.toString();
}
private static final boolean chunkSetsEqual(final HashedChunkSet thisSet, final HashedChunkSet otherSet)
{
if (thisSet == null)
return otherSet == null;
return thisSet.equals(otherSet);
}
private static final boolean bitSetsEqual(final HashedBitSet thisSet, final HashedBitSet otherSet)
{
if (thisSet == null)
return otherSet == null;
return thisSet.equals(otherSet);
}
//-------------------------------------------------------------------------
/**
* @param site
* @return Size of stack.
*/
@Override
public int sizeStackCell(final int site)
{
if (!isEmptyCell(site))
return 1;
return 0;
}
/**
* @param site
* @return Size of stack edge.
*/
@Override
public int sizeStackEdge(final int site)
{
if (!isEmptyEdge(site))
return 1;
return 0;
}
/**
* @param site
* @return Size of stack vertex.
*/
@Override
public int sizeStackVertex(final int site)
{
if (!isEmptyVertex(site))
return 1;
return 0;
}
@Override
public int whoEdge(final int edge)
{
return 0;
}
@Override
public int whoVertex(final int vertex)
{
return 0;
}
@Override
public int whatEdge(int site)
{
return 0;
}
@Override
public int countEdge(int site)
{
return 0;
}
@Override
public int stateEdge(int site)
{
return 0;
}
@Override
public int rotationEdge(int site)
{
return 0;
}
@Override
public int whatVertex(int site)
{
return 0;
}
@Override
public int countVertex(int site)
{
return 0;
}
@Override
public int stateVertex(int site)
{
return 0;
}
@Override
public int rotationVertex(int site)
{
return 0;
}
@Override
public void setValueCell(final State trialState, final int site, final int valueVal)
{
if (valueVal != Constants.UNDEFINED)
{
if (value != null)
value.setChunk(trialState, site - offset, valueVal);
else if (valueVal != 0)
throw new UnsupportedOperationException(
"This game does not support piece values, but a value has been set. valueVal=" + valueVal);
}
}
@Override
public void setCount(final State trialState, final int site, final int countVal)
{
if (countVal != Constants.UNDEFINED)
{
if (count != null)
count.setChunk(trialState, site - offset, (countVal < 0 ? 0 : countVal));
else if (count == null && countVal > 1)
throw new UnsupportedOperationException(
"This game does not support counts, but a count > 1 has been set. countVal=" + countVal);
}
}
@Override
public void addItem(State trialState, int site, int whatItem, int whoItem, Game game)
{
// do nothing
}
@Override
public void insert(State trialState, SiteType type, int site, int level, int whatItem, int whoItem,
final int stateVal,
final int rotationVal, final int valueVal, Game game)
{
// do nothing
}
@Override
public void insertCell(State trialState, int site, int level, int whatItem, int whoItem, final int stateVal,
final int rotationVal, final int valueVal, Game game)
{
// do nothing
}
@Override
public void addItem(State trialState, int site, int whatItem, int whoItem, int stateVal, int rotationVal,
int valueval,
Game game)
{
// do nothing
}
@Override
public void addItem(State trialState, int site, int whatItem, int whoItem, Game game, boolean[] hiddenItem,
final boolean masked)
{
// do nothing
}
@Override
public void removeStack(State trialState, int site)
{
// do nothing
}
@Override
public int whoCell(int site, int level)
{
return whoCell(site);
}
@Override
public int whatCell(int site, int level)
{
return whatCell(site);
}
@Override
public int stateCell(int site, int level)
{
return stateCell(site);
}
@Override
public int rotationCell(int site, int level)
{
return rotationCell(site);
}
@Override
public int remove(State trialState, int site, int level)
{
return remove(trialState, site, SiteType.Cell);
}
@Override
public void setSite(State trialState, int site, int level, int whoVal, int whatVal, int countVal, int stateVal,
int rotationVal, int valueVal)
{
setSite(trialState, site, whoVal, whatVal, countVal, stateVal, rotationVal, valueVal, SiteType.Cell);
}
@Override
public int whoVertex(int site, int level)
{
return 0;
}
@Override
public int whatVertex(int site, int level)
{
return 0;
}
@Override
public int stateVertex(int site, int level)
{
return 0;
}
@Override
public int rotationVertex(int site, int level)
{
return 0;
}
@Override
public int whoEdge(int site, int level)
{
return 0;
}
@Override
public int whatEdge(int site, int level)
{
return 0;
}
@Override
public int stateEdge(int site, int level)
{
return 0;
}
@Override
public int rotationEdge(int site, int level)
{
return 0;
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing to do.
}
@Override
public void insertVertex(State trialState, int site, int level, int whatValue, int whoId, final int stateVal,
final int rotationVal, final int valueVal, Game game)
{
// Nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game)
{
// Nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing to do.
}
@Override
public void removeStackVertex(State trialState, int site)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing to do.
}
@Override
public void insertEdge(State trialState, int site, int level, int whatValue, int whoId, final int stateVal,
final int rotationVal, final int valueVal, Game game)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing to do.
}
@Override
public void removeStackEdge(State trialState, int site)
{
// Nothing to do.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game,
SiteType graphElementType)
{
// Do nothing.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game,
SiteType graphElementType)
{
// Do nothing.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked, SiteType graphElementType)
{
// Do nothing.
}
@Override
public void removeStackGeneric(State trialState, int site, SiteType graphElementType)
{
// Do nothing.
}
@Override
public void addToEmpty(final int site, final SiteType graphType)
{
addToEmptyCell(site);
}
@Override
public void removeFromEmpty(final int site, final SiteType graphType)
{
removeFromEmptyCell(site);
}
//-------------------------------------------------------------------------
/**
* @param preferred
* @return Given HashChunkSet, or who as a replacement if the argument is null
*/
protected final HashedChunkSet defaultIfNull(final HashedChunkSet preferred)
{
if (preferred != null)
return preferred;
return who;
}
@Override
public ChunkSet emptyChunkSetCell()
{
return empty.bitSet();
}
@Override public ChunkSet emptyChunkSetVertex() { return null; }
@Override public ChunkSet emptyChunkSetEdge() { return null; }
@Override
public int numChunksWhoCell()
{
return who.numChunks();
}
@Override public int numChunksWhoVertex() { return Constants.UNDEFINED; }
@Override public int numChunksWhoEdge() { return Constants.UNDEFINED; }
@Override
public int chunkSizeWhoCell()
{
return who.chunkSize();
}
@Override public int chunkSizeWhoVertex() { return Constants.UNDEFINED; }
@Override public int chunkSizeWhoEdge() { return Constants.UNDEFINED; }
@Override
public int numChunksWhatCell()
{
return defaultIfNull(what).numChunks();
}
@Override public int numChunksWhatVertex() { return Constants.UNDEFINED; }
@Override public int numChunksWhatEdge() { return Constants.UNDEFINED; }
@Override
public int chunkSizeWhatCell()
{
return defaultIfNull(what).chunkSize();
}
@Override public int chunkSizeWhatVertex() { return Constants.UNDEFINED; }
@Override public int chunkSizeWhatEdge() { return Constants.UNDEFINED; }
@Override
public boolean matchesWhoCell(final ChunkSet mask, final ChunkSet pattern)
{
return who.matches(mask, pattern);
}
@Override public boolean matchesWhoVertex(final ChunkSet mask, final ChunkSet pattern) { return false; }
@Override public boolean matchesWhoEdge(final ChunkSet mask, final ChunkSet pattern) { return false; }
@Override
public boolean matchesWhoCell(final int wordIdx, final long mask, final long matchingWord)
{
return who.matches(wordIdx, mask, matchingWord);
}
@Override public boolean matchesWhoVertex(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override public boolean matchesWhoEdge(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override
public boolean matchesWhatCell(final int wordIdx, final long mask, final long matchingWord)
{
return defaultIfNull(what).matches(wordIdx, mask, matchingWord);
}
@Override public boolean matchesWhatVertex(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override public boolean matchesWhatEdge(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override
public boolean violatesNotWhoCell(final ChunkSet mask, final ChunkSet pattern)
{
return who.violatesNot(mask, pattern);
}
@Override public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern) { return false; }
@Override public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern) { return false; }
@Override
public boolean violatesNotWhoCell(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return who.violatesNot(mask, pattern, startWord);
}
@Override public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord) { return false; }
@Override public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord) { return false; }
@Override
public boolean matchesWhatCell(final ChunkSet mask, final ChunkSet pattern)
{
return defaultIfNull(what).matches(mask, pattern);
}
@Override public boolean matchesWhatVertex(final ChunkSet mask, final ChunkSet pattern) { return false; }
@Override public boolean matchesWhatEdge(final ChunkSet mask, final ChunkSet pattern) { return false; }
@Override public boolean violatesNotWhatCell(final ChunkSet mask, final ChunkSet pattern)
{
return defaultIfNull(what).violatesNot(mask, pattern);
}
@Override public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern) { return false; }
@Override public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern) { return false; }
@Override public boolean violatesNotWhatCell(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return defaultIfNull(what).violatesNot(mask, pattern, startWord);
}
@Override public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord) { return false; }
@Override public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord) { return false; }
@Override public ChunkSet cloneWhoCell()
{
return who.internalStateCopy();
}
@Override public ChunkSet cloneWhoVertex() { return null; }
@Override public ChunkSet cloneWhoEdge() { return null; }
@Override public ChunkSet cloneWhatCell()
{
return defaultIfNull(what).internalStateCopy();
}
@Override public ChunkSet cloneWhatVertex() { return null; }
@Override public ChunkSet cloneWhatEdge() { return null; }
@Override
public int valueCell(int site, int level)
{
return valueCell(site);
}
@Override
public int valueVertex(int site)
{
return 0;
}
@Override
public int valueVertex(int site, int level)
{
return valueVertex(site);
}
@Override
public int valueEdge(int site)
{
return 0;
}
@Override
public int valueEdge(int site, int level)
{
return valueEdge(site);
}
}
| 41,731 | 27.447171 | 154 | java |
Ludii | Ludii-master/Core/src/other/state/container/ContainerFlatVertexState.java | package other.state.container;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.equipment.Region;
import main.Constants;
import main.collections.ChunkSet;
import other.Sites;
import other.state.State;
import other.state.zhash.HashedBitSet;
import other.state.zhash.HashedChunkSet;
import other.state.zhash.ZobristHashGenerator;
/**
* Global State for a container item using only vertices.
*
* @author Eric.Piette
*/
public class ContainerFlatVertexState extends BaseContainerState
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Owner of a vertex. */
private final HashedChunkSet whoVertex;
/** Type of Item on a vertex. */
private final HashedChunkSet whatVertex;
/** Count of a vertex. */
private final HashedChunkSet countVertex;
/** State of a vertex. */
private final HashedChunkSet stateVertex;
/** Rotation of a vertex. */
private final HashedChunkSet rotationVertex;
/** Value of the piece on a vertex. */
private final HashedChunkSet valueVertex;
/** Which vertex has some hidden properties for each player. */
private final HashedBitSet[] hiddenVertex;
/** Which vertex has the what information hidden for each player. */
private final HashedBitSet[] hiddenWhatVertex;
/** Which vertex has the who information hidden for each player. */
private final HashedBitSet[] hiddenWhoVertex;
/** Which vertex has the count information hidden for each player. */
private final HashedBitSet[] hiddenCountVertex;
/** Which vertex has the state information hidden for each player. */
private final HashedBitSet[] hiddenStateVertex;
/** Which vertex has the rotation information hidden for each player. */
private final HashedBitSet[] hiddenRotationVertex;
/** Which vertex has the value information hidden for each player. */
private final HashedBitSet[] hiddenValueVertex;
/** Which vertex slots are empty. */ //Improvement: it's not great that we have this, but also still empty (for cells) from parent class...
private final Region emptyVertex;
//-------------------------------------------------------------------------
/**
* Constructor of a flat container.
*
* @param generator
* @param game
* @param container
* @param maxWhatVal
* @param maxStateVal
* @param maxCountVal
* @param maxRotationVal
* @param maxPieceValue
*/
public ContainerFlatVertexState
(
final ZobristHashGenerator generator,
final Game game,
final Container container,
final int maxWhatVal,
final int maxStateVal,
final int maxCountVal,
final int maxRotationVal,
final int maxPieceValue
)
{
super
(
game,
container,
container.numSites()
);
final int numPlayers = game.players().count();
final int numVertices = game.board().topology().vertices().size();
if ((game.gameFlags() & GameType.HiddenInfo) == 0L)
{
hiddenVertex = null;
hiddenWhatVertex = null;
hiddenWhoVertex = null;
hiddenCountVertex = null;
hiddenStateVertex = null;
hiddenRotationVertex = null;
hiddenValueVertex = null;
}
else
{
hiddenVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenVertex[i] = new HashedBitSet(generator, numVertices);
hiddenWhatVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWhatVertex[i] = new HashedBitSet(generator, numVertices);
hiddenWhoVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWhoVertex[i] = new HashedBitSet(generator, numVertices);
hiddenCountVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenCountVertex[i] = new HashedBitSet(generator, numVertices);
hiddenStateVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenStateVertex[i] = new HashedBitSet(generator, numVertices);
hiddenRotationVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenRotationVertex[i] = new HashedBitSet(generator, numVertices);
hiddenValueVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenValueVertex[i] = new HashedBitSet(generator, numVertices);
}
this.whoVertex = new HashedChunkSet(generator, numPlayers + 1, numVertices);
whatVertex = maxWhatVal > 0 ? new HashedChunkSet(generator, maxWhatVal, numVertices) : null;
countVertex = maxCountVal > 0 ? new HashedChunkSet(generator, maxCountVal, numVertices) : null;
stateVertex = maxStateVal > 0 ? new HashedChunkSet(generator, maxStateVal, numVertices) : null;
rotationVertex = maxRotationVal > 0 ? new HashedChunkSet(generator, maxRotationVal, numVertices) : null;
valueVertex = maxPieceValue > 0 ? new HashedChunkSet(generator, maxPieceValue, numVertices) : null;
this.emptyVertex = new Region(numVertices);
}
/**
* Copy constructor.
*
* @param other
*/
public ContainerFlatVertexState(final ContainerFlatVertexState other)
{
super(other);
if (other.hiddenVertex != null)
{
hiddenVertex = new HashedBitSet[other.hiddenVertex.length];
for (int i = 1; i < other.hiddenVertex.length; i++)
hiddenVertex[i] = (other.hiddenVertex[i] == null) ? null : other.hiddenVertex[i].clone();
hiddenWhatVertex = new HashedBitSet[other.hiddenWhatVertex.length];
for (int i = 1; i < other.hiddenWhatVertex.length; i++)
hiddenWhatVertex[i] = (other.hiddenWhatVertex[i] == null) ? null : other.hiddenWhatVertex[i].clone();
hiddenWhoVertex = new HashedBitSet[other.hiddenWhoVertex.length];
for (int i = 1; i < other.hiddenWhoVertex.length; i++)
hiddenWhoVertex[i] = (other.hiddenWhoVertex[i] == null) ? null : other.hiddenWhoVertex[i].clone();
hiddenCountVertex = new HashedBitSet[other.hiddenCountVertex.length];
for (int i = 1; i < other.hiddenCountVertex.length; i++)
hiddenCountVertex[i] = (other.hiddenCountVertex[i] == null) ? null : other.hiddenCountVertex[i].clone();
hiddenStateVertex = new HashedBitSet[other.hiddenStateVertex.length];
for (int i = 1; i < other.hiddenStateVertex.length; i++)
hiddenStateVertex[i] = (other.hiddenStateVertex[i] == null) ? null : other.hiddenStateVertex[i].clone();
hiddenRotationVertex = new HashedBitSet[other.hiddenRotationVertex.length];
for (int i = 1; i < other.hiddenRotationVertex.length; i++)
hiddenRotationVertex[i] = (other.hiddenRotationVertex[i] == null) ? null
: other.hiddenRotationVertex[i].clone();
hiddenValueVertex = new HashedBitSet[other.hiddenValueVertex.length];
for (int i = 1; i < other.hiddenValueVertex.length; i++)
hiddenValueVertex[i] = (other.hiddenValueVertex[i] == null) ? null : other.hiddenValueVertex[i].clone();
}
else
{
hiddenVertex = null;
hiddenWhatVertex = null;
hiddenWhoVertex = null;
hiddenCountVertex = null;
hiddenRotationVertex = null;
hiddenValueVertex = null;
hiddenStateVertex = null;
}
this.whoVertex = (other.whoVertex == null) ? null : other.whoVertex.clone();
this.whatVertex = (other.whatVertex == null) ? null : other.whatVertex.clone();
this.countVertex = (other.countVertex == null) ? null : other.countVertex.clone();
this.stateVertex = (other.stateVertex == null) ? null : other.stateVertex.clone();
this.rotationVertex = (other.rotationVertex == null) ? null : other.rotationVertex.clone();
this.valueVertex = (other.valueVertex == null) ? null : other.valueVertex.clone();
this.emptyVertex = (other.emptyVertex == null) ? null : new Region(other.emptyVertex);
}
@Override
public ContainerFlatVertexState deepClone()
{
return new ContainerFlatVertexState(this);
}
//-------------------------------------------------------------------------
@Override
protected long calcCanonicalHash(final int[] siteRemap, final int[] edgeRemap, final int[] vertexRemap,
final int[] playerRemap, final boolean whoOnly)
{
long hash = 0;
if (vertexRemap != null && vertexRemap.length > 0)
{
if (whoVertex != null)
hash ^= whoVertex.calculateHashAfterRemap(vertexRemap, playerRemap);
if (!whoOnly)
{
if (whatVertex != null)
hash ^= whatVertex.calculateHashAfterRemap(vertexRemap, null);
if (countVertex != null)
hash ^= countVertex.calculateHashAfterRemap(vertexRemap, null);
if (stateVertex != null)
hash ^= stateVertex.calculateHashAfterRemap(vertexRemap, null);
if (rotationVertex != null)
hash ^= rotationVertex.calculateHashAfterRemap(vertexRemap, null);
if (hiddenVertex != null)
{
for (int i = 1; i < hiddenVertex.length; i++)
hash ^= hiddenVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhatVertex != null)
{
for (int i = 1; i < hiddenWhatVertex.length; i++)
hash ^= hiddenWhatVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhoVertex != null)
{
for (int i = 1; i < hiddenWhoVertex.length; i++)
hash ^= hiddenWhoVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenCountVertex != null)
{
for (int i = 1; i < hiddenCountVertex.length; i++)
hash ^= hiddenCountVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenRotationVertex != null)
{
for (int i = 1; i < hiddenRotationVertex.length; i++)
hash ^= hiddenRotationVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenValueVertex != null)
{
for (int i = 1; i < hiddenValueVertex.length; i++)
hash ^= hiddenValueVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenStateVertex != null)
{
for (int i = 1; i < hiddenStateVertex.length; i++)
hash ^= hiddenStateVertex[i].calculateHashAfterRemap(siteRemap, false);
}
}
}
return hash;
}
//-------------------------------------------------------------------------
/**
* Reset this state.
*/
@Override
public void reset(final State trialState, final Game game)
{
super.reset(trialState, game);
final int numVertices = game.board().topology().vertices().size();
super.reset(trialState, game);
if (whoVertex != null)
whoVertex.clear(trialState);
if (whatVertex != null)
whatVertex.clear(trialState);
if (countVertex != null)
countVertex.clear(trialState);
if (stateVertex != null)
stateVertex.clear(trialState);
if (rotationVertex != null)
rotationVertex.clear(trialState);
if (valueVertex != null)
valueVertex.clear(trialState);
if (hiddenVertex != null)
for (int i = 1; i < hiddenVertex.length; i++)
hiddenVertex[i].clear(trialState);
if (hiddenWhatVertex != null)
for (int i = 1; i < hiddenWhatVertex.length; i++)
hiddenWhatVertex[i].clear(trialState);
if (hiddenWhoVertex != null)
for (int i = 1; i < hiddenWhoVertex.length; i++)
hiddenWhoVertex[i].clear(trialState);
if (hiddenCountVertex != null)
for (int i = 1; i < hiddenCountVertex.length; i++)
hiddenCountVertex[i].clear(trialState);
if (hiddenRotationVertex != null)
for (int i = 1; i < hiddenRotationVertex.length; i++)
hiddenRotationVertex[i].clear(trialState);
if (hiddenValueVertex != null)
for (int i = 1; i < hiddenValueVertex.length; i++)
hiddenValueVertex[i].clear(trialState);
if (hiddenStateVertex != null)
for (int i = 1; i < hiddenStateVertex.length; i++)
hiddenStateVertex[i].clear(trialState);
if (emptyVertex != null)
emptyVertex.set(numVertices);
}
//-------------------------------------------------------------------------
@Override
public boolean isHidden(final int player, final int site, final int level, final SiteType type)
{
if (hiddenVertex == null)
return false;
if (player < 1 || player > (hiddenVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenVertex ...) in the containerState. Player = "
+ player);
return this.hiddenVertex[player].get(site);
}
@Override
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType type)
{
if (hiddenWhatVertex == null)
return false;
if (player < 1 || player > (hiddenWhatVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenWhat ...) in the containerState. Player = "
+ player);
return this.hiddenWhatVertex[player].get(site);
}
@Override
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType type)
{
if (hiddenWhoVertex == null)
return false;
if (player < 1 || player > (hiddenWhoVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenWho ...) in the containerState. Player = "
+ player);
return this.hiddenWhoVertex[player].get(site);
}
@Override
public boolean isHiddenState(final int player, final int site, final int level, final SiteType type)
{
if (hiddenStateVertex == null)
return false;
if (player < 1 || player > (hiddenStateVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenState ...) in the containerState. Player = "
+ player);
return this.hiddenStateVertex[player].get(site);
}
@Override
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType type)
{
if (hiddenRotationVertex == null)
return false;
if (player < 1 || player > (hiddenRotationVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenRotation ...) in the containerState. Player = "
+ player);
return this.hiddenRotationVertex[player].get(site);
}
@Override
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType type)
{
if (hiddenValueVertex == null)
return false;
if (player < 1 || player > (hiddenValueVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenValue ...) in the containerState. Player = "
+ player);
return this.hiddenValueVertex[player].get(site);
}
@Override
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType type)
{
if (hiddenCountVertex == null)
return false;
if (player < 1 || player > (hiddenCountVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenCount ...) in the containerState. Player = "
+ player);
return this.hiddenCountVertex[player].get(site);
}
@Override
public void setHidden(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (hiddenVertex == null)
throw new UnsupportedOperationException("No Hidden information, but the method (setHidden ...) was called");
if (player < 1 || player > (hiddenVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHidden ...) in the containerState. Player = "
+ player);
this.hiddenVertex[player].set(state, site, on);
}
@Override
public void setHiddenWhat(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (hiddenWhatVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWhat ...) was called");
if (player < 1 || player > (hiddenWhatVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWhat ...) in the containerState. Player = "
+ player);
this.hiddenWhatVertex[player].set(state, site, on);
}
@Override
public void setHiddenWho(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (hiddenWhoVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWho ...) was called");
if (player < 1 || player > (hiddenWhoVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWho ...) in the containerState. Player = "
+ player);
this.hiddenWhoVertex[player].set(state, site, on);
}
@Override
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenStateVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenState ...) was called");
if (player < 1 || player > (hiddenStateVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenState ...) in the containerState. Player = "
+ player);
this.hiddenStateVertex[player].set(state, site, on);
}
@Override
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenRotationVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenRotation ...) was called");
if (player < 1 || player > (hiddenRotationVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenRotation ...) in the containerState. Player = "
+ player);
this.hiddenRotationVertex[player].set(state, site, on);
}
@Override
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenValueVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenValue ...) was called");
if (player < 1 || player > (hiddenValueVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenValue ...) in the containerState. Player = "
+ player);
this.hiddenValueVertex[player].set(state, site, on);
}
@Override
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (hiddenCountVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenCount ...) was called");
if (player < 1 || player > (hiddenCountVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenCount ...) in the containerState. Player = "
+ player);
this.hiddenCountVertex[player].set(state, site, on);
}
//-------------------------------------------------------------------------
@Override
public boolean isPlayable(final int site)
{
return true;
}
@Override
public void setPlayable(final State trialState, final int site, final boolean on)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public boolean isOccupied(final int site)
{
return countVertex(site) != 0;
}
//-------------------------------------------------------------------------
@Override
public void setSite(final State trialState, final int site, final int whoVal, final int whatVal, final int countVal,
final int stateVal, final int rotationVal, final int valueVal, final SiteType type)
{
final boolean wasEmpty = !isOccupied(site);
if (whoVal != Constants.UNDEFINED)
whoVertex.setChunk(trialState, site, whoVal);
if (whatVal != Constants.UNDEFINED)
defaultIfNull(whatVertex).setChunk(trialState, site, whatVal);
if (countVal != Constants.UNDEFINED)
{
if (countVertex != null)
countVertex.setChunk(trialState, site, (countVal < 0 ? 0 : countVal));
else if (countVertex == null && countVal > 1)
throw new UnsupportedOperationException(
"This game does not support counts, but a count > 1 has been set. countVal=" + countVal);
}
if (stateVal != Constants.UNDEFINED)
{
if (stateVertex != null)
stateVertex.setChunk(trialState, site, stateVal);
else if (stateVal != 0)
throw new UnsupportedOperationException(
"This game does not support states, but a state has been set. stateVal=" + stateVal);
}
if (rotationVal != Constants.UNDEFINED)
{
if (rotationVertex != null)
rotationVertex.setChunk(trialState, site, rotationVal);
else if (rotationVal != 0)
throw new UnsupportedOperationException(
"This game does not support rotations, but a rotation has been set. rotationVal="
+ rotationVal);
}
if (valueVal != Constants.UNDEFINED)
{
if (valueVertex != null)
valueVertex.setChunk(trialState, site, valueVal);
else if (valueVal != 0)
throw new UnsupportedOperationException(
"This game does not support piece values, but a value has been set. valueVal=" + valueVal);
}
final boolean isEmpty = !isOccupied(site);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
{
addToEmptyCell(site);
}
else
{
removeFromEmptyCell(site);
}
}
//-------------------------------------------------------------------------
@Override
public int whoCell(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public int whatCell(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public int stateCell(final int site)
{
return 0;
}
@Override
public int rotationCell(final int site)
{
return 0;
}
@Override
public int valueCell(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public int countCell(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public int remove(final State trialState, final int site, final SiteType type)
{
final int whatIdx = what(site, type);
setSite(trialState, site, 0, 0, 0, 0, 0, 0, type);
return whatIdx;
}
@Override
public int remove(final State trialState, final int site, final int level, final SiteType type)
{
return remove(trialState, site, type);
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((hiddenVertex == null) ? 0 : hiddenVertex.hashCode());
result = prime * result + ((hiddenWhatVertex == null) ? 0 : hiddenWhatVertex.hashCode());
result = prime * result + ((hiddenWhoVertex == null) ? 0 : hiddenWhoVertex.hashCode());
result = prime * result + ((hiddenStateVertex == null) ? 0 : hiddenStateVertex.hashCode());
result = prime * result + ((hiddenRotationVertex == null) ? 0 : hiddenRotationVertex.hashCode());
result = prime * result + ((hiddenValueVertex == null) ? 0 : hiddenValueVertex.hashCode());
result = prime * result + ((hiddenStateVertex == null) ? 0 : hiddenStateVertex.hashCode());
result = prime * result + ((whoVertex == null) ? 0 : whoVertex.hashCode());
result = prime * result + ((countVertex == null) ? 0 : countVertex.hashCode());
result = prime * result + ((whatVertex == null) ? 0 : whatVertex.hashCode());
result = prime * result + ((stateVertex == null) ? 0 : stateVertex.hashCode());
result = prime * result + ((rotationVertex == null) ? 0 : rotationVertex.hashCode());
result = prime * result + ((valueVertex == null) ? 0 : valueVertex.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (!(obj instanceof ContainerFlatVertexState))
return false;
if (!super.equals(obj))
return false;
final ContainerFlatVertexState other = (ContainerFlatVertexState) obj;
if (hiddenVertex != null)
{
for (int i = 1; i < hiddenVertex.length; i++)
if (!bitSetsEqual(hiddenVertex[i], other.hiddenVertex[i]))
return false;
}
if (hiddenWhatVertex != null)
{
for (int i = 1; i < hiddenWhatVertex.length; i++)
if (!bitSetsEqual(hiddenWhatVertex[i], other.hiddenWhatVertex[i]))
return false;
}
if (hiddenWhoVertex != null)
{
for (int i = 1; i < hiddenWhoVertex.length; i++)
if (!bitSetsEqual(hiddenWhoVertex[i], other.hiddenWhoVertex[i]))
return false;
}
if (hiddenRotationVertex != null)
{
for (int i = 1; i < hiddenRotationVertex.length; i++)
if (!bitSetsEqual(hiddenRotationVertex[i], other.hiddenRotationVertex[i]))
return false;
}
if (hiddenStateVertex != null)
{
for (int i = 1; i < hiddenStateVertex.length; i++)
if (!bitSetsEqual(hiddenStateVertex[i], other.hiddenStateVertex[i]))
return false;
}
if (hiddenValueVertex != null)
{
for (int i = 1; i < hiddenValueVertex.length; i++)
if (!bitSetsEqual(hiddenValueVertex[i], other.hiddenValueVertex[i]))
return false;
}
if (hiddenValueVertex != null)
{
for (int i = 1; i < hiddenValueVertex.length; i++)
if (!bitSetsEqual(hiddenValueVertex[i], other.hiddenValueVertex[i]))
return false;
}
if (hiddenCountVertex != null)
{
for (int i = 1; i < hiddenCountVertex.length; i++)
if (!bitSetsEqual(hiddenCountVertex[i], other.hiddenCountVertex[i]))
return false;
}
if (!chunkSetsEqual(whoVertex, other.whoVertex))
return false;
if (!chunkSetsEqual(countVertex, other.countVertex))
return false;
if (!chunkSetsEqual(whatVertex, other.whatVertex))
return false;
if (!chunkSetsEqual(stateVertex, other.stateVertex))
return false;
if (!chunkSetsEqual(rotationVertex, other.rotationVertex))
return false;
if (!chunkSetsEqual(valueVertex, other.valueVertex))
return false;
return true;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("ContainerState type = " + this.getClass() + "\n");
if (emptyChunkSetVertex() != null)
sb.append("Empty = " + emptyChunkSetVertex().toChunkString() + "\n");
if (whoVertex != null)
sb.append("Who = " + cloneWhoVertex().toChunkString() + "\n");
if (whatVertex != null)
sb.append("What" + cloneWhatVertex().toChunkString() + "\n");
if (stateVertex != null)
sb.append("State = " + stateVertex.internalStateCopy().toChunkString() + "\n");
if (rotationVertex != null)
sb.append("Rotation = " + rotationVertex.internalStateCopy().toChunkString() + "\n");
if (valueVertex != null)
sb.append("value = " + valueVertex.internalStateCopy().toChunkString() + "\n");
if (countVertex != null)
sb.append("Count = " + countVertex.internalStateCopy().toChunkString() + "\n");
if (hiddenVertex != null)
{
for (int i = 1; i < hiddenVertex.length; i++)
sb.append(
"Hidden for " + " player " + i + " = " + hiddenVertex[i].internalStateCopy().toString() + "\n");
}
if (hiddenWhatVertex != null)
{
for (int i = 1; i < hiddenWhatVertex.length; i++)
sb.append(
"Hidden What for " + " player " + i + " = " + hiddenWhatVertex[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenWhoVertex != null)
{
for (int i = 1; i < hiddenWhoVertex.length; i++)
sb.append("Hidden Who for " + " player " + i + " = " + hiddenWhoVertex[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenCountVertex != null)
{
for (int i = 1; i < hiddenCountVertex.length; i++)
sb.append("Hidden Count for " + " player " + i + " = "
+ hiddenCountVertex[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenValueVertex != null)
{
for (int i = 1; i < hiddenValueVertex.length; i++)
sb.append("Hidden Value for " + " player " + i + " = "
+ hiddenValueVertex[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenStateVertex != null)
{
for (int i = 1; i < hiddenStateVertex.length; i++)
sb.append("Hidden State for " + " player " + i + " = "
+ hiddenStateVertex[i].internalStateCopy().toString()
+ "\n");
}
if (hiddenRotationVertex != null)
{
for (int i = 1; i < hiddenRotationVertex.length; i++)
sb.append("Hidden Rotation for " + " player " + i + " = "
+ hiddenRotationVertex[i].internalStateCopy().toString() + "\n");
}
return sb.toString();
}
private static final boolean chunkSetsEqual(final HashedChunkSet thisSet, final HashedChunkSet otherSet)
{
if (thisSet == null)
return otherSet == null;
return thisSet.equals(otherSet);
}
private static final boolean bitSetsEqual(final HashedBitSet thisSet, final HashedBitSet otherSet)
{
if (thisSet == null)
return otherSet == null;
return thisSet.equals(otherSet);
}
//-------------------------------------------------------------------------
/**
* @param site
* @return Size of stack.
*/
@Override
public int sizeStackCell(final int site)
{
if (whatCell(site) != 0)
return 1;
return 0;
}
/**
* @param site
* @return Size of stack edge.
*/
@Override
public int sizeStackEdge(final int site)
{
if (whatEdge(site) != 0)
return 1;
return 0;
}
/**
* @param site
* @return Size of stack vertex.
*/
@Override
public int sizeStackVertex(final int site)
{
if (whatVertex(site) != 0)
return 1;
return 0;
}
@Override
public int whoEdge(final int edge)
{
return 0;
}
@Override
public int whoVertex(final int vertex)
{
return whoVertex.getChunk(vertex);
}
@Override
public int whatEdge(int site)
{
return 0;
}
@Override
public int countEdge(int site)
{
return 0;
}
@Override
public int stateEdge(int site)
{
return 0;
}
@Override
public int rotationEdge(int site)
{
return 0;
}
@Override
public int whatVertex(int site)
{
return whatVertex.getChunk(site);
}
@Override
public int countVertex(int site)
{
if (countVertex != null)
return countVertex.getChunk(site);
if (whoVertex.getChunk(site) != 0 || whatVertex != null && whatVertex.getChunk(site) != 0)
return 1;
return 0;
}
@Override
public int stateVertex(int site)
{
if (stateVertex == null)
return 0;
return stateVertex.getChunk(site);
}
@Override
public int rotationVertex(int site)
{
if (rotationVertex == null)
return 0;
return rotationVertex.getChunk(site);
}
@Override
public void setValueCell(final State trialState, final int site, final int valueVal)
{
// do nothing
}
@Override
public void setCount(final State trialState, final int site, final int countVal)
{
// do nothing
}
@Override
public void addItem(State trialState, int site, int whatItem, int whoItem, Game game)
{
// do nothing
}
@Override
public void insert(State trialState, SiteType type, int site, int level, int whatItem, int whoItem, final int state,
final int rotation, final int value, Game game)
{
// do nothing
}
@Override
public void insertCell(State trialState, int site, int level, int whatItem, int whoItem, final int state,
final int rotation, final int value, Game game)
{
// do nothing
}
@Override
public void addItem(State trialState, int site, int whatItem, int whoItem, int stateVal, int rotationVal,
int valueval, Game game)
{
// do nothing
}
@Override
public void addItem(State trialState, int site, int whatItem, int whoItem, Game game, boolean[] hiddenItem,
final boolean masked)
{
// do nothing
}
@Override
public void removeStack(State trialState, int site)
{
// do nothing
}
@Override
public int whoCell(int site, int level)
{
return whoCell(site);
}
@Override
public int whatCell(int site, int level)
{
return whatCell(site);
}
@Override
public int stateCell(int site, int level)
{
return stateCell(site);
}
@Override
public int rotationCell(int site, int level)
{
return rotationCell(site);
}
@Override
public int remove(State trialState, int site, int level)
{
return remove(trialState, site, SiteType.Vertex);
}
@Override
public void setSite(State trialState, int site, int level, int whoVal, int whatVal, int countVal, int stateVal,
int rotationVal, int valueVal)
{
setSite(trialState, site, whoVal, whatVal, countVal, stateVal, rotationVal, valueVal, SiteType.Vertex);
}
@Override
public int whoVertex(int site, int level)
{
return whoVertex(site);
}
@Override
public int whatVertex(int site, int level)
{
return whatVertex(site);
}
@Override
public int stateVertex(int site, int level)
{
return stateVertex(site);
}
@Override
public int rotationVertex(int site, int level)
{
return rotationVertex(site);
}
@Override
public int whoEdge(int site, int level)
{
return 0;
}
@Override
public int whatEdge(int site, int level)
{
return 0;
}
@Override
public int stateEdge(int site, int level)
{
return 0;
}
@Override
public int rotationEdge(int site, int level)
{
return 0;
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing to do.
}
@Override
public void insertVertex(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// Nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal, Game game)
{
// Nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing to do.
}
@Override
public void removeStackVertex(State trialState, int site)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing to do.
}
@Override
public void insertEdge(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal, Game game)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing to do.
}
@Override
public void removeStackEdge(State trialState, int site)
{
// Nothing to do.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game,
SiteType graphElementType)
{
// Do nothing.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal, Game game, SiteType graphElementType)
{
// Do nothing.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked, SiteType graphElementType)
{
// Do nothing.
}
@Override
public void removeStackGeneric(State trialState, int site, SiteType graphElementType)
{
// Do nothing.
}
@Override
public Sites emptySites()
{
return new Sites(emptyVertex.sites());
}
@Override
public int numEmpty()
{
return emptyVertex.count();
}
@Override
public void addToEmpty(final int site, final SiteType graphType)
{
emptyVertex.add(site);
}
@Override
public void removeFromEmpty(final int site, final SiteType graphType)
{
emptyVertex.remove(site);
}
@Override
public boolean isEmptyVertex(final int vertex)
{
return emptyVertex.contains(vertex);
}
@Override
public boolean isEmptyEdge(final int edge)
{
return true;
}
@Override
public boolean isEmptyCell(final int site)
{
return true;
}
@Override
public Region emptyRegion(final SiteType type)
{
return emptyVertex;
}
@Override
public void addToEmptyCell(final int site)
{
emptyVertex.add(site);
}
@Override
public void removeFromEmptyCell(final int site)
{
emptyVertex.remove(site);
}
//-------------------------------------------------------------------------
/**
* @param preferred
* @return Given HashChunkSet, or who as a replacement if the argument is null
*/
protected final HashedChunkSet defaultIfNull(final HashedChunkSet preferred)
{
if (preferred != null)
return preferred;
return whoVertex;
}
@Override
public ChunkSet emptyChunkSetCell()
{
return null;
}
@Override
public ChunkSet emptyChunkSetVertex()
{
return emptyVertex.bitSet();
}
@Override
public ChunkSet emptyChunkSetEdge()
{
return null;
}
@Override
public int numChunksWhoCell()
{
return Constants.UNDEFINED;
}
@Override
public int numChunksWhoVertex()
{
return whoVertex.numChunks();
}
@Override
public int numChunksWhoEdge()
{
return Constants.UNDEFINED;
}
@Override
public int chunkSizeWhoCell()
{
return Constants.UNDEFINED;
}
@Override
public int chunkSizeWhoVertex()
{
return whoVertex.chunkSize();
}
@Override
public int chunkSizeWhoEdge()
{
return Constants.UNDEFINED;
}
@Override
public int numChunksWhatCell()
{
return Constants.UNDEFINED;
}
@Override
public int numChunksWhatVertex()
{
return defaultIfNull(whatVertex).numChunks();
}
@Override
public int numChunksWhatEdge()
{
return Constants.UNDEFINED;
}
@Override
public int chunkSizeWhatCell()
{
return Constants.UNDEFINED;
}
@Override
public int chunkSizeWhatVertex()
{
return defaultIfNull(whatVertex).chunkSize();
}
@Override
public int chunkSizeWhatEdge()
{
return Constants.UNDEFINED;
}
@Override
public boolean matchesWhoCell(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean matchesWhoVertex(final ChunkSet mask, final ChunkSet pattern)
{
return whoVertex.matches(mask, pattern);
}
@Override
public boolean matchesWhoEdge(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhoCell(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern)
{
return whoVertex.violatesNot(mask, pattern);
}
@Override
public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhoCell(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return false;
}
@Override
public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return whoVertex.violatesNot(mask, pattern, startWord);
}
@Override
public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return false;
}
@Override
public boolean matchesWhatCell(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean matchesWhatVertex(final ChunkSet mask, final ChunkSet pattern)
{
return defaultIfNull(whatVertex).matches(mask, pattern);
}
@Override
public boolean matchesWhatEdge(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhatCell(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern)
{
return defaultIfNull(whatVertex).violatesNot(mask, pattern);
}
@Override
public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern)
{
return false;
}
@Override
public boolean violatesNotWhatCell(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return false;
}
@Override
public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return defaultIfNull(whatVertex).violatesNot(mask, pattern, startWord);
}
@Override
public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return false;
}
@Override
public boolean matchesWhoVertex(final int wordIdx, final long mask, final long matchingWord)
{
return whoVertex.matches(wordIdx, mask, matchingWord);
}
@Override public boolean matchesWhoEdge(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override public boolean matchesWhoCell(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override
public boolean matchesWhatVertex(final int wordIdx, final long mask, final long matchingWord)
{
return defaultIfNull(whatVertex).matches(wordIdx, mask, matchingWord);
}
@Override public boolean matchesWhatEdge(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override public boolean matchesWhatCell(final int wordIdx, final long mask, final long matchingWord) { return false; }
@Override
public ChunkSet cloneWhoCell()
{
return null;
}
@Override
public ChunkSet cloneWhoVertex()
{
return whoVertex.internalStateCopy();
}
@Override
public ChunkSet cloneWhoEdge()
{
return null;
}
@Override
public ChunkSet cloneWhatCell()
{
return null;
}
@Override
public ChunkSet cloneWhatVertex()
{
return defaultIfNull(whatVertex).internalStateCopy();
}
@Override
public ChunkSet cloneWhatEdge()
{
return null;
}
@Override
public int valueCell(int site, int level)
{
return valueCell(site);
}
@Override
public int valueVertex(int site)
{
if (valueVertex == null)
return 0;
return valueVertex.getChunk(site);
}
@Override
public int valueVertex(int site, int level)
{
if (valueVertex == null)
return 0;
return valueVertex(site);
}
@Override
public int valueEdge(int site)
{
return 0;
}
@Override
public int valueEdge(int site, int level)
{
return valueEdge(site);
}
//-------------------------------------------------------------------------
// Optimised versions of methods with graph element types; we only support
// Vertex anyway, so just assume we were passed Vertex as type
@Override
public int what(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return whatVertex(site);
}
@Override
public int who(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return whoVertex(site);
}
@Override
public int count(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return countVertex(site);
}
@Override
public int sizeStack(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return sizeStackVertex(site);
}
@Override
public int state(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return stateVertex(site);
}
@Override
public int rotation(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return rotationVertex(site);
}
@Override
public int value(final int site, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return valueVertex(site);
}
//-------------------Methods with levels---------------------
@Override
public int what(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return whatVertex(site, level);
}
@Override
public int who(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return whoVertex(site, level);
}
@Override
public int state(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return stateVertex(site, level);
}
@Override
public int rotation(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return rotationVertex(site, level);
}
@Override
public int value(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType != SiteType.Vertex)
return 0;
return valueVertex(site, level);
}
//-------------------------------------------------------------------------
}
| 44,619 | 25.108836 | 141 | java |
Ludii | Ludii-master/Core/src/other/state/container/ContainerGraphState.java | package other.state.container;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.equipment.Region;
import main.Constants;
import main.collections.ChunkSet;
import other.state.State;
import other.state.zhash.HashedBitSet;
import other.state.zhash.HashedChunkSet;
import other.state.zhash.ZobristHashGenerator;
/**
* The state of a container corresponding to a graph.
*
* @author Eric.Piette
*/
public class ContainerGraphState extends ContainerFlatState
{
private static final long serialVersionUID = 1L;
//-----------------------------------------------------------------------------
/** Owner of an edge. */
private final HashedChunkSet whoEdge;
/** Owner of a vertex. */
private final HashedChunkSet whoVertex;
/** Type of Item on an edge. */
private final HashedChunkSet whatEdge;
/** Type of Item on a vertex. */
private final HashedChunkSet whatVertex;
/** Count on an edge. */
private final HashedChunkSet countEdge;
/** Count of a vertex. */
private final HashedChunkSet countVertex;
/** State of an edge. */
private final HashedChunkSet stateEdge;
/** State of a vertex. */
private final HashedChunkSet stateVertex;
/** Rotation of a edge. */
private final HashedChunkSet rotationEdge;
/** Rotation of a vertex. */
private final HashedChunkSet rotationVertex;
/** Value of the piece on a vertex. */
private final HashedChunkSet valueVertex;
/** Value of the piece on a edge. */
private final HashedChunkSet valueEdge;
/** Which vertex has some hidden properties for each player. */
private final HashedBitSet[] hiddenVertex;
/** Which vertex has the what information hidden for each player. */
private final HashedBitSet[] hiddenWhatVertex;
/** Which vertex has the who information hidden for each player. */
private final HashedBitSet[] hiddenWhoVertex;
/** Which vertex has the count information hidden for each player. */
private final HashedBitSet[] hiddenCountVertex;
/** Which vertex has the state information hidden for each player. */
private final HashedBitSet[] hiddenStateVertex;
/** Which vertex has the rotation information hidden for each player. */
private final HashedBitSet[] hiddenRotationVertex;
/** Which vertex has the value information hidden for each player. */
private final HashedBitSet[] hiddenValueVertex;
/** Which edge has some hidden properties for each player. */
private final HashedBitSet[] hiddenEdge;
/** Which edge has the what information hidden for each player. */
private final HashedBitSet[] hiddenWhatEdge;
/** Which edge has the who information hidden for each player. */
private final HashedBitSet[] hiddenWhoEdge;
/** Which edge has the count information hidden for each player. */
private final HashedBitSet[] hiddenCountEdge;
/** Which edge has the state information hidden for each player. */
private final HashedBitSet[] hiddenStateEdge;
/** Which edge has the rotation information hidden for each player. */
private final HashedBitSet[] hiddenRotationEdge;
/** Which edge has the value information hidden for each player. */
private final HashedBitSet[] hiddenValueEdge;
/** Which edge slots are empty. */
private final Region emptyEdge;
/** Which vertex slots are empty. */
private final Region emptyVertex;
/**
* @param generator The generator.
* @param game The game.
* @param container The container.
* @param maxWhatVal The max what value.
* @param maxStateVal The max state value.
* @param maxCountVal The max count value.
* @param maxRotationVal The max rotation value.
* @param maxPieceValue The max piece value.
*/
public ContainerGraphState
(
final ZobristHashGenerator generator,
final Game game,
final Container container,
final int maxWhatVal,
final int maxStateVal,
final int maxCountVal,
final int maxRotationVal,
final int maxPieceValue
)
{
super(generator, game, container, container.numSites(), maxWhatVal, maxStateVal, maxCountVal, maxRotationVal,
maxPieceValue);
final int numEdges = game.board().topology().edges().size();
final int numVertices = game.board().topology().vertices().size();
final int numPlayers = game.players().count();
if ((game.gameFlags() & GameType.HiddenInfo) == 0L)
{
hiddenEdge = null;
hiddenWhatEdge = null;
hiddenWhoEdge = null;
hiddenRotationEdge = null;
hiddenCountEdge = null;
hiddenValueEdge = null;
hiddenStateEdge = null;
hiddenVertex = null;
hiddenWhatVertex = null;
hiddenWhoVertex = null;
hiddenCountVertex = null;
hiddenStateVertex = null;
hiddenRotationVertex = null;
hiddenValueVertex = null;
}
else
{
hiddenVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenVertex[i] = new HashedBitSet(generator, numVertices);
hiddenWhatVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWhatVertex[i] = new HashedBitSet(generator, numVertices);
hiddenWhoVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWhoVertex[i] = new HashedBitSet(generator, numVertices);
hiddenCountVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenCountVertex[i] = new HashedBitSet(generator, numVertices);
hiddenStateVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenStateVertex[i] = new HashedBitSet(generator, numVertices);
hiddenRotationVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenRotationVertex[i] = new HashedBitSet(generator, numVertices);
hiddenValueVertex = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenValueVertex[i] = new HashedBitSet(generator, numVertices);
hiddenEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenEdge[i] = new HashedBitSet(generator, numEdges);
hiddenWhatEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWhatEdge[i] = new HashedBitSet(generator, numEdges);
hiddenWhoEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenWhoEdge[i] = new HashedBitSet(generator, numEdges);
hiddenCountEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenCountEdge[i] = new HashedBitSet(generator, numEdges);
hiddenStateEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenStateEdge[i] = new HashedBitSet(generator, numEdges);
hiddenRotationEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenRotationEdge[i] = new HashedBitSet(generator, numEdges);
hiddenValueEdge = new HashedBitSet[numPlayers + 1];
for (int i = 1; i < (numPlayers + 1); i++)
hiddenValueEdge[i] = new HashedBitSet(generator, numEdges);
}
this.whoVertex = new HashedChunkSet(generator, numPlayers + 1, numVertices);
whatVertex = maxWhatVal > 0 ? new HashedChunkSet(generator, maxWhatVal, numVertices) : null;
countVertex = maxCountVal > 0 ? new HashedChunkSet(generator, maxCountVal, numVertices) : null;
stateVertex = maxStateVal > 0 ? new HashedChunkSet(generator, maxStateVal, numVertices) : null;
rotationVertex = maxRotationVal > 0 ? new HashedChunkSet(generator, maxRotationVal, numVertices) : null;
valueVertex = maxPieceValue > 0 ? new HashedChunkSet(generator, maxPieceValue, numVertices) : null;
this.emptyVertex = new Region(numVertices);
this.whoEdge = new HashedChunkSet(generator, numPlayers + 1, numEdges);
whatEdge = maxWhatVal > 0 ? new HashedChunkSet(generator, maxWhatVal, numEdges) : null;
rotationEdge = maxRotationVal > 0 ? new HashedChunkSet(generator, maxRotationVal, numEdges) : null;
countEdge = maxCountVal > 0 ? new HashedChunkSet(generator, maxCountVal, numEdges) : null;
stateEdge = maxStateVal > 0 ? new HashedChunkSet(generator, maxStateVal, numEdges) : null;
valueEdge = maxPieceValue > 0 ? new HashedChunkSet(generator, maxPieceValue, numEdges) : null;
this.emptyEdge = new Region(numEdges);
}
/**
* Copy constructor.
*
* @param other
*/
private ContainerGraphState(final ContainerGraphState other)
{
super(other);
if (other.hiddenEdge != null)
{
hiddenEdge = new HashedBitSet[other.hiddenEdge.length];
for (int i = 1; i < other.hiddenEdge.length; i++)
hiddenEdge[i] = (other.hiddenEdge[i] == null) ? null : other.hiddenEdge[i].clone();
hiddenWhatEdge = new HashedBitSet[other.hiddenWhatEdge.length];
for (int i = 1; i < other.hiddenWhatEdge.length; i++)
hiddenWhatEdge[i] = (other.hiddenWhatEdge[i] == null) ? null : other.hiddenWhatEdge[i].clone();
hiddenWhoEdge = new HashedBitSet[other.hiddenWhoEdge.length];
for (int i = 1; i < other.hiddenWhoEdge.length; i++)
hiddenWhoEdge[i] = (other.hiddenWhoEdge[i] == null) ? null : other.hiddenWhoEdge[i].clone();
hiddenCountEdge = new HashedBitSet[other.hiddenCountEdge.length];
for (int i = 1; i < other.hiddenCountEdge.length; i++)
hiddenCountEdge[i] = (other.hiddenCountEdge[i] == null) ? null : other.hiddenCountEdge[i].clone();
hiddenStateEdge = new HashedBitSet[other.hiddenStateEdge.length];
for (int i = 1; i < other.hiddenStateEdge.length; i++)
hiddenStateEdge[i] = (other.hiddenStateEdge[i] == null) ? null : other.hiddenStateEdge[i].clone();
hiddenRotationEdge = new HashedBitSet[other.hiddenRotationEdge.length];
for (int i = 1; i < other.hiddenRotationEdge.length; i++)
hiddenRotationEdge[i] = (other.hiddenRotationEdge[i] == null) ? null
: other.hiddenRotationEdge[i].clone();
hiddenValueEdge = new HashedBitSet[other.hiddenValueEdge.length];
for (int i = 1; i < other.hiddenValueEdge.length; i++)
hiddenValueEdge[i] = (other.hiddenValueEdge[i] == null) ? null : other.hiddenValueEdge[i].clone();
}
else
{
hiddenEdge = null;
hiddenWhatEdge = null;
hiddenWhoEdge = null;
hiddenCountEdge = null;
hiddenRotationEdge = null;
hiddenValueEdge = null;
hiddenStateEdge = null;
}
if (other.hiddenVertex != null)
{
hiddenVertex = new HashedBitSet[other.hiddenVertex.length];
for (int i = 1; i < other.hiddenVertex.length; i++)
hiddenVertex[i] = (other.hiddenVertex[i] == null) ? null : other.hiddenVertex[i].clone();
hiddenWhatVertex = new HashedBitSet[other.hiddenWhatVertex.length];
for (int i = 1; i < other.hiddenWhatVertex.length; i++)
hiddenWhatVertex[i] = (other.hiddenWhatVertex[i] == null) ? null : other.hiddenWhatVertex[i].clone();
hiddenWhoVertex = new HashedBitSet[other.hiddenWhoVertex.length];
for (int i = 1; i < other.hiddenWhoVertex.length; i++)
hiddenWhoVertex[i] = (other.hiddenWhoVertex[i] == null) ? null : other.hiddenWhoVertex[i].clone();
hiddenCountVertex = new HashedBitSet[other.hiddenCountVertex.length];
for (int i = 1; i < other.hiddenCountVertex.length; i++)
hiddenCountVertex[i] = (other.hiddenCountVertex[i] == null) ? null : other.hiddenCountVertex[i].clone();
hiddenStateVertex = new HashedBitSet[other.hiddenStateVertex.length];
for (int i = 1; i < other.hiddenStateVertex.length; i++)
hiddenStateVertex[i] = (other.hiddenStateVertex[i] == null) ? null : other.hiddenStateVertex[i].clone();
hiddenRotationVertex = new HashedBitSet[other.hiddenRotationVertex.length];
for (int i = 1; i < other.hiddenRotationVertex.length; i++)
hiddenRotationVertex[i] = (other.hiddenRotationVertex[i] == null) ? null
: other.hiddenRotationVertex[i].clone();
hiddenValueVertex = new HashedBitSet[other.hiddenValueVertex.length];
for (int i = 1; i < other.hiddenValueVertex.length; i++)
hiddenValueVertex[i] = (other.hiddenValueVertex[i] == null) ? null : other.hiddenValueVertex[i].clone();
}
else
{
hiddenVertex = null;
hiddenWhatVertex = null;
hiddenWhoVertex = null;
hiddenCountVertex = null;
hiddenRotationVertex = null;
hiddenValueVertex = null;
hiddenStateVertex = null;
}
this.whoEdge = (other.whoEdge == null) ? null : other.whoEdge.clone();
this.whoVertex = (other.whoVertex == null) ? null : other.whoVertex.clone();
this.whatEdge = (other.whatEdge == null) ? null : other.whatEdge.clone();
this.whatVertex = (other.whatVertex == null) ? null : other.whatVertex.clone();
this.countEdge = (other.countEdge == null) ? null : other.countEdge.clone();
this.countVertex = (other.countVertex == null) ? null : other.countVertex.clone();
this.stateEdge = (other.stateEdge == null) ? null : other.stateEdge.clone();
this.stateVertex = (other.stateVertex == null) ? null : other.stateVertex.clone();
this.rotationEdge = (other.rotationEdge == null) ? null : other.rotationEdge.clone();
this.rotationVertex = (other.rotationVertex == null) ? null : other.rotationVertex.clone();
this.valueVertex = (other.valueVertex == null) ? null : other.valueVertex.clone();
this.valueEdge = (other.valueEdge == null) ? null : other.valueEdge.clone();
this.emptyEdge = (other.emptyEdge == null) ? null : new Region(other.emptyEdge);
this.emptyVertex = (other.emptyVertex == null) ? null : new Region(other.emptyVertex);
}
@Override
public ContainerGraphState deepClone()
{
return new ContainerGraphState(this);
}
@Override
public void reset(final State trialState, final Game game)
{
final int numEdges = game.board().topology().edges().size();
final int numVertices = game.board().topology().vertices().size();
super.reset(trialState, game);
if (whoEdge != null)
whoEdge.clear(trialState);
if (whoVertex != null)
whoVertex.clear(trialState);
if (whatEdge != null)
whatEdge.clear(trialState);
if (whatVertex != null)
whatVertex.clear(trialState);
if (countEdge != null)
countEdge.clear(trialState);
if (countVertex != null)
countVertex.clear(trialState);
if (stateEdge != null)
stateEdge.clear(trialState);
if (stateVertex != null)
stateVertex.clear(trialState);
if (rotationEdge != null)
rotationEdge.clear(trialState);
if (rotationVertex != null)
rotationVertex.clear(trialState);
if (valueVertex != null)
valueVertex.clear(trialState);
if (valueEdge != null)
valueEdge.clear(trialState);
if (hiddenEdge != null)
for (int i = 1; i < hiddenEdge.length; i++)
hiddenEdge[i].clear(trialState);
if (hiddenWhatEdge != null)
for (int i = 1; i < hiddenWhatEdge.length; i++)
hiddenWhatEdge[i].clear(trialState);
if (hiddenWhoEdge != null)
for (int i = 1; i < hiddenWhoEdge.length; i++)
hiddenWhoEdge[i].clear(trialState);
if (hiddenCountEdge != null)
for (int i = 1; i < hiddenCountEdge.length; i++)
hiddenCountEdge[i].clear(trialState);
if (hiddenRotationEdge != null)
for (int i = 1; i < hiddenRotationEdge.length; i++)
hiddenRotationEdge[i].clear(trialState);
if (hiddenValueEdge != null)
for (int i = 1; i < hiddenValueEdge.length; i++)
hiddenValueEdge[i].clear(trialState);
if (hiddenStateEdge != null)
for (int i = 1; i < hiddenStateEdge.length; i++)
hiddenStateEdge[i].clear(trialState);
if (hiddenVertex != null)
for (int i = 1; i < hiddenVertex.length; i++)
hiddenVertex[i].clear(trialState);
if (hiddenWhatVertex != null)
for (int i = 1; i < hiddenWhatVertex.length; i++)
hiddenWhatVertex[i].clear(trialState);
if (hiddenWhoVertex != null)
for (int i = 1; i < hiddenWhoVertex.length; i++)
hiddenWhoVertex[i].clear(trialState);
if (hiddenCountVertex != null)
for (int i = 1; i < hiddenCountVertex.length; i++)
hiddenCountVertex[i].clear(trialState);
if (hiddenRotationVertex != null)
for (int i = 1; i < hiddenRotationVertex.length; i++)
hiddenRotationVertex[i].clear(trialState);
if (hiddenValueVertex != null)
for (int i = 1; i < hiddenValueVertex.length; i++)
hiddenValueVertex[i].clear(trialState);
if (hiddenStateVertex != null)
for (int i = 1; i < hiddenStateVertex.length; i++)
hiddenStateVertex[i].clear(trialState);
if (emptyEdge != null)
emptyEdge.set(numEdges);
if (emptyVertex != null)
emptyVertex.set(numVertices);
}
//-------------------------------------------------------------------------
@Override
public boolean isHidden(final int player, final int site, final int level, final SiteType type)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
return super.isHidden(player, site, level, type);
else if (type == SiteType.Edge)
{
if (hiddenEdge == null)
return false;
if (player < 1 || player > (hiddenEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hidden ...) in the containerState. Player = "
+ player);
return this.hiddenEdge[player].get(site - offset);
}
else
{
if (hiddenVertex == null)
return false;
if (player < 1 || player > (hiddenVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hidden ...) in the containerState. Player = "
+ player);
return this.hiddenVertex[player].get(site - offset);
}
}
@Override
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType type)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
return super.isHiddenWhat(player, site, level, type);
else if (type == SiteType.Edge)
{
if (hiddenWhatEdge == null)
return false;
if (player < 1 || player > (hiddenWhatEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenWhat ...) in the containerState. Player = "
+ player);
return this.hiddenWhatEdge[player].get(site - offset);
}
else
{
if (hiddenWhatVertex == null)
return false;
if (player < 1 || player > (hiddenWhatVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenWhat ...) in the containerState. Player = "
+ player);
return this.hiddenWhatVertex[player].get(site - offset);
}
}
@Override
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType type)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
return super.isHiddenWho(player, site, level, type);
else if (type == SiteType.Edge)
{
if (hiddenWhoEdge == null)
return false;
if (player < 1 || player > (hiddenWhoEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenWho ...) in the containerState. Player = "
+ player);
return this.hiddenWhoEdge[player].get(site - offset);
}
else
{
if (hiddenWhoVertex == null)
return false;
if (player < 1 || player > (hiddenWhoVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenWho ...) in the containerState. Player = "
+ player);
return this.hiddenWhoVertex[player].get(site - offset);
}
}
@Override
public boolean isHiddenState(final int player, final int site, final int level, final SiteType type)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
return super.isHiddenState(player, site, level, type);
else if (type == SiteType.Edge)
{
if (hiddenStateEdge == null)
return false;
if (player < 1 || player > (hiddenStateEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenState ...) in the containerState. Player = "
+ player);
return this.hiddenStateEdge[player].get(site - offset);
}
else
{
if (hiddenStateVertex == null)
return false;
if (player < 1 || player > (hiddenStateVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenState ...) in the containerState. Player = "
+ player);
return this.hiddenStateVertex[player].get(site - offset);
}
}
@Override
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType type)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
return super.isHiddenRotation(player, site, level, type);
else if (type == SiteType.Edge)
{
if (hiddenRotationEdge == null)
return false;
if (player < 1 || player > (hiddenRotationEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenRotation ...) in the containerState. Player = "
+ player);
return this.hiddenRotationEdge[player].get(site - offset);
}
else
{
if (hiddenRotationVertex == null)
return false;
if (player < 1 || player > (hiddenRotationVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenRotation ...) in the containerState. Player = "
+ player);
return this.hiddenRotationVertex[player].get(site - offset);
}
}
@Override
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType type)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
return super.isHiddenValue(player, site, level, type);
else if (type == SiteType.Edge)
{
if (hiddenValueEdge == null)
return false;
if (player < 1 || player > (hiddenValueEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenValue ...) in the containerState. Player = "
+ player);
return this.hiddenValueEdge[player].get(site - offset);
}
else
{
if (hiddenValueVertex == null)
return false;
if (player < 1 || player > (hiddenValueVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenValue ...) in the containerState. Player = "
+ player);
return this.hiddenValueVertex[player].get(site - offset);
}
}
@Override
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType type)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
return super.isHiddenCount(player, site, level, type);
else if (type == SiteType.Edge)
{
if (hiddenCountEdge == null)
return false;
if (player < 1 || player > (hiddenCountEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenCount ...) in the containerState. Player = "
+ player);
return this.hiddenCountEdge[player].get(site - offset);
}
else
{
if (hiddenCountVertex == null)
return false;
if (player < 1 || player > (hiddenCountVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (hiddenCount ...) in the containerState. Player = "
+ player);
return this.hiddenCountVertex[player].get(site - offset);
}
}
@Override
public void setHidden(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
super.setHidden(state, player, site, level, type, on);
else if (type == SiteType.Edge)
{
if (hiddenEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHidden ...) was called");
if (player < 1 || player > (hiddenEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHidden ...) in the containerState. Player = "
+ player);
this.hiddenEdge[player].set(state, site - offset, on);
}
else
{
if (hiddenVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHidden ...) was called");
if (player < 1 || player > (hiddenVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHidden ...) in the containerState. Player = "
+ player);
this.hiddenVertex[player].set(state, site - offset, on);
}
}
@Override
public void setHiddenWhat(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
super.setHiddenWhat(state, player, site, level, type, on);
else if (type == SiteType.Edge)
{
if (hiddenWhatEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWhat ...) was called");
if (player < 1 || player > (hiddenWhatEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWhat ...) in the containerState. Player = "
+ player);
this.hiddenWhatEdge[player].set(state, site - offset, on);
}
else
{
if (hiddenWhatVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWhat ...) was called");
if (player < 1 || player > (hiddenWhatVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWhat ...) in the containerState. Player = "
+ player);
this.hiddenWhatVertex[player].set(state, site - offset, on);
}
}
@Override
public void setHiddenWho(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
super.setHiddenWho(state, player, site, level, type, on);
else if (type == SiteType.Edge)
{
if (hiddenWhoEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWho ...) was called");
if (player < 1 || player > (hiddenWhoEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWho ...) in the containerState. Player = "
+ player);
this.hiddenWhoEdge[player].set(state, site - offset, on);
}
else
{
if (hiddenWhoVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenWho ...) was called");
if (player < 1 || player > (hiddenWhoVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenWho ...) in the containerState. Player = "
+ player);
this.hiddenWhoVertex[player].set(state, site - offset, on);
}
}
@Override
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
super.setHiddenState(state, player, site, level, type, on);
else if (type == SiteType.Edge)
{
if (hiddenStateEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenState ...) was called");
if (player < 1 || player > (hiddenStateEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenState ...) in the containerState. Player = "
+ player);
this.hiddenStateEdge[player].set(state, site - offset, on);
}
else
{
if (hiddenStateVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenState ...) was called");
if (player < 1 || player > (hiddenStateVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenState ...) in the containerState. Player = "
+ player);
this.hiddenStateVertex[player].set(state, site - offset, on);
}
}
@Override
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
super.setHiddenRotation(state, player, site, level, type, on);
else if (type == SiteType.Edge)
{
if (hiddenRotationEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenRotation ...) was called");
if (player < 1 || player > (hiddenRotationEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenRotation ...) in the containerState. Player = "
+ player);
this.hiddenRotationEdge[player].set(state, site - offset, on);
}
else
{
if (hiddenRotationVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenRotation ...) was called");
if (player < 1 || player > (hiddenRotationVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenRotation ...) in the containerState. Player = "
+ player);
this.hiddenRotationVertex[player].set(state, site - offset, on);
}
}
@Override
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
super.setHiddenValue(state, player, site, level, type, on);
else if (type == SiteType.Edge)
{
if (hiddenValueEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenValue ...) was called");
if (player < 1 || player > (hiddenValueEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenValue ...) in the containerState. Player = "
+ player);
this.hiddenValueEdge[player].set(state, site - offset, on);
}
else
{
if (hiddenValueVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenValue ...) was called");
if (player < 1 || player > (hiddenValueVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenValue ...) in the containerState. Player = "
+ player);
this.hiddenValueVertex[player].set(state, site - offset, on);
}
}
@Override
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
super.setHiddenCount(state, player, site, level, type, on);
else if (type == SiteType.Edge)
{
if (hiddenCountEdge == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenCount ...) was called");
if (player < 1 || player > (hiddenCountEdge.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenCount ...) in the containerState. Player = "
+ player);
this.hiddenCountEdge[player].set(state, site - offset, on);
}
else
{
if (hiddenCountVertex == null)
throw new UnsupportedOperationException(
"No Hidden information, but the method (setHiddenCount ...) was called");
if (player < 1 || player > (hiddenCountVertex.length - 1))
throw new UnsupportedOperationException(
"A wrong player is set in calling the method (setHiddenCount ...) in the containerState. Player = "
+ player);
this.hiddenCountVertex[player].set(state, site - offset, on);
}
}
@Override
protected long calcCanonicalHash(int[] siteRemap, int[] edgeRemap, int[] vertexRemap, int[] playerRemap, final boolean whoOnly)
{
long hash = 0;
if (siteRemap != null && siteRemap.length > 0)
{
if (who != null) hash ^= who.calculateHashAfterRemap(siteRemap, playerRemap);
if (!whoOnly)
{
if (what != null) hash ^= what.calculateHashAfterRemap(siteRemap, null);
if (playable != null) hash ^= playable.calculateHashAfterRemap(siteRemap, false);
if (count != null) hash ^= count.calculateHashAfterRemap(siteRemap, null);
if (state != null) hash ^= state.calculateHashAfterRemap(siteRemap, null);
if (rotation != null) hash ^= rotation.calculateHashAfterRemap(siteRemap, null);
if (value != null) hash ^= value.calculateHashAfterRemap(siteRemap, null);
if (hidden != null)
{
for (int i = 1; i < hidden.length; i++)
hash ^= hidden[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhat != null)
{
for (int i = 1; i < hiddenWhat.length; i++)
hash ^= hiddenWhat[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWho != null)
{
for (int i = 1; i < hiddenWho.length; i++)
hash ^= hiddenWho[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenCount != null)
{
for (int i = 1; i < hiddenCount.length; i++)
hash ^= hiddenCount[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenRotation != null)
{
for (int i = 1; i < hiddenRotation.length; i++)
hash ^= hiddenRotation[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenValue != null)
{
for (int i = 1; i < hiddenValue.length; i++)
hash ^= hiddenValue[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenState != null)
{
for (int i = 1; i < hiddenState.length; i++)
hash ^= hiddenState[i].calculateHashAfterRemap(siteRemap, false);
}
}
}
if (edgeRemap != null && edgeRemap.length > 0)
{
if (whoEdge != null) hash ^= whoEdge.calculateHashAfterRemap(edgeRemap, playerRemap);
if (!whoOnly)
{
if (whatEdge != null) hash ^= whatEdge.calculateHashAfterRemap(edgeRemap, null);
if (countEdge != null) hash ^= countEdge.calculateHashAfterRemap(edgeRemap, null);
if (stateEdge != null) hash ^= stateEdge.calculateHashAfterRemap(edgeRemap, null);
if (rotationEdge != null) hash ^= rotationEdge.calculateHashAfterRemap(edgeRemap, null);
if (hiddenEdge != null)
{
for (int i = 1; i < hiddenEdge.length; i++)
hash ^= hiddenEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhatEdge != null)
{
for (int i = 1; i < hiddenWhatEdge.length; i++)
hash ^= hiddenWhatEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhoEdge != null)
{
for (int i = 1; i < hiddenWhoEdge.length; i++)
hash ^= hiddenWhoEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenCountEdge != null)
{
for (int i = 1; i < hiddenCountEdge.length; i++)
hash ^= hiddenCountEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenRotationEdge != null)
{
for (int i = 1; i < hiddenRotationEdge.length; i++)
hash ^= hiddenRotationEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenValueEdge != null)
{
for (int i = 1; i < hiddenValueEdge.length; i++)
hash ^= hiddenValueEdge[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenStateEdge != null)
{
for (int i = 1; i < hiddenStateEdge.length; i++)
hash ^= hiddenStateEdge[i].calculateHashAfterRemap(siteRemap, false);
}
}
}
if (vertexRemap != null && vertexRemap.length > 0)
{
if (whoVertex != null) hash ^= whoVertex.calculateHashAfterRemap(vertexRemap, playerRemap);
if (!whoOnly)
{
if (whatVertex != null) hash ^= whatVertex.calculateHashAfterRemap(vertexRemap, null);
if (countVertex != null) hash ^= countVertex.calculateHashAfterRemap(vertexRemap, null);
if (stateVertex != null) hash ^= stateVertex.calculateHashAfterRemap(vertexRemap, null);
if (rotationVertex != null) hash ^= rotationVertex.calculateHashAfterRemap(vertexRemap, null);
if (hiddenVertex != null)
{
for (int i = 1; i < hiddenVertex.length; i++)
hash ^= hiddenVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhatVertex != null)
{
for (int i = 1; i < hiddenWhatVertex.length; i++)
hash ^= hiddenWhatVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenWhoVertex != null)
{
for (int i = 1; i < hiddenWhoVertex.length; i++)
hash ^= hiddenWhoVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenCountVertex != null)
{
for (int i = 1; i < hiddenCountVertex.length; i++)
hash ^= hiddenCountVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenRotationVertex != null)
{
for (int i = 1; i < hiddenRotationVertex.length; i++)
hash ^= hiddenRotationVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenValueVertex != null)
{
for (int i = 1; i < hiddenValueVertex.length; i++)
hash ^= hiddenValueVertex[i].calculateHashAfterRemap(siteRemap, false);
}
if (hiddenStateVertex != null)
{
for (int i = 1; i < hiddenStateVertex.length; i++)
hash ^= hiddenStateVertex[i].calculateHashAfterRemap(siteRemap, false);
}
}
}
return hash;
}
@Override
public int whoEdge(final int edge)
{
return whoEdge.getChunk(edge);
}
@Override
public int whoVertex(final int vertex)
{
return whoVertex.getChunk(vertex);
}
//-------------------------------------------------------------------------
@Override
public int whatEdge(final int edge)
{
if (whatEdge == null)
return whoEdge(edge);
return whatEdge.getChunk(edge);
}
//-------------------------------------------------------------------------
@Override
public int stateEdge(final int edge)
{
if (stateEdge == null)
return 0;
return stateEdge.getChunk(edge);
}
@Override
public int rotationEdge(final int edge)
{
if (rotationEdge == null)
return 0;
return rotationEdge.getChunk(edge);
}
//-------------------------------------------------------------------------
@Override
public int countEdge(final int edge)
{
if (countEdge != null)
return countEdge.getChunk(edge);
if (whoEdge.getChunk(edge) != 0 || whatEdge != null && whatEdge.getChunk(edge) != 0)
return 1;
return 0;
}
//-------------------------------------------------------------------------
@Override
public int whatVertex(final int vertex)
{
if (whatVertex == null)
return whoVertex(vertex);
return whatVertex.getChunk(vertex);
}
//-------------------------------------------------------------------------
@Override
public int stateVertex(final int vertex)
{
if (stateVertex == null)
return 0;
return stateVertex.getChunk(vertex);
}
@Override
public int rotationVertex(final int vertex)
{
if (rotationVertex == null)
return 0;
return rotationVertex.getChunk(vertex);
}
//-------------------------------------------------------------------------
@Override
public int countVertex(final int vertex)
{
if (countVertex != null)
return countVertex.getChunk(vertex);
if (whoVertex.getChunk(vertex) != 0 || whatVertex != null && whatVertex.getChunk(vertex) != 0)
return 1;
return 0;
}
/**
* @param site The site.
* @param type The graph element type.
*
* @return True if the site is occupied.
*/
public boolean isOccupied(final int site, final SiteType type)
{
if (type.equals(SiteType.Cell))
return countCell(site) != 0;
else if (type.equals(SiteType.Edge))
return countEdge(site) != 0;
else
return countVertex(site) != 0;
}
@Override
public void addToEmpty(final int site, final SiteType type)
{
if (type.equals(SiteType.Cell))
empty.add(site - offset);
else if (type.equals(SiteType.Edge))
emptyEdge.add(site);
else
emptyVertex.add(site);
}
@Override
public void removeFromEmpty(final int site, final SiteType type)
{
if (type.equals(SiteType.Cell))
empty.remove(site - offset);
else if (type.equals(SiteType.Edge))
emptyEdge.remove(site);
else
emptyVertex.remove(site);
}
@Override
public void setSite(final State trialState, final int site, final int whoVal, final int whatVal, final int countVal,
final int stateVal, final int rotationVal, final int valueVal, final SiteType type)
{
if (type.equals(SiteType.Cell) || container().index() != 0)
{
super.setSite(trialState, site, whoVal, whatVal, countVal, stateVal, rotationVal, valueVal, type);
}
else if (type.equals(SiteType.Edge))
{
final boolean wasEmpty = !isOccupied(site, type);
if (whoVal != Constants.UNDEFINED)
whoEdge.setChunk(trialState, site, whoVal);
if (whatVal != Constants.UNDEFINED)
defaultIfNull(whatEdge).setChunk(trialState, site, whatVal);
if (countVal != Constants.UNDEFINED)
{
if (countEdge != null)
countEdge.setChunk(trialState, site, (countVal < 0 ? 0 : countVal));
else if (countEdge == null && countVal > 1)
throw new UnsupportedOperationException(
"This game does not support counts, but a count > 1 has been set. countVal=" + countVal);
}
if (stateVal != Constants.UNDEFINED)
{
if (stateEdge != null)
stateEdge.setChunk(trialState, site, stateVal);
else if (stateVal != 0)
throw new UnsupportedOperationException(
"This game does not support states, but a state has been set. stateVal=" + stateVal);
}
if (rotationVal != Constants.UNDEFINED)
{
if (rotationEdge != null)
rotationEdge.setChunk(trialState, site, rotationVal);
else if (rotationVal != 0)
throw new UnsupportedOperationException(
"This game does not support rotations, but a rotation has been set. rotationVal="
+ rotationVal);
}
if (valueVal != Constants.UNDEFINED)
{
if (valueEdge != null)
valueEdge.setChunk(trialState, site, valueVal);
else if (valueVal != 0)
throw new UnsupportedOperationException(
"This game does not support piece values, but a value has been set. valueVal=" + valueVal);
}
final boolean isEmpty = !isOccupied(site, type);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmpty(site, type);
else
removeFromEmpty(site, type);
}
else if (type.equals(SiteType.Vertex))
{
final boolean wasEmpty = !isOccupied(site, type);
if (whoVal != Constants.UNDEFINED)
whoVertex.setChunk(trialState, site, whoVal);
if (whatVal != Constants.UNDEFINED)
defaultIfNull(whatVertex).setChunk(trialState, site, whatVal);
if (countVal != Constants.UNDEFINED)
{
if (countVertex != null)
countVertex.setChunk(trialState, site, (countVal < 0 ? 0 : countVal));
else if (countVertex == null && countVal > 1)
throw new UnsupportedOperationException(
"This game does not support counts, but a count > 1 has been set. countVal=" + countVal);
}
if (stateVal != Constants.UNDEFINED)
{
if (stateVertex != null)
stateVertex.setChunk(trialState, site, stateVal);
else if (stateVal != 0)
throw new UnsupportedOperationException(
"This game does not support states, but a state has been set. stateVal=" + stateVal);
}
if (rotationVal != Constants.UNDEFINED)
{
if (rotationVertex != null)
rotationVertex.setChunk(trialState, site, rotationVal);
else if (rotationVal != 0)
throw new UnsupportedOperationException(
"This game does not support rotations, but a rotation has been set. rotationVal="
+ rotationVal);
}
if (valueVal != Constants.UNDEFINED)
{
if (valueVertex != null)
valueVertex.setChunk(trialState, site, valueVal);
else if (valueVal != 0)
throw new UnsupportedOperationException(
"This game does not support piece values, but a value has been set. valueVal=" + valueVal);
}
final boolean isEmpty = !isOccupied(site, type);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmpty(site, type);
else
removeFromEmpty(site, type);
}
}
@Override
public Region emptyRegion(final SiteType type)
{
if (type.equals(SiteType.Cell))
return empty;
else if (type.equals(SiteType.Edge))
return emptyEdge;
else
return emptyVertex;
}
@Override
public boolean isEmptyVertex(final int vertex)
{
return emptyVertex.contains(vertex - offset);
}
@Override
public boolean isEmptyEdge(final int edge)
{
return emptyEdge.contains(edge - offset);
}
@Override
public int whoVertex(int site, int level)
{
return whoVertex(site);
}
@Override
public int whatVertex(int site, int level)
{
return whatVertex(site);
}
@Override
public int stateVertex(int site, int level)
{
return stateVertex(site);
}
@Override
public int rotationVertex(int site, int level)
{
return rotationVertex(site);
}
@Override
public int valueVertex(final int site)
{
if (valueVertex == null)
return 0;
return valueVertex.getChunk(site);
}
@Override
public int whoEdge(int site, int level)
{
return whoEdge(site);
}
@Override
public int whatEdge(int site, int level)
{
return whatEdge(site);
}
@Override
public int stateEdge(int site, int level)
{
return stateEdge(site);
}
@Override
public int rotationEdge(int site, int level)
{
return rotationEdge(site);
}
@Override
public int valueEdge(final int site)
{
if (valueEdge == null)
return 0;
return valueEdge.getChunk(site);
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("ContainerState type = " + this.getClass() + "\n");
if (empty != null)
sb.append("empty = " + empty.bitSet().toChunkString() + "\n");
if (emptyEdge != null)
sb.append("emptyEdge = " + emptyEdge.bitSet().toChunkString() + "\n");
if (emptyVertex != null)
sb.append("emptyVertex = " + emptyVertex.bitSet().toChunkString() + "\n");
if (who != null)
sb.append("Who = " + who.internalStateCopy().toChunkString() + "\n");
if (whoEdge != null)
sb.append("whoEdge = " + whoEdge.internalStateCopy().toChunkString() + "\n");
if (whoVertex != null)
sb.append("whoVertex = " + whoVertex.internalStateCopy().toChunkString() + "\n");
if (what != null)
sb.append("What" + what.internalStateCopy().toChunkString() + "\n");
if (whatEdge != null)
sb.append("whatEdge = " + whatEdge.internalStateCopy().toChunkString() + "\n");
if (whatVertex != null)
sb.append("whatVertex = " + whatVertex.internalStateCopy().toChunkString() + "\n");
if (state != null)
sb.append("State = " + state.internalStateCopy().toChunkString() + "\n");
if (rotation != null)
sb.append("Rotation = " + rotation.internalStateCopy().toChunkString() + "\n");
if (value != null)
sb.append("value = " + value.internalStateCopy().toChunkString() + "\n");
if (count != null)
sb.append("Count = " + count.internalStateCopy().toChunkString() + "\n");
if (playable != null)
sb.append("Playable = " + playable.internalStateCopy().toString() + "\n");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override public ChunkSet emptyChunkSetVertex() { return emptyVertex.bitSet(); }
@Override public ChunkSet emptyChunkSetEdge() { return emptyEdge.bitSet(); }
@Override public int numChunksWhoVertex() { return whoVertex.numChunks(); }
@Override public int numChunksWhoEdge() { return whoEdge.numChunks(); }
@Override public int chunkSizeWhoVertex() { return whoVertex.chunkSize(); }
@Override public int chunkSizeWhoEdge() { return whoEdge.chunkSize(); }
@Override
public int numChunksWhatVertex()
{
return whatVertex != null ? whatVertex.numChunks() : whoVertex.numChunks();
}
@Override
public int numChunksWhatEdge()
{
return whatEdge != null ? whatEdge.numChunks() : whoEdge.numChunks();
}
@Override
public int chunkSizeWhatVertex()
{
return whatVertex != null ? whatVertex.chunkSize() : whoVertex.chunkSize();
}
@Override
public int chunkSizeWhatEdge()
{
return whatEdge != null ? whatEdge.chunkSize() : whoEdge.chunkSize();
}
@Override public boolean matchesWhoVertex(final ChunkSet mask, final ChunkSet pattern) { return whoVertex.matches(mask, pattern); }
@Override public boolean matchesWhoEdge(final ChunkSet mask, final ChunkSet pattern) { return whoEdge.matches(mask, pattern); }
@Override public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern) { return whoVertex.violatesNot(mask, pattern); }
@Override public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern) { return whoEdge.violatesNot(mask, pattern); }
@Override public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{ return whoVertex.violatesNot(mask, pattern, startWord); }
@Override public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{ return whoEdge.violatesNot(mask, pattern, startWord); }
@Override
public boolean matchesWhatVertex(final ChunkSet mask, final ChunkSet pattern)
{
return whatVertex != null ? whatVertex.matches(mask, pattern) : whoVertex.matches(mask, pattern);
}
@Override
public boolean matchesWhatEdge(final ChunkSet mask, final ChunkSet pattern)
{
return whatEdge != null ? whatEdge.matches(mask, pattern) : whoEdge.matches(mask, pattern);
}
@Override
public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern)
{
return whatVertex != null ? whatVertex.violatesNot(mask, pattern) : whoVertex.violatesNot(mask, pattern);
}
@Override
public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern)
{
return whatEdge != null ? whatEdge.violatesNot(mask, pattern) : whoEdge.violatesNot(mask, pattern);
}
@Override
public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return whatVertex != null ? whatVertex.violatesNot(mask, pattern, startWord) : whoVertex.violatesNot(mask, pattern, startWord);
}
@Override
public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord)
{
return whatEdge != null ? whatEdge.violatesNot(mask, pattern, startWord) : whoEdge.violatesNot(mask, pattern, startWord);
}
@Override
public boolean matchesWhoVertex(final int wordIdx, final long mask, final long matchingWord)
{
return whoVertex.matches(wordIdx, mask, matchingWord);
}
@Override
public boolean matchesWhoEdge(final int wordIdx, final long mask, final long matchingWord)
{
return whoEdge.matches(wordIdx, mask, matchingWord);
}
@Override
public boolean matchesWhatVertex(final int wordIdx, final long mask, final long matchingWord)
{
return whatVertex != null ? whatVertex.matches(wordIdx, mask, matchingWord) : whoVertex.matches(wordIdx, mask, matchingWord);
}
@Override
public boolean matchesWhatEdge(final int wordIdx, final long mask, final long matchingWord)
{
return whatEdge != null ? whatEdge.matches(wordIdx, mask, matchingWord) : whoEdge.matches(wordIdx, mask, matchingWord);
}
@Override public ChunkSet cloneWhoVertex() { return whoVertex.internalStateCopy(); }
@Override public ChunkSet cloneWhoEdge() { return whoEdge.internalStateCopy(); }
@Override public ChunkSet cloneWhatVertex() { return whatVertex != null ? whatVertex.internalStateCopy() : whoVertex.internalStateCopy(); }
@Override public ChunkSet cloneWhatEdge() { return whatEdge != null ? whatEdge.internalStateCopy() : whoEdge.internalStateCopy(); }
}
| 52,009 | 32.42545 | 140 | java |
Ludii | Ludii-master/Core/src/other/state/container/ContainerState.java | package other.state.container;
import java.io.Serializable;
import java.util.BitSet;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.util.equipment.Region;
import main.collections.ChunkSet;
import other.Sites;
import other.state.State;
import other.state.symmetry.SymmetryValidator;
/**
* Common ContainerState methods.
*
* @author mrraow, cambolbro, Eric.Piette and Dennis Soemers
*/
public interface ContainerState extends Serializable
{
/**
* Reset this state. Manages hashes, if any
* @param trialState
* @param game
*/
public void reset(final State trialState, final Game game);
/**
* Removes the item(s) at site, performs all necessary operations to clean up
* afterwards
*
* @param state
* @param site
* @param type
* @return the index of the component removed, or 0 if none
*/
public int remove(final State state, final int site, final SiteType type);
/**
* Removes the item(s) at site and level, performs all necessary operations to
* clean up afterwards
*
* @param state
* @param site
* @param level
* @param type
* @return the index of the component removed, or 0 if none
*/
public int remove(final State state, final int site, final int level, final SiteType type);
//-------------------------------------------------------------------------
/**
* @return Deep copy of self.
*/
public ContainerState deepClone();
//-------------------------------------------------------------------------
/**
* Iterates through the allowed symmetries, returns the lowest hash value
* @param validator validates a given symmetry
* @param state provides extra information for symmetries, e.g. number of players
* @param whoOnly if true, hash only the 'who' values (for games with undifferentiated pieces)
* @return canonical (lowest) hash value from the allowed symmetries
*/
public long canonicalHash(final SymmetryValidator validator, final State state, final boolean whoOnly);
/**
* @return Collection of empty sites.
*/
public Sites emptySites();
/**
* @return Number of empty sites.
*/
public int numEmpty();
/**
* @param site
* @param type
*
* @return Whether the specified site is empty.
*/
public boolean isEmpty(final int site, final SiteType type);
/**
* @param cell
*
* @return Whether the specified cell is empty.
*/
public boolean isEmptyCell(final int cell);
/**
* @param edge
*
* @return Whether the specified edge is empty.
*/
public boolean isEmptyEdge(final int edge);
/**
* @param vertex
*
* @return Whether the specified vertex is empty.
*/
public boolean isEmptyVertex(final int vertex);
/**
* NOTE: Do NOT modify the Region!
*
* @param type
*
* @return Reference to the empty Region.
*/
public Region emptyRegion(final SiteType type);
/**
* Add a site to the empty record.
* @param site
*/
public void addToEmptyCell(final int site);
/**
* Add a site to the empty record for a specific graph element type.
*
* @param site
* @param type
*/
public void addToEmpty(final int site, final SiteType type);
/**
* Remove a site from the empty record for a specific graph element type.
*
* @param site
* @param type
*/
public void removeFromEmpty(final int site, final SiteType type);
/**
* Remove a site from the empty record.
* @param site
*/
public void removeFromEmptyCell(final int site);
/**
* Add a vertex to the empty record.
*
* @param site
*/
public void addToEmptyVertex(final int site);
/**
* Remove a vertex from the empty record.
*
* @param site
*/
public void removeFromEmptyVertex(final int site);
/**
* Add an edge to the empty record.
*
* @param site
*/
public void addToEmptyEdge(final int site);
/**
* Remove an edge from the empty record.
*
* @param site
*/
public void removeFromEmptyEdge(final int site);
//-------------------------------------------------------------------------
/**
* @return Reference to corresponding source container.
*/
public Container container();
/**
* Set the container reference.
* @param cont
*/
public void setContainer(final Container cont);
/**
* @return Container name extracted from file
*/
public String nameFromFile();
/**
* Set playable a site.
*
* @param trialState
* @param site
* @param on
*/
public void setPlayable(final State trialState, final int site, final boolean on);
//-------------------------------------------------------------------------
/**
* Grand unified setter
*
* @param trialState
* @param site
* @param who
* @param what
* @param count
* @param state
* @param rotation
* @param value
* @param type
*/
public void setSite
(
final State trialState, final int site, final int who, final int what, final int count,
final int state, final int rotation, final int value, final SiteType type
);
//-------------------------------------------------------------------------
/**
* @param site
* @return Index of owner at the specified site.
*/
public int whoCell(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Index of item at the specified site.
*/
public int whatCell(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item count at the specified site.
*/
public int countCell(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item state at the specified site.
*/
public int stateCell(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item rotation at the specified site.
*/
public int rotationCell(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item value at the specified site.
*/
public int valueCell(final int site);
/**
* @param site
* @param level
* @return Item value at the specified site.
*/
public int valueCell(final int site, final int level);
//-------------------------------------------------------------------------
/**
* @param site
* @return can we play here?
*/
public boolean isPlayable(final int site);
//-------------------------------------------------------------------------
/**
* @param site
*
* @return is this site occupied.
*/
public boolean isOccupied(final int site);
/**
* @param site
*
* @return the size of the stack
*/
public int sizeStackCell(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Index of item at the specified edge.
*/
public int whatEdge(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Index of the owner of a specified edge.
*/
public int whoEdge(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item count at the specified edge.
*/
public int countEdge(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item state at the specified edge.
*/
public int stateEdge(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item rotation at the specified edge.
*/
public int rotationEdge(final int site);
//-------------------------------------------------------------------------
/**
* @param site
*
* @return the size of the stack for edge
*/
public int sizeStackEdge(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Index of item at the specified vertex.
*/
public int whatVertex(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Index of item at the specified vertex.
*/
public int whoVertex(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item count at the specified vertex.
*/
public int countVertex(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item state at the specified vertex.
*/
public int stateVertex(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @return Item rotation at the specified vertex.
*/
public int rotationVertex(final int site);
/**
* @param site
* @return Item value at the specified vertex.
*/
public int valueVertex(final int site);
/**
* @param site
* @param level
* @return Item value at the specified vertex.
*/
public int valueVertex(final int site, final int level);
/**
* @param site
* @return the size of the stack for vertex.
*/
public int sizeStackVertex(final int site);
//-------------------------------------------------------------------------
/**
* @param site
* @param graphElementType
* @return The index of the component on that site.
*/
public abstract int what(final int site,
final SiteType graphElementType);
/**
* @param site
* @param graphElementType
* @return The who data of the site.
*/
public abstract int who(final int site,
final SiteType graphElementType);
/**
* @param site
* @param graphElementType
* @return The count data of the site.
*/
public abstract int count(final int site,
final SiteType graphElementType);
/**
* @param site
* @param graphElementType
* @return The size stack of the site.
*/
public abstract int sizeStack(final int site,
final SiteType graphElementType);
/**
*
* @param site
* @param graphElementType
* @return The local state value of the site.
*/
public abstract int state(final int site,
final SiteType graphElementType);
/**
* @param site
* @param graphElementType
* @return The rotation value of the site.
*/
public abstract int rotation(final int site,
final SiteType graphElementType);
/**
* @param site
* @param graphElementType
* @return The piece value of the site.
*/
public abstract int value(final int site,
final SiteType graphElementType);
/**
* @param site
* @param level
* @param graphElementType
* @return The what data of the site.
*/
public abstract int what(final int site, final int level,
final SiteType graphElementType);
/**
* @param site
* @param level
* @param graphElementType
* @return The who data of the site.
*/
public abstract int who(final int site, final int level,
final SiteType graphElementType);
/**
* @param site
* @param level
* @param graphElementType
* @return The state value of the site.
*/
public abstract int state(final int site, final int level,
final SiteType graphElementType);
/**
* @param site
* @param level
* @param graphElementType
* @return The rotation value of the site.
*/
public abstract int rotation(final int site, final int level,
final SiteType graphElementType);
/**
* @param site
* @param level
* @param graphElementType
* @return The piece value of the site.
*/
public abstract int value(final int site, final int level,
final SiteType graphElementType);
/**
* To set the value of a site in case of dominoes games.
*
* @param state
* @param site
* @param value
*/
public void setValueCell(final State state, final int site, final int value);
/**
* Add an item.
*
* @param trialState
* @param site
* @param what
* @param who
* @param game
* @param graphElementType
*/
public void addItemGeneric(final State trialState, final int site, final int what, final int who, final Game game,
final SiteType graphElementType);
/**
* Add an item.
*
* @param trialState
* @param site
* @param what
* @param who
* @param stateVal
* @param rotationVal
* @param value
* @param game
* @param graphElementType
*/
public void addItemGeneric(final State trialState, final int site, final int what, final int who,
final int stateVal, final int rotationVal, final int value, final Game game,
final SiteType graphElementType);
/**
* Add an item.
*
* @param trialState
* @param site
* @param what
* @param who
* @param game
* @param hidden
* @param masked
* @param graphElementType
*/
public void addItemGeneric(final State trialState, final int site, final int what, final int who, final Game game,
final boolean[] hidden, final boolean masked, final SiteType graphElementType);
/**
* Remove a stack.
*
* @param state
* @param site
* @param graphElementType
*/
public void removeStackGeneric(final State state, final int site, final SiteType graphElementType);
/**
* Set the count.
*
* @param state
* @param site
* @param count
*/
public void setCount(final State state, final int site, final int count);
/**
* Add an item.
*
* @param trialState
* @param site
* @param what
* @param who
* @param game
*/
public void addItem(final State trialState, final int site, final int what, final int who, final Game game);
/**
* Insert an element in a stack of any type.
*
* @param trialState
* @param type
* @param site
* @param level
* @param what
* @param who
* @param state
* @param rotation
* @param value
* @param game
*/
public void insert(final State trialState, final SiteType type, final int site, final int level, final int what,
final int who, final int state, final int rotation, final int value, final Game game);
/**
* Insert an element in a stack.
*
* @param trialState
* @param site
* @param level
* @param what
* @param who
* @param state
* @param rotation
* @param value
* @param game
*/
public void insertCell(final State trialState, final int site, final int level, final int what, final int who,
final int state, final int rotation, final int value, final Game game);
/**
* Add an item.
*
* @param trialState
* @param site
* @param what
* @param who
* @param stateVal
* @param rotationVal
* @param value
* @param game
*/
public void addItem(final State trialState, final int site, final int what, final int who, final int stateVal,
final int rotationVal, final int value, final Game game);
/**
* Add an item.
*
* @param trialState
* @param site
* @param what
* @param who
* @param game
* @param hidden
* @param masked
*/
public void addItem(final State trialState, final int site, final int what, final int who, final Game game, final boolean[] hidden, final boolean masked);
/**
* Remove a stack.
*
* @param state
* @param site
*/
public void removeStack(final State state, final int site);
/**
* @param site
* @param level
* @return The owner of a cell.
*/
public int whoCell(final int site, final int level);
/**
* @param site
* @param level
* @return the index of the element in the site.
*/
public int whatCell(final int site, final int level);
/**
* @param site
* @param level
* @return The state of the cell.
*/
public int stateCell(final int site, final int level);
/**
* @param site
* @param level
* @return The rotation of the cell.
*/
public int rotationCell(final int site, final int level);
/**
* @param state
* @param site
* @param level
* @return The value removed.
*/
public int remove(final State state, final int site, final int level);
/**
* Set data on a site.
*
* @param trialState
* @param site
* @param level
* @param whoVal
* @param whatVal
* @param countVal
* @param stateVal
* @param rotationVal
* @param valueVal
*/
public void setSite(final State trialState, final int site, final int level, final int whoVal, final int whatVal, final int countVal, final int stateVal, final int rotationVal, final int valueVal);
/**
* Add an item to a vertex.
*
* @param trialState
* @param site
* @param what
* @param who
* @param game
*/
public void addItemVertex(final State trialState, final int site, final int what, final int who, final Game game);
/**
* Insert an element to a vertex.
*
* @param trialState
* @param site
* @param level
* @param what
* @param who
* @param state
* @param rotation
* @param value
* @param game
*/
public void insertVertex(final State trialState, final int site, final int level, final int what, final int who,
final int state, final int rotation, final int value,
final Game game);
/**
* Insert an element to a vertex.
*
* @param trialState
* @param site
* @param what
* @param who
* @param stateVal
* @param rotationVal
* @param value
* @param game
*/
public void addItemVertex(final State trialState, final int site, final int what, final int who, final int stateVal,
final int rotationVal, final int value, final Game game);
/**
* Add an element to a vertex.
*
* @param trialState
* @param site
* @param what
* @param who
* @param game
* @param hidden
* @param masked
*/
public void addItemVertex(final State trialState, final int site, final int what, final int who, final Game game, final boolean[] hidden, final boolean masked);
/**
* Remove a stack from a vertex.
*
* @param state
* @param site
*/
public void removeStackVertex(final State state, final int site);
/**
* @param site
* @param level
* @return The owner of a vertex.
*/
public int whoVertex(final int site, final int level);
/**
* @param site
* @param level
* @return The index of the element on a vertex.
*/
public int whatVertex(final int site, final int level);
/**
* @param site
* @param level
* @return The state value of a vertex.
*/
public int stateVertex(final int site, final int level);
/**
* @param site
* @param level
* @return The rotation value of a vertex.
*/
public int rotationVertex(final int site, final int level);
/**
* Add an item to an edge.
*
* @param trialState
* @param site
* @param what
* @param who
* @param game
*/
public void addItemEdge(final State trialState, final int site, final int what, final int who, final Game game);
/**
* Insert a element to an edge.
*
* @param trialState
* @param site
* @param level
* @param what
* @param who
* @param state
* @param rotation
* @param value
* @param game
*/
public void insertEdge(final State trialState, final int site, final int level, final int what, final int who,
final int state, final int rotation, final int value,
final Game game);
/**
* Add a element to an edge.
*
* @param trialState
* @param site
* @param what
* @param who
* @param stateVal
* @param rotationVal
* @param value
* @param game
*/
public void addItemEdge(final State trialState, final int site, final int what, final int who, final int stateVal,
final int rotationVal, final int value, final Game game);
/**
* Add an element to an edge.
*
* @param trialState
* @param site
* @param what
* @param who
* @param game
* @param hidden
* @param masked
*/
public void addItemEdge(final State trialState, final int site, final int what, final int who, final Game game, final boolean[] hidden, final boolean masked);
/**
* Remove a stack from an edge.
*
* @param state
* @param site
*/
public void removeStackEdge(final State state, final int site);
/**
* @param site
* @param level
* @return The owner of an edge.
*/
public int whoEdge(final int site, final int level);
/**
* @param site
* @param level
* @return The index of the component on an edge.
*/
public int whatEdge(final int site, final int level);
/**
* @param site
* @param level
* @return The state value of an edge.
*/
public int stateEdge(final int site, final int level);
/**
* @param site
* @param level
* @return The rotation value of an edge.
*/
public int rotationEdge(final int site, final int level);
/**
* @param site
* @return Item value at the specified edge.
*/
public int valueEdge(final int site);
/**
* @param site
* @param level
* @return Item value at the specified edge.
*/
public int valueEdge(final int site, final int level);
// ------ Hidden Info--------------------------------------------
/**
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the site is invisible.
*/
public boolean isHidden(final int who, final int site, final int level, final SiteType type);
/**
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the what information is not know.
*/
public boolean isHiddenWhat(final int who, final int site, final int level, final SiteType type);
/**
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the who information is not know.
*/
public boolean isHiddenWho(final int who, final int site, final int level, final SiteType type);
/**
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the local state info is not know.
*/
public boolean isHiddenState(final int who, final int site, final int level, final SiteType type);
/**
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the piece value is not know.
*/
public boolean isHiddenValue(final int who, final int site, final int level, final SiteType type);
/**
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the rotation information is not know.
*/
public boolean isHiddenRotation(final int who, final int site, final int level, final SiteType type);
/**
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the count information is not know.
*/
public boolean isHiddenCount(final int who, final int site, final int level, final SiteType type);
/**
* To set the hidden information.
*
* @param state The state.
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHidden(final State state, final int who, final int site, final int level, final SiteType type,
final boolean on);
/**
* To set the What hidden information.
*
* @param state The state.
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenWhat(final State state, final int who, final int site, final int level, final SiteType type,
final boolean on);
/**
* To set the Who hidden information.
*
* @param state The state.
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenWho(final State state, final int who, final int site, final int level, final SiteType type,
final boolean on);
/**
* To set the state hidden information.
*
* @param state The state.
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenState(final State state, final int who, final int site, final int level, final SiteType type,
final boolean on);
/**
* To set the piece value hidden information.
*
* @param state The state.
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenValue(final State state, final int who, final int site, final int level, final SiteType type,
final boolean on);
/**
* To set the rotation hidden information.
*
* @param state The state.
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenRotation(final State state, final int who, final int site, final int level,
final SiteType type,
final boolean on);
/**
* To set the count hidden information.
*
* @param state The state.
* @param who The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenCount(final State state, final int who, final int site, final int level, final SiteType type,
final boolean on);
//------ Deduction Puzzle--------------------------------------------
/**
* @param var The site corresponding to the var.
* @param value The value to check.
* @param type The graph element type.
* @return if the value for the element is possible.
*/
public boolean bit(final int var, final int value, final SiteType type);
/**
* @param var The site corresponding to the var.
* @param type The graph element type.
* @return True if the variable is solved.
*/
public boolean isResolved(final int var, final SiteType type);
/**
* @param var The site corresponding to the var.
* @return True if the variable is solved.
*/
public boolean isResolvedEdges(final int var);
/**
* @param var The site corresponding to the var.
* @return True if the variable is solved.
*/
public boolean isResolvedCell(final int var);
/**
* @param var The site corresponding to the var.
* @return True if the variable is solved.
*/
public boolean isResolvedVerts(final int var);
/**
* Set the corresponding variable.
*
* @param var The site corresponding to the var.
* @param value The value to check.
* @param type The graph element type.
*/
public void set(final int var, final int value, final SiteType type);
/**
* @param type
* @param var
* @return Current values for the specified variable.
*/
public abstract BitSet values(final SiteType type, final int var);
//-------------------------------------------------------------------------
/** @return Reference to the empty ChunkSet for vertices. */
public ChunkSet emptyChunkSetVertex();
/** @return Reference to the empty ChunkSet for cells. */
public ChunkSet emptyChunkSetCell();
/** @return Reference to the empty ChunkSet for edges. */
public ChunkSet emptyChunkSetEdge();
/** @return The number of chunks that we have in the "who" ChunkSet for vertices */
public int numChunksWhoVertex();
/** @return The number of chunks that we have in the "who" ChunkSet for cells */
public int numChunksWhoCell();
/** @return The number of chunks that we have in the "who" ChunkSet for edges */
public int numChunksWhoEdge();
/** @return The size per chunk for our "who" ChunkSet for vertices */
public int chunkSizeWhoVertex();
/** @return The size per chunk for our "who" ChunkSet for cells */
public int chunkSizeWhoCell();
/** @return The size per chunk for our "who" ChunkSet for edges */
public int chunkSizeWhoEdge();
/** @return The number of chunks that we have in the "what" ChunkSet for vertices */
public int numChunksWhatVertex();
/** @return The number of chunks that we have in the "what" ChunkSet for cells */
public int numChunksWhatCell();
/** @return The number of chunks that we have in the "what" ChunkSet for edges */
public int numChunksWhatEdge();
/** @return The size per chunk for our "what" ChunkSet for vertices */
public int chunkSizeWhatVertex();
/** @return The size per chunk for our "what" ChunkSet for cells */
public int chunkSizeWhatCell();
/** @return The size per chunk for our "what" ChunkSet for edges */
public int chunkSizeWhatEdge();
/**
* Tests whether the parts of the given pattern that are covered by the given mask
* are identical in our "who" ChunkSet for vertices.
*
* @param mask Relevant parts of ChunkSet
* @param pattern Pattern we wish to match
* @return True if and only if match
*/
public boolean matchesWhoVertex(final ChunkSet mask, final ChunkSet pattern);
/**
* Same as above, but for cells
*
* @param mask Relevant parts of ChunkSet
* @param pattern Pattern we wish to match
*
* @return True if and only if match
*/
public boolean matchesWhoCell(final ChunkSet mask, final ChunkSet pattern);
/**
* Same as above, but for edges
*
* @param mask Relevant parts of ChunkSet
* @param pattern Pattern we wish to match
*
* @return True if and only if match
*/
public boolean matchesWhoEdge(final ChunkSet mask, final ChunkSet pattern);
/**
* Tests whether the parts of the given pattern that are covered by the given mask
* are identical in our "what" ChunkSet for vertices.
*
* @param mask Relevant parts of ChunkSet
* @param pattern Pattern we wish to match
* @return True if and only if match
*/
public boolean matchesWhatVertex(final ChunkSet mask, final ChunkSet pattern);
/**
* Same as above, but for cells
*
* @param mask Relevant parts of ChunkSet
* @param pattern Pattern we wish to match
*
* @return True if and only if match
*/
public boolean matchesWhatCell(final ChunkSet mask, final ChunkSet pattern);
/**
* Same as above, but for edges
*
* @param mask Relevant parts of ChunkSet
* @param pattern Pattern we wish to match
*
* @return True if and only if match
*/
public boolean matchesWhatEdge(final ChunkSet mask, final ChunkSet pattern);
/**
* Tests whether we match a single specific who-value of a vertex.
*
* @param wordIdx Index of the word we want to match
* @param mask Mask to apply
* @param matchingWord The word that we must match after masking
* @return True if a match
*/
public boolean matchesWhoVertex(final int wordIdx, final long mask, final long matchingWord);
/**
* Tests whether we match a single specific who-value of a cell.
*
* @param wordIdx Index of the word we want to match
* @param mask Mask to apply
* @param matchingWord The word that we must match after masking
* @return True if a match
*/
public boolean matchesWhoCell(final int wordIdx, final long mask, final long matchingWord);
/**
* Tests whether we match a single specific who-value of an edge.
*
* @param wordIdx Index of the word we want to match
* @param mask Mask to apply
* @param matchingWord The word that we must match after masking
* @return True if a match
*/
public boolean matchesWhoEdge(final int wordIdx, final long mask, final long matchingWord);
/**
* Tests whether we match a single specific what-value of a vertex.
*
* @param wordIdx Index of the word we want to match
* @param mask Mask to apply
* @param matchingWord The word that we must match after masking
* @return True if a match
*/
public boolean matchesWhatVertex(final int wordIdx, final long mask, final long matchingWord);
/**
* Tests whether we match a single specific what-value of a cell.
*
* @param wordIdx Index of the word we want to match
* @param mask Mask to apply
* @param matchingWord The word that we must match after masking
* @return True if a match
*/
public boolean matchesWhatCell(final int wordIdx, final long mask, final long matchingWord);
/**
* Tests whether we match a single specific what-value of an edge.
*
* @param wordIdx Index of the word we want to match
* @param mask Mask to apply
* @param matchingWord The word that we must match after masking
* @return True if a match
*/
public boolean matchesWhatEdge(final int wordIdx, final long mask, final long matchingWord);
/**
* Tests whether at least one of the chunks in our "who" ChunkSet for vertices
* is equal to one of the chunks in the given pattern that is covered by the
* given mask.
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern);
/**
* Same as above, but for cells
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhoCell(final ChunkSet mask, final ChunkSet pattern);
/**
* Same as above, but for edges
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern);
/**
* Tests whether at least one of the chunks in our "what" ChunkSet for vertices
* is equal to one of the chunks in the given pattern that is covered by the
* given mask.
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern);
/**
* Same as above, but for cells
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhatCell(final ChunkSet mask, final ChunkSet pattern);
/**
* Same as above, but for edges
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern);
/**
* Tests whether at least one of the chunks in our "who" ChunkSet for vertices
* is equal to one of the chunks in the given pattern that is covered by the
* given mask.
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @param startWord The first word of our array of longs in which to start checking
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhoVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord);
/**
* Same as above, but for cells
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @param startWord The first word of our array of longs in which to start
* checking
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhoCell(final ChunkSet mask, final ChunkSet pattern, final int startWord);
/**
* Same as above, but for edges
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @param startWord The first word of our array of longs in which to start
* checking
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhoEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord);
/**
* Tests whether at least one of the chunks in our "what" ChunkSet for vertices
* is equal to one of the chunks in the given pattern that is covered by the given mask.
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @param startWord The first word of our array of longs in which to start checking
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhatVertex(final ChunkSet mask, final ChunkSet pattern, final int startWord);
/**
* Same as above, but for cells
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @param startWord The first word of our array of longs in which to start
* checking
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhatCell(final ChunkSet mask, final ChunkSet pattern, final int startWord);
/**
* Same as above, but for edges
*
* @param mask Relevant parts of ChunkSet
* @param pattern Values that our masked chunks may not have
* @param startWord The first word of our array of longs in which to start
* checking
* @return True if and only if we violate at least one "must-not" condition
*/
public boolean violatesNotWhatEdge(final ChunkSet mask, final ChunkSet pattern, final int startWord);
/** @return Clone of the "who" ChunkSet for vertices */
public ChunkSet cloneWhoVertex();
/** @return Clone of the "who" ChunkSet for cells */
public ChunkSet cloneWhoCell();
/** @return Clone of the "who" ChunkSet for edges */
public ChunkSet cloneWhoEdge();
/** @return Clone of the "what" ChunkSet for vertices */
public ChunkSet cloneWhatVertex();
/** @return Clone of the "what" ChunkSet for cells */
public ChunkSet cloneWhatCell();
/** @return Clone of the "what" ChunkSet for edges */
public ChunkSet cloneWhatEdge();
}
| 38,654 | 26.260226 | 198 | java |
Ludii | Ludii-master/Core/src/other/state/container/ContainerStateFactory.java | package other.state.container;
import game.Game;
import game.equipment.container.Container;
import main.Constants;
import main.collections.ChunkStack;
import other.context.Context;
import other.state.puzzle.ContainerDeductionPuzzleState;
import other.state.puzzle.ContainerDeductionPuzzleStateLarge;
import other.state.stacking.ContainerGraphStateStacks;
import other.state.stacking.ContainerGraphStateStacksLarge;
import other.state.stacking.ContainerStateStacksLarge;
import other.state.stacking.ContainerStateStacks;
import other.state.zhash.ZobristHashGenerator;
import other.trial.Trial;
/**
* Factory pattern
* @author mrraow
*/
public class ContainerStateFactory
{
/**
* @param generator
* @param game
* @param container
*
* @return The correct container state.
*/
public static final ContainerState createStateForContainer(final ZobristHashGenerator generator, final Game game, final Container container)
{
final int containerSites = container.numSites();
final int maxWhatValComponents = game.numComponents();
final int maxWhatValNumPlayers = game.players().count();
final int maxStateValMaximalLocal = 2 + game.maximalLocalStates();
final int maxPieces = game.maxCount();
final int maxCountValMaxPieces = (maxPieces == 0) ? 1 : maxPieces;
final boolean requiresStack = game.isStacking();
final boolean requiresLargeStack = game.hasLargeStack();
final boolean requiresCard = game.hasCard();
final boolean requiresCount = game.requiresCount();
final boolean requiresState = game.requiresLocalState();
final boolean requiresRotation = game.requiresRotation();
final boolean requiresPuzzle = game.isDeductionPuzzle();
final boolean requiresIndices = game.requiresItemIndices();
final boolean requiresPieceValue = game.requiresPieceValue();
final int numChunks = containerSites;
int maxWhatVal = Constants.UNDEFINED;
int maxStateVal = Constants.UNDEFINED;
int maxRotationVal = Constants.UNDEFINED;
int maxCountVal = Constants.UNDEFINED;
final int maxPieceValue = (requiresPieceValue) ? game.maximalValue() : Constants.UNDEFINED;
if (requiresPuzzle)
return constructPuzzle(generator, game, container);
// Special case for cards game
if (requiresCard)
return new ContainerStateStacksLarge(generator, game, container, ChunkStack.TYPE_INDEX_STATE);
if(requiresLargeStack && !container.isHand())
{
if (game.isGraphGame())
return new ContainerGraphStateStacksLarge(generator, game, container, ChunkStack.TYPE_INDEX_STATE);
return new ContainerStateStacksLarge(generator, game, container, ChunkStack.TYPE_INDEX_STATE);
}
else if(requiresLargeStack)
{
return new ContainerStateStacksLarge(generator, game, container, ChunkStack.TYPE_INDEX_STATE);
}
if (!container.isHand() && game.isGraphGame() && requiresStack)
return new ContainerGraphStateStacks(generator, game, container, ChunkStack.TYPE_INDEX_STATE);
// Special case for the hands
if (container.isHand())
{
if (requiresStack)
return constructStack(generator, game, container, requiresState, requiresPieceValue, requiresIndices);
maxWhatVal = maxWhatValComponents;
if (requiresCount)
maxCountVal = maxCountValMaxPieces;
maxStateVal = maxStateValMaximalLocal;
if (requiresRotation)
maxRotationVal = game.maximalRotationStates();
if (game.isGraphGame())
return new ContainerGraphState(generator, game, container, maxWhatVal, maxStateVal,
maxCountVal, maxRotationVal, maxPieceValue);
return new ContainerFlatState(generator, game, container, numChunks, maxWhatVal, maxStateVal, maxCountVal,
maxRotationVal, maxPieceValue);
}
// Special case for stacking
if (requiresStack)
return constructStack(generator, game, container, requiresState, requiresPieceValue, requiresIndices);
// Complex sizing recreating previous processing, but probably wrong... No no, good!
maxCountVal = requiresCount ? maxCountValMaxPieces : -1;
maxWhatVal = requiresIndices ? maxWhatValComponents : maxWhatValNumPlayers;
if (!requiresCount && !requiresIndices && !requiresState && !game.isGraphGame())
maxWhatVal = -1;
if (requiresState)
maxStateVal = maxStateValMaximalLocal;
if (requiresRotation)
maxRotationVal = game.maximalRotationStates();
if (game.isGraphGame())
{
if (game.isVertexGame() && !game.isCellGame() && !game.isEdgeGame())
{
return new ContainerFlatVertexState(generator, game, container, maxWhatVal, maxStateVal, maxCountVal,
maxRotationVal, maxPieceValue);
}
if (!game.isVertexGame() && !game.isCellGame() && game.isEdgeGame())
{
return new ContainerFlatEdgeState(generator, game, container, maxWhatVal, maxStateVal, maxCountVal,
maxRotationVal, maxPieceValue);
}
return new ContainerGraphState(generator, game, container, maxWhatVal, maxStateVal, maxCountVal,
maxRotationVal, maxPieceValue);
}
return new ContainerFlatState(generator, game, container, numChunks, maxWhatVal, maxStateVal, maxCountVal,
maxRotationVal, maxPieceValue);
}
/**
* @param generator
* @param game
* @param container
* @param requiresState
* @param requiresIndices
* @param requiresValue
* @return A container state for stack.
*/
private static ContainerState constructStack(final ZobristHashGenerator generator, final Game game, final Container container,
final boolean requiresState, final boolean requiresIndices, final boolean requiresValue)
{
if (!container.isHand() && !requiresIndices && !requiresState && !requiresValue)
return new ContainerStateStacks(generator, game, container, ChunkStack.TYPE_PLAYER_STATE);
return new ContainerStateStacks(generator, game, container, ChunkStack.TYPE_INDEX_STATE);
}
/**
* @param generator
* @param game
* @param container
* @return A container state for puzzles.
*/
private static ContainerState constructPuzzle(final ZobristHashGenerator generator, final Game game,
final Container container)
{
final int numComponents = game.numComponents();
final int nbValuesEdge;
final int nbValuesVertex;
if (game.isDeductionPuzzle()) // not useful but just to avoid an error on the parsing in worse case.
nbValuesEdge = game.board().edgeRange().max(new Context(game, new Trial(game)))
- game.board().edgeRange().min(new Context(game, new Trial(game))) + 1;
else
nbValuesEdge = 1;
if (game.isDeductionPuzzle()) // not useful but just to avoid an error on the parsing in worse case.
nbValuesVertex = game.board().cellRange().max(new Context(game, new Trial(game)))
- game.board().cellRange().min(new Context(game, new Trial(game))) + 1;
else
nbValuesVertex = 1;
if ((numComponents + 1) > 31 || nbValuesEdge > 31 || nbValuesVertex > 31)
return new ContainerDeductionPuzzleStateLarge(generator, game, container);
else
return new ContainerDeductionPuzzleState(generator, game, container);
}
}
| 6,942 | 34.78866 | 141 | java |
Ludii | Ludii-master/Core/src/other/state/owned/CellOnlyOwned.java | package other.state.owned;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import other.location.CellOnlyLocation;
import other.location.Location;
import other.state.OwnedIndexMapper;
/**
* A version of Owned for games that only use Cell (no other site types)
*
* @author Dennis Soemers
*/
public final class CellOnlyOwned implements Owned, Serializable
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* All the positions (site & level) where is a piece owned by a player. PlayerId
* --> ComponentId --> Positions.
*/
protected final List<CellOnlyLocation>[][] locations;
/** Our index mapper */
protected final OwnedIndexMapper indexMapper;
//-------------------------------------------------------------------------
/**
* To init the positions of the owned site
*
* @param game
*/
@SuppressWarnings("unchecked")
public CellOnlyOwned(final Game game)
{
indexMapper = new OwnedIndexMapper(game);
locations = (List<CellOnlyLocation>[][]) new List<?>[game.players().size() + 1][];
for (int p = 0; p <= game.players().size(); p++)
{
locations[p] = (List<CellOnlyLocation>[]) new List<?>[indexMapper.numValidIndices(p)];
for (int i = 0; i < locations[p].length; i++)
{
locations[p][i] = new ArrayList<CellOnlyLocation>();
}
}
}
/**
* Copy Constructor.
*
* @param other
*/
@SuppressWarnings("unchecked")
private CellOnlyOwned(final CellOnlyOwned other)
{
// We can simply copy the reference for this one
this.indexMapper = other.indexMapper;
// Need deep copies here
this.locations = (List<CellOnlyLocation>[][]) new List<?>[other.locations.length][];
for (int p = 0; p < other.locations.length; ++p)
{
this.locations[p] = (List<CellOnlyLocation>[]) new List<?>[other.locations[p].length];
for (int i = 0; i < other.locations[p].length; ++i)
{
final List<CellOnlyLocation> otherPositionsComp = other.locations[p][i];
final List<CellOnlyLocation> newPositionsComp = new ArrayList<CellOnlyLocation>(otherPositionsComp.size());
for (int k = 0; k < otherPositionsComp.size(); ++k)
{
newPositionsComp.add((CellOnlyLocation) otherPositionsComp.get(k).copy());
}
this.locations[p][i] = newPositionsComp;
}
}
}
@Override
public Owned copy()
{
return new CellOnlyOwned(this);
}
//-------------------------------------------------------------------------
@Override
public int mapCompIndex(final int playerId, final int componentId)
{
return indexMapper.compIndex(playerId, componentId);
}
@Override
public int reverseMap(final int playerId, final int mappedIndex)
{
return indexMapper.reverseMap(playerId, mappedIndex);
}
@Override
public TIntArrayList levels(final int playerId, final int componentId, final int site)
{
final TIntArrayList levels = new TIntArrayList();
final List<CellOnlyLocation> locs = locations[playerId][indexMapper.compIndex(playerId, componentId)];
for (final Location pos : locs)
{
if (pos.site() == site)
{
levels.add(pos.level());
}
}
return levels;
}
@Override
public TIntArrayList sites(final int playerId, final int componentId)
{
final int indexMapped = indexMapper.compIndex(playerId, componentId);
if (indexMapped < 0)
return new TIntArrayList();
final TIntArrayList sites = new TIntArrayList();
final List<CellOnlyLocation> locs = locations[playerId][indexMapped];
for (final Location loc : locs)
{
if (!sites.contains(loc.site()))
sites.add(loc.site());
}
return sites;
}
@Override
public TIntArrayList sites(final int playerId)
{
final TIntArrayList sites = new TIntArrayList();
for (int i = 0; i < locations[playerId].length; i++)
{
final List<CellOnlyLocation> locs = locations[playerId][i];
for (final CellOnlyLocation loc : locs)
{
if (!sites.contains(loc.site()))
sites.add(loc.site());
}
}
return sites;
}
@Override
public TIntArrayList sitesOnTop(final int playerId)
{
final TIntArrayList sites = new TIntArrayList();
for (int i = 0; i < locations[playerId].length; i++)
{
final List<CellOnlyLocation> locs = locations[playerId][i];
for (final CellOnlyLocation loc : locs)
{
if (!sites.contains(loc.site()))
sites.add(loc.site());
}
}
return sites;
}
@Override
public List<CellOnlyLocation> positions(final int playerId, final int componentId)
{
final int indexMapped = indexMapper.compIndex(playerId, componentId);
if (indexMapped < 0)
return new ArrayList<CellOnlyLocation>();
return locations[playerId][indexMapped];
}
@Override
public List<CellOnlyLocation>[] positions(final int playerId)
{
return locations[playerId];
}
//-------------------------------------------------------------------------
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
final List<CellOnlyLocation> compPositions = locations[playerId][indexMapper.compIndex(playerId, componentId)];
for (int i = 0; i < compPositions.size(); /** */)
{
if (compPositions.get(i).site() == pieceLoc)
{
compPositions.remove(i);
}
else
{
++i;
}
}
}
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
final List<CellOnlyLocation> locs = locations[playerId][indexMapper.compIndex(playerId, componentId)];
for (int i = 0; i < locs.size(); i++)
{
if
(
locs.get(i).site() == pieceLoc
&&
locs.get(i).level() == level
)
{
locs.remove(i);
i--;
}
}
for (int idPlayer = 0; idPlayer < locations.length; idPlayer++)
{
for (int i = 0; i < locations[idPlayer].length; i++)
{
for (int idPos = 0; idPos < locations[idPlayer][i].size(); idPos++)
{
final int sitePos = locations[idPlayer][i].get(idPos).site();
final int levelPos = locations[idPlayer][i].get(idPos).level();
if (sitePos == pieceLoc && levelPos > level)
{
locations[idPlayer][i].get(idPos).decrementLevel();
}
}
}
}
}
@Override
public void removeNoUpdate(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
final List<CellOnlyLocation> locs = locations[playerId][indexMapper.compIndex(playerId, componentId)];
for (int i = 0; i < locs.size(); i++)
{
if
(
locs.get(i).site() == pieceLoc
&&
locs.get(i).level() == level
)
{
locs.remove(i);
i--;
}
}
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
assert (type == SiteType.Cell);
locations[playerId][indexMapper.compIndex(playerId, componentId)].add(new CellOnlyLocation(pieceLoc));
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (type == SiteType.Cell);
locations[playerId][indexMapper.compIndex(playerId, componentId)].add(new CellOnlyLocation(pieceLoc, level));
}
//-------------------------------------------------------------------------
}
| 7,447 | 25.411348 | 128 | java |
Ludii | Ludii-master/Core/src/other/state/owned/FlatCellOnlyOwned.java | package other.state.owned;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import main.collections.FastTIntArrayList;
import other.location.FlatCellOnlyLocation;
import other.state.OwnedIndexMapper;
/**
* A version of Owned for games that only use Cells and no levels
*
* @author Dennis Soemers
*/
public final class FlatCellOnlyOwned implements Owned, Serializable
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* All the sites where is a piece owned by a player. PlayerId
* --> ComponentId --> Sites.
*/
protected final FastTIntArrayList[][] locations;
/** Our index mapper */
protected final OwnedIndexMapper indexMapper;
//-------------------------------------------------------------------------
/**
* To init the positions of the owned site
*
* @param game
*/
public FlatCellOnlyOwned(final Game game)
{
indexMapper = new OwnedIndexMapper(game);
locations = new FastTIntArrayList[game.players().size() + 1][];
for (int p = 0; p < locations.length; p++)
{
locations[p] = new FastTIntArrayList[indexMapper.numValidIndices(p)];
for (int i = 0; i < locations[p].length; i++)
{
locations[p][i] = new FastTIntArrayList();
}
}
}
/**
* Copy Constructor.
*
* @param other
*/
private FlatCellOnlyOwned(final FlatCellOnlyOwned other)
{
// We can simply copy the reference for this one
this.indexMapper = other.indexMapper;
// Need deep copies here
this.locations = new FastTIntArrayList[other.locations.length][];
for (int p = 0; p < other.locations.length; ++p)
{
this.locations[p] = new FastTIntArrayList[other.locations[p].length];
for (int i = 0; i < locations[p].length; ++i)
{
this.locations[p][i] = new FastTIntArrayList(other.locations[p][i]);
}
}
}
@Override
public FlatCellOnlyOwned copy()
{
return new FlatCellOnlyOwned(this);
}
//-------------------------------------------------------------------------
@Override
public int mapCompIndex(final int playerId, final int componentId)
{
return indexMapper.compIndex(playerId, componentId);
}
@Override
public int reverseMap(final int playerId, final int mappedIndex)
{
return indexMapper.reverseMap(playerId, mappedIndex);
}
@Override
public TIntArrayList levels(final int playerId, final int componentId, final int site)
{
throw new UnsupportedOperationException();
}
@Override
public FastTIntArrayList sites(final int playerId, final int componentId)
{
final int mappedIdx = indexMapper.compIndex(playerId, componentId);
if (mappedIdx >= 0)
return new FastTIntArrayList(locations[playerId][mappedIdx]);
else
return new FastTIntArrayList();
}
@Override
public TIntArrayList sites(final int playerId)
{
final TIntArrayList sites = new TIntArrayList();
for (int i = 0; i < locations[playerId].length; i++)
{
// Note: we do no contains() checks because, in non-stacking games,
// the same site should never occur more than once anyway
sites.addAll(locations[playerId][i]);
}
return sites;
}
@Override
public TIntArrayList sitesOnTop(final int playerId)
{
return sites(playerId);
}
@Override
public List<FlatCellOnlyLocation> positions(final int playerId, final int componentId)
{
final int indexMapped = indexMapper.compIndex(playerId, componentId);
if (indexMapped < 0)
return new ArrayList<FlatCellOnlyLocation>();
final TIntArrayList sites = locations[playerId][indexMapped];
final List<FlatCellOnlyLocation> locs = new ArrayList<FlatCellOnlyLocation>(sites.size());
for (int i = 0; i < sites.size(); ++i)
{
locs.add(new FlatCellOnlyLocation(sites.getQuick(i)));
}
return locs;
}
@Override
public List<FlatCellOnlyLocation>[] positions(final int playerId)
{
final TIntArrayList[] playerSites = locations[playerId];
@SuppressWarnings("unchecked")
final List<FlatCellOnlyLocation>[] playerLocs = (List<FlatCellOnlyLocation>[]) new List<?>[playerSites.length];
for (int i = 0; i < playerSites.length; ++i)
{
final TIntArrayList sites = locations[playerId][i];
if (sites == null)
{
playerLocs[i] = null;
}
else
{
final List<FlatCellOnlyLocation> locs = new ArrayList<FlatCellOnlyLocation>(sites.size());
for (int j = 0; j < sites.size(); ++j)
{
locs.add(new FlatCellOnlyLocation(sites.getQuick(j)));
}
playerLocs[i] = locs;
}
}
return playerLocs;
}
//-------------------------------------------------------------------------
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
final FastTIntArrayList compPositions = locations[playerId][indexMapper.compIndex(playerId, componentId)];
// Since order doesn't matter, we'll do a remove-swap
final int idx = compPositions.indexOf(pieceLoc);
if (idx >= 0)
{
final int lastIdx = compPositions.size() - 1;
compPositions.set(idx, compPositions.getQuick(lastIdx));
compPositions.removeAt(lastIdx);
}
}
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (level == 0);
remove(playerId, componentId, pieceLoc, type);
}
@Override
public void removeNoUpdate(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (level == 0);
remove(playerId, componentId, pieceLoc, type);
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
assert (type == SiteType.Cell);
locations[playerId][indexMapper.compIndex(playerId, componentId)].add(pieceLoc);
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (type == SiteType.Cell);
assert (level == 0);
add(playerId, componentId, pieceLoc, type);
}
//-------------------------------------------------------------------------
}
| 6,290 | 26.233766 | 128 | java |
Ludii | Ludii-master/Core/src/other/state/owned/FlatVertexOnlyOwned.java | package other.state.owned;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import main.collections.FastTIntArrayList;
import other.location.FlatVertexOnlyLocation;
import other.state.OwnedIndexMapper;
/**
* A version of Owned for games that only use Vertices and no levels
*
* @author Dennis Soemers
*/
public final class FlatVertexOnlyOwned implements Owned, Serializable
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* All the sites where is a piece owned by a player. PlayerId
* --> ComponentId --> Sites.
*/
protected final FastTIntArrayList[][] locations;
/** Our index mapper */
protected final OwnedIndexMapper indexMapper;
//-------------------------------------------------------------------------
/**
* To init the positions of the owned site
*
* @param game
*/
public FlatVertexOnlyOwned(final Game game)
{
indexMapper = new OwnedIndexMapper(game);
locations = new FastTIntArrayList[game.players().size() + 1][];
for (int p = 0; p <= game.players().size(); p++)
{
locations[p] = new FastTIntArrayList[indexMapper.numValidIndices(p)];
for (int i = 0; i < locations[p].length; i++)
{
locations[p][i] = new FastTIntArrayList();
}
}
}
/**
* Copy Constructor.
*
* @param other
*/
private FlatVertexOnlyOwned(final FlatVertexOnlyOwned other)
{
// We can simply copy the reference for this one
this.indexMapper = other.indexMapper;
// Need deep copies here
this.locations = new FastTIntArrayList[other.locations.length][];
for (int p = 0; p < other.locations.length; ++p)
{
this.locations[p] = new FastTIntArrayList[other.locations[p].length];
for (int i = 0; i < other.locations[p].length; ++i)
{
this.locations[p][i] = new FastTIntArrayList(other.locations[p][i]);
}
}
}
@Override
public FlatVertexOnlyOwned copy()
{
return new FlatVertexOnlyOwned(this);
}
//-------------------------------------------------------------------------
@Override
public int mapCompIndex(final int playerId, final int componentId)
{
return indexMapper.compIndex(playerId, componentId);
}
@Override
public int reverseMap(final int playerId, final int mappedIndex)
{
return indexMapper.reverseMap(playerId, mappedIndex);
}
@Override
public TIntArrayList levels(final int playerId, final int componentId, final int site)
{
throw new UnsupportedOperationException();
}
@Override
public FastTIntArrayList sites(final int playerId, final int componentId)
{
final int mappedIdx = indexMapper.compIndex(playerId, componentId);
if (mappedIdx >= 0)
return new FastTIntArrayList(locations[playerId][mappedIdx]);
else
return new FastTIntArrayList();
}
@Override
public TIntArrayList sites(final int playerId)
{
final TIntArrayList sites = new TIntArrayList();
for (int i = 0; i < locations[playerId].length; i++)
{
// Note: we do no contains() checks because, in non-stacking games,
// the same site should never occur more than once anyway
sites.addAll(locations[playerId][i]);
}
return sites;
}
@Override
public TIntArrayList sitesOnTop(final int playerId)
{
return sites(playerId);
}
@Override
public List<FlatVertexOnlyLocation> positions(final int playerId, final int componentId)
{
final int indexMapped = indexMapper.compIndex(playerId, componentId);
if (indexMapped < 0)
return new ArrayList<FlatVertexOnlyLocation>();
final TIntArrayList sites = locations[playerId][indexMapped];
final List<FlatVertexOnlyLocation> locs = new ArrayList<FlatVertexOnlyLocation>(sites.size());
for (int i = 0; i < sites.size(); ++i)
{
locs.add(new FlatVertexOnlyLocation(sites.getQuick(i)));
}
return locs;
}
@Override
public List<FlatVertexOnlyLocation>[] positions(final int playerId)
{
final TIntArrayList[] playerSites = locations[playerId];
@SuppressWarnings("unchecked")
final List<FlatVertexOnlyLocation>[] playerLocs = (List<FlatVertexOnlyLocation>[]) new List<?>[playerSites.length];
for (int i = 0; i < playerSites.length; ++i)
{
final TIntArrayList sites = locations[playerId][i];
if (sites == null)
{
playerLocs[i] = null;
}
else
{
final List<FlatVertexOnlyLocation> locs = new ArrayList<FlatVertexOnlyLocation>(sites.size());
for (int j = 0; j < sites.size(); ++j)
{
locs.add(new FlatVertexOnlyLocation(sites.getQuick(j)));
}
playerLocs[i] = locs;
}
}
return playerLocs;
}
//-------------------------------------------------------------------------
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
final FastTIntArrayList compPositions = locations[playerId][indexMapper.compIndex(playerId, componentId)];
// Since order doesn't matter, we'll do a remove-swap
final int idx = compPositions.indexOf(pieceLoc);
if (idx >= 0)
{
final int lastIdx = compPositions.size() - 1;
compPositions.set(idx, compPositions.getQuick(lastIdx));
compPositions.removeAt(lastIdx);
}
}
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (level == 0);
remove(playerId, componentId, pieceLoc, type);
}
@Override
public void removeNoUpdate(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (level == 0);
remove(playerId, componentId, pieceLoc, type);
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
assert (type == SiteType.Vertex);
locations[playerId][indexMapper.compIndex(playerId, componentId)].add(pieceLoc);
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (type == SiteType.Vertex);
assert (level == 0);
add(playerId, componentId, pieceLoc, type);
}
//-------------------------------------------------------------------------
}
| 6,345 | 26.471861 | 128 | java |
Ludii | Ludii-master/Core/src/other/state/owned/FlatVertexOnlyOwnedSingleComp.java | package other.state.owned;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import main.collections.FastTIntArrayList;
import other.location.FlatVertexOnlyLocation;
import other.state.OwnedIndexMapper;
/**
* A version of Owned for games that only use Vertices, and no levels,
* and at most one component ID per player
*
* @author Dennis Soemers
*/
public final class FlatVertexOnlyOwnedSingleComp implements Owned, Serializable
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* All the sites where is a piece owned by a player. PlayerId --> Sites
* (we skip the component ID that is normally the second index).
*/
protected final FastTIntArrayList[] locations;
/** Our index mapper */
protected final OwnedIndexMapper indexMapper;
//-------------------------------------------------------------------------
/**
* To init the positions of the owned site
*
* @param game
*/
public FlatVertexOnlyOwnedSingleComp(final Game game)
{
indexMapper = new OwnedIndexMapper(game);
locations = new FastTIntArrayList[game.players().size() + 1];
for (int p = 0; p <= game.players().size(); p++)
{
assert (indexMapper.numValidIndices(p) <= 1);
locations[p] = new FastTIntArrayList();
}
}
/**
* Copy Constructor.
*
* @param other
*/
private FlatVertexOnlyOwnedSingleComp(final FlatVertexOnlyOwnedSingleComp other)
{
// We can simply copy the reference for this one
this.indexMapper = other.indexMapper;
// Need deep copies here
this.locations = new FastTIntArrayList[other.locations.length];
for (int p = 0; p < other.locations.length; ++p)
{
this.locations[p] = new FastTIntArrayList(other.locations[p]);
}
}
@Override
public FlatVertexOnlyOwnedSingleComp copy()
{
return new FlatVertexOnlyOwnedSingleComp(this);
}
//-------------------------------------------------------------------------
@Override
public int mapCompIndex(final int playerId, final int componentId)
{
return indexMapper.compIndex(playerId, componentId);
}
@Override
public int reverseMap(final int playerId, final int mappedIndex)
{
return indexMapper.reverseMap(playerId, mappedIndex);
}
@Override
public TIntArrayList levels(final int playerId, final int componentId, final int site)
{
throw new UnsupportedOperationException();
}
@Override
public FastTIntArrayList sites(final int playerId, final int componentId)
{
final int mappedIdx = indexMapper.compIndex(playerId, componentId);
if (mappedIdx >= 0)
return new FastTIntArrayList(locations[playerId]);
else
return new FastTIntArrayList();
}
@Override
public TIntArrayList sites(final int playerId)
{
return new TIntArrayList(locations[playerId]);
}
@Override
public TIntArrayList sitesOnTop(final int playerId)
{
return sites(playerId);
}
@Override
public List<FlatVertexOnlyLocation> positions(final int playerId, final int componentId)
{
final int indexMapped = indexMapper.compIndex(playerId, componentId);
if (indexMapped < 0)
return new ArrayList<FlatVertexOnlyLocation>();
final TIntArrayList sites = locations[playerId];
final List<FlatVertexOnlyLocation> locs = new ArrayList<FlatVertexOnlyLocation>(sites.size());
for (int i = 0; i < sites.size(); ++i)
{
locs.add(new FlatVertexOnlyLocation(sites.getQuick(i)));
}
return locs;
}
@Override
public List<FlatVertexOnlyLocation>[] positions(final int playerId)
{
@SuppressWarnings("unchecked")
final List<FlatVertexOnlyLocation>[] playerLocs = (List<FlatVertexOnlyLocation>[]) new List<?>[1];
final TIntArrayList sites = locations[playerId];
final List<FlatVertexOnlyLocation> locs = new ArrayList<FlatVertexOnlyLocation>(sites.size());
for (int j = 0; j < sites.size(); ++j)
{
locs.add(new FlatVertexOnlyLocation(sites.getQuick(j)));
}
playerLocs[0] = locs;
return playerLocs;
}
//-------------------------------------------------------------------------
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
final FastTIntArrayList compPositions = locations[playerId];
// Since order doesn't matter, we'll do a remove-swap
final int idx = compPositions.indexOf(pieceLoc);
if (idx >= 0)
{
final int lastIdx = compPositions.size() - 1;
compPositions.set(idx, compPositions.getQuick(lastIdx));
compPositions.removeAt(lastIdx);
}
}
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (level == 0);
remove(playerId, componentId, pieceLoc, type);
}
@Override
public void removeNoUpdate(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (level == 0);
remove(playerId, componentId, pieceLoc, type);
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
assert (type == SiteType.Vertex);
assert (indexMapper.compIndex(playerId, componentId) == 0);
locations[playerId].add(pieceLoc);
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
assert (type == SiteType.Vertex);
assert (level == 0);
add(playerId, componentId, pieceLoc, type);
}
//-------------------------------------------------------------------------
}
| 5,712 | 26.73301 | 128 | java |
Ludii | Ludii-master/Core/src/other/state/owned/FullOwned.java | package other.state.owned;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import other.location.FullLocation;
import other.location.Location;
import other.state.OwnedIndexMapper;
/**
* A "Full" version of Owned, with all the data we could ever need (no optimisations)
*
* @author Dennis Soemers
*/
public final class FullOwned implements Owned, Serializable
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* All the positions (site & level) where is a piece owned by a player. PlayerId
* --> ComponentId --> Positions.
*/
protected final List<FullLocation>[][] locations;
/** Our index mapper */
protected final OwnedIndexMapper indexMapper;
//-------------------------------------------------------------------------
/**
* To init the positions of the owned site
*
* @param game
*/
@SuppressWarnings("unchecked")
public FullOwned(final Game game)
{
indexMapper = new OwnedIndexMapper(game);
locations = (List<FullLocation>[][]) new List<?>[game.players().size() + 1][];
for (int p = 0; p <= game.players().size(); p++)
{
locations[p] = (List<FullLocation>[]) new List<?>[indexMapper.numValidIndices(p)];
for (int i = 0; i < locations[p].length; i++)
{
locations[p][i] = new ArrayList<FullLocation>();
}
}
}
/**
* Copy Constructor.
*
* @param other
*/
@SuppressWarnings("unchecked")
private FullOwned(final FullOwned other)
{
// We can simply copy the reference for this one
this.indexMapper = other.indexMapper;
// Need deep copies here
this.locations = (List<FullLocation>[][]) new List<?>[other.locations.length][];
for (int p = 0; p < other.locations.length; ++p)
{
this.locations[p] = (List<FullLocation>[]) new List<?>[other.locations[p].length];
for (int i = 0; i < other.locations[p].length; ++i)
{
final List<FullLocation> otherPositionsComp = other.locations[p][i];
final List<FullLocation> newPositionsComp = new ArrayList<FullLocation>(otherPositionsComp.size());
for (int k = 0; k < otherPositionsComp.size(); ++k)
{
newPositionsComp.add((FullLocation) otherPositionsComp.get(k).copy());
}
this.locations[p][i] = newPositionsComp;
}
}
}
@Override
public Owned copy()
{
return new FullOwned(this);
}
//-------------------------------------------------------------------------
@Override
public int mapCompIndex(final int playerId, final int componentId)
{
return indexMapper.compIndex(playerId, componentId);
}
@Override
public int reverseMap(final int playerId, final int mappedIndex)
{
return indexMapper.reverseMap(playerId, mappedIndex);
}
@Override
public TIntArrayList levels(final int playerId, final int componentId, final int site)
{
final TIntArrayList levels = new TIntArrayList();
final int compIndex = indexMapper.compIndex(playerId, componentId);
if (compIndex >= 0)
{
final List<FullLocation> locs = locations[playerId][compIndex];
for (final Location pos : locs)
{
if (pos.site() == site)
{
levels.add(pos.level());
}
}
}
return levels;
}
@Override
public TIntArrayList sites(final int playerId, final int componentId)
{
final TIntArrayList sites = new TIntArrayList();
final int compIndex = indexMapper.compIndex(playerId, componentId);
if (compIndex >= 0)
{
final List<FullLocation> locs = locations[playerId][compIndex];
for (final Location loc : locs)
{
if (!sites.contains(loc.site()))
sites.add(loc.site());
}
}
return sites;
}
@Override
public TIntArrayList sites(final int playerId)
{
final TIntArrayList sites = new TIntArrayList();
for (int i = 0; i < locations[playerId].length; i++)
{
final List<FullLocation> locs = locations[playerId][i];
for (final FullLocation loc : locs)
{
if (!sites.contains(loc.site()))
sites.add(loc.site());
}
}
return sites;
}
@Override
public TIntArrayList sitesOnTop(final int playerId)
{
final TIntArrayList sites = new TIntArrayList();
for (int i = 0; i < locations[playerId].length; i++)
{
final List<FullLocation> locs = locations[playerId][i];
for (final FullLocation loc : locs)
{
if (!sites.contains(loc.site()))
sites.add(loc.site());
}
}
return sites;
}
@Override
public List<FullLocation> positions(final int playerId, final int componentId)
{
final int indexMapped = indexMapper.compIndex(playerId, componentId);
if (indexMapped < 0)
return new ArrayList<FullLocation>();
return locations[playerId][indexMapped];
}
@Override
public List<FullLocation>[] positions(final int playerId)
{
return locations[playerId];
}
//-------------------------------------------------------------------------
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
final List<FullLocation> compPositions = locations[playerId][indexMapper.compIndex(playerId, componentId)];
for (int i = 0; i < compPositions.size(); /** */)
{
if (compPositions.get(i).site() == pieceLoc
&& (type == null || compPositions.get(i).siteType().equals(type)))
{
compPositions.remove(i);
}
else
{
++i;
}
}
}
@Override
public void remove(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
final List<FullLocation> locs = locations[playerId][indexMapper.compIndex(playerId, componentId)];
for (int i = 0; i < locs.size(); i++)
{
if
(
locs.get(i).site() == pieceLoc
&&
locs.get(i).level() == level
&& (type == null || locs.get(i).siteType().equals(type))
)
{
locs.remove(i);
i--;
}
}
for (int idPlayer = 0; idPlayer < locations.length; idPlayer++)
{
for (int i = 0; i < locations[idPlayer].length; i++)
{
for (int idPos = 0; idPos < locations[idPlayer][i].size(); idPos++)
{
final int sitePos = locations[idPlayer][i].get(idPos).site();
final int levelPos = locations[idPlayer][i].get(idPos).level();
if (sitePos == pieceLoc && levelPos > level
&& (type == null || i >= locs.size() || locations[idPlayer][i].get(idPos).siteType().equals(type)))
{
locations[idPlayer][i].get(idPos).decrementLevel();
}
}
}
}
}
@Override
public void removeNoUpdate(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
final List<FullLocation> locs = locations[playerId][indexMapper.compIndex(playerId, componentId)];
for (int i = 0; i < locs.size(); i++)
{
if
(
locs.get(i).site() == pieceLoc
&&
locs.get(i).level() == level
&& (type == null || locs.get(i).siteType().equals(type))
)
{
locs.remove(i);
i--;
}
}
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final SiteType type)
{
locations[playerId][indexMapper.compIndex(playerId, componentId)].add(new FullLocation(pieceLoc, type));
}
@Override
public void add(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type)
{
locations[playerId][indexMapper.compIndex(playerId, componentId)].add(new FullLocation(pieceLoc, level, type));
}
//-------------------------------------------------------------------------
}
| 7,649 | 25.19863 | 128 | java |
Ludii | Ludii-master/Core/src/other/state/owned/Owned.java | package other.state.owned;
import java.util.List;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import other.location.Location;
/**
* Interface for objects that can quickly tell us which location contain
* pieces (of certain types) for certain players (without requiring full
* scans of the containers).
*
* @author Eric.Piette and Dennis Soemers
*/
public interface Owned
{
//-------------------------------------------------------------------------
/**
* @return A deep copy of this Owned object.
*/
public Owned copy();
//-------------------------------------------------------------------------
/**
* @param playerId
* @param componentId
* @return Mapped index that this Owned object would use instead of componentId (for given player)
*/
public int mapCompIndex(final int playerId, final int componentId);
/**
* @param playerId
* @param mappedIndex
* @return Reverses a given mapped index back into a component ID (for given player ID)
*/
public int reverseMap(final int playerId, final int mappedIndex);
/**
* @param playerId
* @param componentId
* @param site
* @return All the levels on the site owned by the playerId with the
* componentId.
*/
public TIntArrayList levels(final int playerId, final int componentId, final int site);
/**
* @param playerId
* @param componentId
* @return All the sites with at least one specific component owned by the
* player.
*/
public TIntArrayList sites(final int playerId, final int componentId);
/**
* @param playerId
* @return All the sites with at least one component owned by the player.
*/
public TIntArrayList sites(final int playerId);
/**
* @param playerId
* @return All the sites owned by a player, only if the top component is owned
* by him.
*/
public TIntArrayList sitesOnTop(final int playerId);
/**
* @param playerId
* @param componentId
* @return All the positions owned by the playerId with the componentId.
*/
public List<? extends Location> positions(final int playerId, final int componentId);
/**
* WARNING: the returned array is not indexed directly by component indices, but
* by mapped component indices!
*
* @param playerId
* @return All the positions of all the component owned by the player
*/
public List<? extends Location>[] positions(final int playerId);
//-------------------------------------------------------------------------
/**
* To remove a loc (at any level) for a player and a specific component.
*
* @param playerId
* @param componentId
* @param pieceLoc
* @param type
*/
public void remove(final int playerId, final int componentId, final int pieceLoc, final SiteType type);
/**
* To remove a loc at a specific level for a player and a specific component.
*
* @param playerId
* @param componentId
* @param pieceLoc
* @param level
* @param type
*/
public void remove(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type);
/**
* To remove a loc at a specific level for a player and a specific component without to decrement the higher levels.
*
* @param playerId
* @param componentId
* @param pieceLoc
* @param level
* @param type
*/
public void removeNoUpdate(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type);
/**
* To add a loc for a player with a component (at level 0)
*
* @param playerId
* @param componentId
* @param pieceLoc
* @param type
*/
public void add(final int playerId, final int componentId, final int pieceLoc, final SiteType type);
/**
* To add a loc for a player with a component at a specific level.
*
* @param playerId
* @param componentId
* @param pieceLoc
* @param level
* @param type
*/
public void add(final int playerId, final int componentId, final int pieceLoc, final int level, final SiteType type);
//-------------------------------------------------------------------------
} | 4,071 | 27.082759 | 129 | java |
Ludii | Ludii-master/Core/src/other/state/owned/OwnedFactory.java | package other.state.owned;
import game.Game;
import game.equipment.component.Component;
import game.types.state.GameType;
/**
* Factory to instantiate appropriate "Owned" containers for a given
* game's states.
*
* @author Dennis Soemers
*/
public final class OwnedFactory
{
//-------------------------------------------------------------------------
/**
* Constructor
*/
private OwnedFactory()
{
// Do not instantiate
}
//-------------------------------------------------------------------------
/**
* @param game
* @return Owned object created for given game
*/
public static Owned createOwned(final Game game)
{
final long gameFlags = game.gameFlags();
if
(
(gameFlags & GameType.Cell) != 0L &&
(gameFlags & GameType.Edge) == 0L &&
(gameFlags & GameType.Vertex) == 0L
)
{
// We only use Cells, no other site types
if (game.isStacking())
return new CellOnlyOwned(game);
else
return new FlatCellOnlyOwned(game);
}
else if
(
(gameFlags & GameType.Cell) == 0L &&
(gameFlags & GameType.Edge) == 0L &&
(gameFlags & GameType.Vertex) != 0L
)
{
// We only use Vertices, no other site types
if (!game.isStacking())
{
boolean maxOneCompPerPlayer = true;
final Component[] components = game.equipment().components();
for (int p = 0; p < game.players().count() + 2; ++p)
{
int numComps = 0;
for (int e = 0; e < components.length; ++e)
{
final Component comp = components[e];
if (comp != null && comp.owner() == p)
numComps++;
}
if (numComps > 1)
{
maxOneCompPerPlayer = false;
break;
}
}
if (maxOneCompPerPlayer)
return new FlatVertexOnlyOwnedSingleComp(game);
else
return new FlatVertexOnlyOwned(game);
}
}
// Default to all the data we might ever need
return new FullOwned(game);
}
//-------------------------------------------------------------------------
}
| 2,004 | 20.105263 | 76 | java |
Ludii | Ludii-master/Core/src/other/state/puzzle/BaseContainerStateDeductionPuzzles.java | package other.state.puzzle;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.util.equipment.Region;
import main.collections.ChunkSet;
import other.Sites;
import other.state.State;
import other.state.container.ContainerState;
/**
* Global State for a container item.
*
* @author cambolbro and mrraow
*/
public abstract class BaseContainerStateDeductionPuzzles implements ContainerState
{
private static final long serialVersionUID = 1L;
/** Reference to corresponding source container. */
private transient Container container;
/**
* Name of container. Often actually left at null, only need it when reading
* item states from files.
*/
private transient String nameFromFile = null;
/** Offset for this state's container */
protected final int offset;
//-------------------------------------------------------------------------
/** Which slots are empty. */
private final Region empty;
/**
* Constructor.
* @param game
* @param container
* @param numSites
*/
public BaseContainerStateDeductionPuzzles(final Game game, final Container container, final int numSites)
{
this.container = container;
this.empty = new Region(numSites);
this.offset = game.equipment().sitesFrom()[container.index()];
}
/**
* Copy constructor.
*
* @param other
*/
public BaseContainerStateDeductionPuzzles(final BaseContainerStateDeductionPuzzles other)
{
container = other.container;
empty = new Region(other.empty);
this.offset = other.offset;
}
//-------------------------------------------------------------------------
/**
* Reset this state.
*/
@Override
public void reset (final State trialState, final Game game)
{
final int numSites = container.numSites();
empty.set(numSites);
}
//-------------------------------------------------------------------------
@Override
public String nameFromFile()
{
return nameFromFile;
}
@Override
public Container container()
{
return container;
}
@Override
public void setContainer(final Container cont)
{
container = cont;
}
//-------------------------------------------------------------------------
@Override
public Sites emptySites()
{
return new Sites(empty.sites());
}
@Override
public int numEmpty()
{
return empty.count();
}
@Override
public Region emptyRegion(final SiteType type)
{
return empty;
}
@Override
public void addToEmptyCell (final int site)
{
empty.add(site - offset);
}
@Override
public void removeFromEmptyCell (final int site)
{
empty.remove(site - offset);
}
//-------------------------------------------------------------------------
/**
* Serializes the ItemState
* @param out
* @throws IOException
*/
private void writeObject(final ObjectOutputStream out) throws IOException
{
// Use default writer to write all fields of subclasses, like ChunkSets
// this will not include our container, because it's transient
out.defaultWriteObject();
// now write just the name of the container
out.writeUTF(container.name());
}
/**
* Deserializes the ItemState
* @param in
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(final ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// Use default reader to read all fields of subclasses, like ChunkSets
// This will not include our container, because it's transient
in.defaultReadObject();
// now read the name of our container
nameFromFile = in.readUTF();
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (empty.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (!(obj instanceof BaseContainerStateDeductionPuzzles))
return false;
final BaseContainerStateDeductionPuzzles other = (BaseContainerStateDeductionPuzzles) obj;
if (!empty.equals(other.empty))
return false;
return true;
}
@Override
public int stateCell(final int site)
{
return 0;
}
@Override
public int rotationCell(final int site)
{
return 0;
}
@Override
public boolean isPlayable(final int site)
{
throw new UnsupportedOperationException ("Not supported for puzzles");
}
@Override
public boolean isOccupied(final int site)
{
throw new UnsupportedOperationException ("Not supported for puzzles");
}
@Override
public void setSite(State trialState, int site, int who, int what, int count, int state, int rotation,
final int valueVal,
final SiteType type)
{
throw new UnsupportedOperationException ("Not supported for puzzles");
}
//-------------------------------------------------------------------------
/**
* @param var
* @return Number of edges for this "edge" on the graph.
*/
public abstract int numberEdge(final int var);
/**
* Sets all values for the specified variable to "true".
* @param type
* @param var
* @param numValues
*/
public abstract void resetVariable(final SiteType type, final int var, final int numValues);
/**
* @param var
* @param type
* @return The correct resolved method according to the type.
*/
@Override
public boolean isResolved(final int var, final SiteType type)
{
if (type == SiteType.Cell)
return isResolvedCell(var);
else if (type == SiteType.Vertex)
return isResolvedVerts(var);
else
return isResolvedEdges(var);
}
//----------------------------Vertex--------------------------------------
@Override
public boolean bit(final int var, final int value, final SiteType type)
{
if (type == SiteType.Cell)
return bitCell(var, value);
else if (type == SiteType.Vertex)
return bitVert(var, value);
else
return bitEdge(var, value);
}
@Override
public void set(final int var, final int value, final SiteType type)
{
if (type == SiteType.Cell)
setCell(var, value);
else if (type == SiteType.Vertex)
setVert(var, value);
else
setEdge(var, value);
}
/**
*
* @param var
* @param value
* @return if the value for the vert is possible
*/
public abstract boolean bitVert(final int var, final int value);
/**
* @param var
* @param value
* Set a value to the variable for the vert.
*/
public abstract void setVert(final int var, final int value);
/**
* @param var
* @param value
* Toggle a value to the variable for the cell.
*/
public abstract void toggleVerts(final int var, final int value);
/**
* @param var
* @return the assigned value for vertex
*/
@Override
public abstract int whatVertex(final int var);
//-------------------Edges----------------------------------------
/**
* @param var
* @return the assigned value for edge
*/
@Override
public abstract int whatEdge(final int var);
/**
*
* @param var
* @param value
* @return if the value for the edge is possible
*/
public abstract boolean bitEdge(final int var, final int value);
/**
* @param var
* @param value
* Set a value to the variable for the edge.
*/
public abstract void setEdge(final int var, final int value);
/**
* @param var
* @param value
* Toggle a value to the variable for the edge.
*/
public abstract void toggleEdges(final int var, final int value);
//---------------------Cells-----------------------------------------
/**
*
* @param var
* @param value
* @return if the value for the cell is possible
*/
public abstract boolean bitCell(final int var, final int value);
/**
* @param var
* @param value Set a value to the variable for the cell.
*/
public abstract void setCell(final int var, final int value);
/**
* @param var
* @param value Toggle a value to the variable for the cell.
*/
public abstract void toggleCells(final int var, final int value);
//-------------------------------------------------------------------------
@Override
public int what(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whatCell(site);
else if (graphElementType == SiteType.Edge)
return whatEdge(site);
else
return whatVertex(site);
}
@Override
public int who(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whoCell(site);
else if (graphElementType == SiteType.Edge)
return whoEdge(site);
else
return whoVertex(site);
}
@Override
public int count(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return countCell(site);
else if (graphElementType == SiteType.Edge)
return countEdge(site);
else
return countVertex(site);
}
@Override
public int sizeStack(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return sizeStackCell(site);
else if (graphElementType == SiteType.Edge)
return whatEdge(site) == 0 ? 0 : 1;
else
return whatVertex(site) == 0 ? 0 : 1;
}
@Override
public int state(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return stateCell(site);
else if (graphElementType == SiteType.Edge)
return stateEdge(site);
else
return stateVertex(site);
}
@Override
public int rotation(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return rotationCell(site);
else if (graphElementType == SiteType.Edge)
return rotationEdge(site);
else
return rotationVertex(site);
}
@Override
public int what(final int site, final int level,
final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whatCell(site, level);
else if (graphElementType == SiteType.Edge)
return whatEdge(site);
else
return whatVertex(site);
}
@Override
public int who(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whoCell(site, level);
else if (graphElementType == SiteType.Edge)
return whoEdge(site);
else
return whoVertex(site);
}
@Override
public int state(final int site, final int level,
final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return stateCell(site, level);
else if (graphElementType == SiteType.Edge)
return stateEdge(site);
else
return stateVertex(site);
}
@Override
public int rotation(final int site, final int level,
final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return rotationCell(site, level);
else if (graphElementType == SiteType.Edge)
return rotationEdge(site);
else
return rotationVertex(site);
}
@Override
public int whatVertex(int site, int level)
{
return 0;
}
@Override
public int stateVertex(int site, int level)
{
return 0;
}
@Override
public int rotationVertex(int site, int level)
{
return 0;
}
@Override
public int whatEdge(int site, int level)
{
return 0;
}
@Override
public int stateEdge(int site, int level)
{
return 0;
}
@Override
public int rotationEdge(int site, int level)
{
return 0;
}
@Override
public boolean isHidden(final int player, final int site, final int level, final SiteType type)
{
return false;
}
@Override
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType type)
{
return false;
}
@Override
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType type)
{
return false;
}
@Override
public boolean isHiddenState(final int player, final int site, final int level, final SiteType type)
{
return false;
}
@Override
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType type)
{
return false;
}
@Override
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType type)
{
return false;
}
@Override
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType type)
{
return false;
}
@Override
public void setHidden(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
// Nothing to do.
}
@Override
public void setHiddenWhat(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
// Nothing to do.
}
@Override
public void setHiddenWho(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
// Nothing to do.
}
@Override
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
// Nothing to do.
}
@Override
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
// Nothing to do.
}
@Override
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
// Nothing to do.
}
@Override
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
// Nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game)
{
// nothing to do.
}
@Override
public void insertVertex(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game)
{
// nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// nothing to do.
}
@Override
public void removeStackVertex(State trialState, int site)
{
// nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game)
{
// nothing to do.
}
@Override
public void insertEdge(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game)
{
// nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// nothing to do.
}
@Override
public void removeStackEdge(State trialState, int site)
{
// nothing to do.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game,
SiteType graphElementType)
{
// Do nothing.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game, SiteType graphElementType)
{
// Do nothing.
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked, SiteType graphElementType)
{
// Do nothing.
}
@Override
public void removeStackGeneric(State trialState, int site, SiteType graphElementType)
{
// Do nothing.
}
@Override
public boolean isEmpty(final int site, final SiteType type)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
return isEmptyCell(site);
else if (type.equals(SiteType.Edge))
return isEmptyEdge(site);
else
return isEmptyVertex(site);
}
@Override
public boolean isEmptyVertex(final int vertex)
{
return true;
}
@Override
public boolean isEmptyEdge(final int edge)
{
return true;
}
@Override
public boolean isEmptyCell(final int site)
{
return empty.contains(site - offset);
}
@Override
public void addToEmpty(final int site, final SiteType graphType)
{
addToEmptyCell(site);
}
@Override
public void removeFromEmpty(final int site, final SiteType graphType)
{
removeFromEmptyCell(site);
}
@Override
public void addToEmptyVertex(final int site)
{
// Nothing to do.
}
@Override
public void removeFromEmptyVertex(final int site)
{
// Nothing to do.
}
@Override
public void addToEmptyEdge(final int site)
{
// Nothing to do.
}
@Override
public void removeFromEmptyEdge(final int site)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public int whoEdge(int site, int level)
{
return whoEdge(site);
}
@Override
public int whoEdge(int site)
{
return (whatEdge(site) != 0) ? 1 : 0;
}
@Override
public int countEdge(int site)
{
return (whatEdge(site) != 0) ? 1 : 0;
}
@Override
public int whoVertex(int site, int level)
{
return whoVertex(site);
}
@Override
public int whoVertex(int site)
{
return (whatVertex(site) != 0) ? 1 : 0;
}
@Override
public int countVertex(int site)
{
return (whatVertex(site) != 0) ? 1 : 0;
}
@Override
public int whoCell(int site, int level)
{
return whoCell(site);
}
@Override
public int whoCell(final int site)
{
return (whatCell(site) != 0) ? 1 : 0;
}
@Override
public int countCell(int site)
{
return (whatCell(site) != 0) ? 1 : 0;
}
//-------------------------------------------------------------------------
@Override public ChunkSet emptyChunkSetCell() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet emptyChunkSetVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet emptyChunkSetEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhoVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhoCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhoEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhoVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhoCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhoEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhatVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhatCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhatEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhatVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhatCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhatEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoVertex(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoCell(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoEdge(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatVertex(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatCell(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatEdge(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoVertex(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoCell(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoEdge(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatVertex(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatCell(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatEdge(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhoVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhoCell() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhoEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhatVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhatCell() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhatEdge() { throw new UnsupportedOperationException("TODO"); }
}
| 23,711 | 26.286536 | 157 | java |
Ludii | Ludii-master/Core/src/other/state/puzzle/ContainerDeductionPuzzleState.java | package other.state.puzzle;
import java.util.BitSet;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import main.math.BitTwiddling;
import other.context.Context;
import other.state.State;
import other.state.container.ContainerState;
import other.state.symmetry.SymmetryValidator;
import other.state.zhash.ZobristHashGenerator;
import other.trial.Trial;
/**
* The state for the deduction puzzle with a range of values under 32 for each
* graph element.
*
* @author Eric.Piette
*/
public class ContainerDeductionPuzzleState extends BaseContainerStateDeductionPuzzles
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The number of values of the vertices. */
protected int nbValuesVert = 1;
/** ChunkSet verts. */
protected ChunkSet verts;
/** ChunkSet edges. */
protected ChunkSet edges;
/** NbValues for edges */
protected int nbValuesEdge = 1;
/** ChunkSet cells. */
protected ChunkSet cells;
/** NbValues for cells */
protected int nbValuesCell = 1;
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param generator
* @param game
* @param container
*/
public ContainerDeductionPuzzleState(final ZobristHashGenerator generator, final Game game, final Container container)
{
super(game, container, game.equipment().totalDefaultSites());
final int numEdges = game.board().topology().edges().size();
final int numFaces = game.board().topology().cells().size();
final int numVertices = game.board().topology().vertices().size();
if (game.isDeductionPuzzle())
nbValuesVert = game.board().vertexRange().max(new Context(game, new Trial(game))) + 1;
else
nbValuesVert = 1;
if (game.isDeductionPuzzle())
nbValuesEdge = game.board().edgeRange().max(new Context(game, new Trial(game))) + 1;
else
nbValuesEdge = 1;
if (game.isDeductionPuzzle())
nbValuesCell = game.board().cellRange().max(new Context(game, new Trial(game))) + 1;
else
nbValuesCell = 1;
if ((nbValuesVert) <= 31 && nbValuesEdge <= 31 && nbValuesCell <= 31)
{
final int chunkSize = BitTwiddling.nextPowerOf2(nbValuesVert);
this.verts = new ChunkSet(chunkSize, numVertices);
for (int var = 0; var < numVertices; var++)
this.verts.setNBits(var, nbValuesVert, true);
final int chunkSizeEdge = BitTwiddling.nextPowerOf2(nbValuesEdge);
this.edges = new ChunkSet(chunkSizeEdge, numEdges);
for (int var = 0 ; var < numEdges ; var++)
this.edges.setNBits(var, nbValuesEdge, true);
final int chunkSizeFace = BitTwiddling.nextPowerOf2(nbValuesCell);
this.cells = new ChunkSet(chunkSizeFace,numFaces);
for (int i = 0 ; i < numFaces ; i ++)
this.cells.setNBits(i, nbValuesCell, true);
}
}
/**
* Copy constructor.
*
* @param other
*/
public ContainerDeductionPuzzleState(final ContainerDeductionPuzzleState other)
{
super(other);
nbValuesVert = other.nbValuesVert;
nbValuesEdge = other.nbValuesEdge;
nbValuesCell = other.nbValuesCell;
this.verts = (other.verts == null) ? null : (ChunkSet) other.verts.clone();
this.edges = (other.edges == null) ? null : (ChunkSet) other.edges.clone();
this.cells = (other.cells == null) ? null : (ChunkSet) other.cells.clone();
}
//-------------------------------------------------------------------------
@Override
public void reset(final State trialState, final Game game)
{
super.reset(trialState, game);
if (verts != null && edges != null && cells != null)
{
final int numEdges = game.board().topology().edges().size();
final int numCells = game.board().topology().cells().size();
final int numVertices = game.board().topology().vertices().size();
verts.clear();
for (int var = 0; var < numVertices; var++)
this.verts.setNBits(var, nbValuesVert, true);
edges.clear();
for (int var = 0 ; var < numEdges ; var++)
this.edges.setNBits(var, nbValuesEdge, true);
cells.clear();
for (int i = 0; i < numCells; i++)
this.cells.setNBits(i, nbValuesCell, true);
}
}
@Override
public int remove(final State state, final int site, final SiteType type)
{
return 0;
}
@Override
public int remove(final State state, final int site, final int level, final SiteType type)
{
return remove(state, site, type);
}
@Override
public ContainerState deepClone()
{
return new ContainerDeductionPuzzleState(this);
}
@Override
public int numberEdge(final int var)
{
for (int i = 0 ; i < nbValuesEdge ; i++)
if (bitEdge(var, i))
return i;
return 0;
}
@Override
public boolean isResolvedVerts(final int var)
{
return verts.isResolved(var);
}
@Override
public int whatVertex(final int var)
{
return verts.resolvedTo(var);
}
//-------------------------------------------------------------------------
@Override
public void resetVariable(final SiteType type, final int var, final int numValues)
{
switch (type)
{
case Vertex: verts.setNBits(var, numValues, true); break;
case Edge: edges.setNBits(var, numValues, true); break;
case Cell: cells.setNBits(var, numValues, true); break;
default:
verts.setNBits(var, numValues, true);
break;
}
}
//-------------------------------------------------------------------------
@Override
public BitSet values(final SiteType type, final int var)
{
final BitSet bs = new BitSet();
switch (type)
{
case Vertex:
{
final int values = verts.getChunk(var);
for (int n = 0; n < nbValuesVert; n++)
if ((values & (0x1 << n)) != 0)
bs.set(n, true);
}
break;
case Edge:
{
final int values = edges.getChunk(var);
for (int n = 0; n < nbValuesEdge; n++)
if ((values & (0x1 << n)) != 0)
bs.set(n, true);
}
break;
case Cell:
{
final int values = cells.getChunk(var);
for (int n = 0; n < nbValuesCell; n++)
if ((values & (0x1 << n)) != 0)
bs.set(n, true);
}
break;
default:
final int values = cells.getChunk(var);
for (int n = 0; n < nbValuesCell; n++)
if ((values & (0x1 << n)) != 0)
bs.set(n, true);
break;
}
return bs;
}
//-------------------------------------------------------------------------
@Override
public boolean bitVert(final int var, final int value)
{
return (verts.getBit(var, value) == 1);
}
@Override
public void setVert(final int var, final int value)
{
verts.resolveToBit(var, value);
}
@Override
public void toggleVerts(final int var, final int value)
{
verts.toggleBit(var, value);
}
//-------------------------------------------------------------------------
@Override
public boolean isResolvedEdges(final int var)
{
return edges.isResolved(var);
}
@Override
public int whatEdge(final int var)
{
return edges.resolvedTo(var);
}
@Override
public boolean bitEdge(final int var, final int value)
{
return (edges.getBit(var, value) == 1);
}
@Override
public void setEdge(final int var, final int value)
{
edges.resolveToBit(var, value);
}
@Override
public void toggleEdges(final int var, final int value)
{
edges.toggleBit(var, value);
}
//-------------------------------------------------------------------------
@Override
public boolean bitCell(final int var, final int value)
{
return (cells.getBit(var, value) == 1);
}
@Override
public void setCell(final int var, final int value)
{
cells.resolveToBit(var, value);
}
@Override
public void toggleCells(final int var, final int value)
{
cells.toggleBit(var, value);
}
@Override
public boolean isResolvedCell(final int var)
{
return cells.isResolved(var);
}
@Override
public int whatCell(final int var)
{
return cells.resolvedTo(var);
}
@Override
public void setPlayable(final State trialState, final int site, final boolean on)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public int sizeStackCell(final int var)
{
if (cells.isResolved(var))
return 1;
return 0;
}
@Override
public int sizeStackEdge(final int var)
{
if (edges.isResolved(var))
return 1;
return 0;
}
@Override
public int sizeStackVertex(final int var)
{
if (verts.isResolved(var))
return 1;
return 0;
}
@Override
public int stateEdge(int site)
{
return 0;
}
@Override
public int rotationEdge(int site)
{
return 0;
}
@Override
public int stateVertex(int site)
{
return 0;
}
@Override
public int rotationVertex(int site)
{
return 0;
}
@Override
public int valueCell(int site)
{
return 0;
}
@Override
public void setValueCell(final State trialState, final int site, final int valueVal)
{
// Nothing to do.
}
@Override
public void setCount(final State trialState, final int site, final int countVal)
{
// Nothing to do.
}
@Override
public void addItem(State trialState, int site, int what, int who, Game game)
{
// Nothing to do.
}
@Override
public void insert(State trialState, final SiteType type, int site, int level, int what, int who, final int state,
final int rotation, final int value, Game game)
{
// Nothing to do.
}
@Override
public void insertCell(State trialState, int site, int level, int what, int who, final int state, final int rotation,
final int value, Game game)
{
// Nothing to do.
}
@Override
public void addItem(State trialState, int site, int what, int who, int stateVal, int rotationVal, int valueVal,
Game game)
{
// Nothing to do.
}
@Override
public void addItem(State trialState, int site, int what, int who, Game game, boolean[] hidden,
final boolean masked)
{
// Nothing to do.
}
@Override
public void removeStack(State state, int site)
{
// Nothing to do.
}
@Override
public int whatCell(int site, int level)
{
return whatCell(site);
}
@Override
public int stateCell(int site, int level)
{
return stateCell(site);
}
@Override
public int rotationCell(int site, int level)
{
return rotationCell(site);
}
@Override
public int remove(State state, int site, int level)
{
return remove(state, site, SiteType.Cell);
}
@Override
public void setSite(State trialState, int site, int level, int whoVal, int whatVal, int countVal, int stateVal,
int rotationVal, int valueVal)
{
// do nothing
}
@Override
public long canonicalHash(SymmetryValidator validator, final State state, final boolean whoOnly)
{
return 0;
}
@Override
public int valueCell(int site, int level)
{
return 0;
}
@Override
public int valueVertex(int site)
{
return 0;
}
@Override
public int valueVertex(int site, int level)
{
return 0;
}
@Override
public int value(int site, SiteType graphElementType)
{
return 0;
}
@Override
public int value(int site, int level, SiteType graphElementType)
{
return 0;
}
@Override
public int valueEdge(int site)
{
return 0;
}
@Override
public int valueEdge(int site, int level)
{
return 0;
}
}
| 11,115 | 20.21374 | 119 | java |
Ludii | Ludii-master/Core/src/other/state/puzzle/ContainerDeductionPuzzleStateLarge.java | package other.state.puzzle;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import other.context.Context;
import other.state.State;
import other.state.container.ContainerState;
import other.state.zhash.ZobristHashGenerator;
import other.trial.Trial;
/**
* @author cambolbro and Eric.Piette
*/
public class ContainerDeductionPuzzleStateLarge extends ContainerDeductionPuzzleState
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Vertice. */
protected final List<BitSet> verticeList;
/** Edges. */
protected final List<BitSet> edgesList;
/** Cells. */
protected final List<BitSet> cellsList;
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param generator The generator.
* @param game The game.
* @param container The container.
*/
public ContainerDeductionPuzzleStateLarge(final ZobristHashGenerator generator, final Game game,
final Container container)
{
super(generator, game, container);
final int numEdges = game.board().topology().edges().size();
final int numCells = game.board().topology().cells().size();
final int numVertices = game.board().topology().vertices().size();
if (game.isDeductionPuzzle())
nbValuesVert = game.board().vertexRange().max(new Context(game, new Trial(game)))
- game.board().vertexRange().min(new Context(game, new Trial(game))) + 1;
else
nbValuesVert = 1;
if (game.isDeductionPuzzle())
nbValuesEdge = game.board().edgeRange().max(new Context(game, new Trial(game)))
- game.board().edgeRange().min(new Context(game, new Trial(game))) + 1;
else
nbValuesEdge = 1;
if (game.isDeductionPuzzle())
nbValuesCell = game.board().cellRange().max(new Context(game, new Trial(game)))
- game.board().cellRange().min(new Context(game, new Trial(game))) + 1;
else
nbValuesCell = 1;
verticeList = new ArrayList<BitSet>();
for (int var = 0; var < numVertices; var++)
{
final BitSet values = new BitSet(nbValuesVert);
values.set(0, nbValuesVert, true);
verticeList.add(values);
}
edgesList = new ArrayList<BitSet>();
for (int var = 0; var < numEdges; var++)
{
final BitSet values = new BitSet(nbValuesEdge);
values.set(0, nbValuesEdge, true);
edgesList.add(values);
}
cellsList = new ArrayList<BitSet>();
for (int var = 0; var < numCells; var++)
{
final BitSet values = new BitSet(nbValuesCell);
values.set(0, nbValuesCell, true);
cellsList.add(values);
}
}
/**
* Copy constructor.
*
* @param other
*/
public ContainerDeductionPuzzleStateLarge(final ContainerDeductionPuzzleStateLarge other)
{
super(other);
nbValuesVert = other.nbValuesVert;
nbValuesEdge = other.nbValuesEdge;
nbValuesCell = other.nbValuesCell;
if (other.verticeList == null)
verticeList = null;
else
{
verticeList = new ArrayList<BitSet>();
for (final BitSet bs : other.verticeList)
verticeList.add((BitSet)bs.clone());
}
if (other.edgesList == null)
edgesList = null;
else
{
edgesList = new ArrayList<BitSet>();
for (final BitSet bs : other.edgesList)
edgesList.add((BitSet)bs.clone());
}
if (other.cellsList == null)
cellsList = null;
else
{
cellsList = new ArrayList<BitSet>();
for (final BitSet bs : other.cellsList)
cellsList.add((BitSet)bs.clone());
}
}
//-------------------------------------------------------------------------
@Override
public void reset(final State trialState, final Game game)
{
super.reset(trialState, game);
if (verticeList != null)
for (final BitSet bs : verticeList)
bs.set(0, nbValuesVert, true);
if (edgesList != null)
for (final BitSet bs : edgesList)
bs.set(0, nbValuesEdge, true);
if (cellsList != null)
for (final BitSet bs : cellsList)
bs.set(0, nbValuesCell, true);
}
//-------------------------------------------------------------------------
@Override
public int remove(final State state, final int site, final SiteType type)
{
return 0;
}
@Override
public ContainerState deepClone()
{
return new ContainerDeductionPuzzleStateLarge(this);
}
@Override
public String nameFromFile()
{
return null;
}
//-------------------------------------------------------------------------
@Override
public int whoCell(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
/**
* @param var
* @return Number of edges for this "edge" on the graph.
*/
@Override
public int numberEdge(final int var)
{
for(int i = 0 ; i < nbValuesEdge ; i++)
if(bitEdge(var, i))
return i;
return 0;
}
/**
* @param var
* @return True if that vertex variable is resolved
*/
@Override
public boolean isResolvedVerts(final int var)
{
return verticeList.get(var - offset).cardinality() == 1;
}
/**
* @param var
* @return The assigned value for vertex, else 0 if not assigned yet.
*/
@Override
public int whatVertex(final int var)
{
final BitSet bs = verticeList.get(var - offset);
final int firstOnBit = bs.nextSetBit(0);
if (firstOnBit == -1)
{
System.out.println("** Unexpected empty variable.");
return 0;
}
if (bs.nextSetBit(firstOnBit + 1) == -1)
return firstOnBit;
else
return 0;
}
//-------------------------------------------------------------------------
/**
* Sets all values for the specified variable to "true".
* @param type
* @param var
* @param numValues
*/
@Override
public void resetVariable(final SiteType type, final int var, final int numValues)
{
switch (type)
{
case Vertex: verticeList.get(var - offset).set(0, nbValuesVert, true); break;
case Edge: edgesList.get(var).set(0, nbValuesEdge, true); break;
case Cell: cellsList.get(var).set(0, nbValuesCell, true); break;
default:
verticeList.get(var - offset).set(0, nbValuesVert, true);
break;
}
}
//-------------------------------------------------------------------------
/**
* @param type
* @param var
* @return Current values for the specified variable.
*/
@Override
public BitSet values(final SiteType type, final int var)
{
switch (type)
{
case Vertex: return verticeList.get(var - offset);
case Edge: return edgesList.get(var);
case Cell: return cellsList.get(var);
default:
return verticeList.get(var - offset);
}
}
//-------------------------------------------------------------------------
/**
*
* @param var
* @param value
* @return if the value for the vert is possible
*/
@Override
public boolean bitVert(final int var, final int value)
{
return verticeList.get(var - offset).get(value);
}
/**
* @param var
* @param value
* Set a value to the variable for the vert.
*/
@Override
public void setVert(final int var, final int value)
{
final BitSet bs = verticeList.get(var - offset);
bs.clear();
bs.set(value, true);
}
/**
* @param var
* @param value
* Toggle a value to the variable for the cell.
*/
@Override
public void toggleVerts(final int var, final int value)
{
verticeList.get(var - offset).flip(value);
}
//-------------------------------------------------------------------------
/**
* @param var
* @return True if that edge variable is resolved
*/
@Override
public boolean isResolvedEdges(final int var)
{
return edgesList.get(var).cardinality() == 1;
}
/**
* @param var
* @return the assigned value for edge
*/
@Override
public int whatEdge(final int var)
{
final BitSet bs = edgesList.get(var);
final int firstOnBit = bs.nextSetBit(0);
if (firstOnBit == -1)
{
System.out.println("** Unexpected empty variable.");
return 0;
}
if (bs.nextSetBit(firstOnBit+1) == -1)
return firstOnBit;
else
return 0;
}
/**
*
* @param var
* @param value
* @return if the value for the edge is possible
*/
@Override
public boolean bitEdge(final int var, final int value)
{
return edgesList.get(var).get(value);
}
/**
* @param var
* @param value
* Set a value to the variable for the edge.
*/
@Override
public void setEdge(final int var, final int value)
{
final BitSet bs = edgesList.get(var);
bs.clear();
bs.set(value, true);
}
/**
* @param var
* @param value
* Toggle a value to the variable for the edge.
*/
@Override
public void toggleEdges(final int var, final int value)
{
edgesList.get(var).flip(value);
}
//-------------------------------------------------------------------------
/**
*
* @param var
* @param value
* @return if the value for the face is possible
*/
@Override
public boolean bitCell(final int var, final int value)
{
return cellsList.get(var).get(value);
}
/**
* @param var
* @param value
* Set a value to the variable for the face.
*/
@Override
public void setCell(final int var, final int value)
{
final BitSet bs = cellsList.get(var);
bs.clear();
bs.set(value, true);
}
/**
* @param var
* @param value
* Toggle a value to the variable for the face.
*/
@Override
public void toggleCells(final int var, final int value)
{
cellsList.get(var).flip(value);
}
/**
* @param var
* @return True if that variable is resolved
*/
@Override
public boolean isResolvedCell(final int var)
{
return cellsList.get(var).cardinality() == 1;
}
/**
* @param var
* @return the assigned value for face
*/
@Override
public int whatCell(final int var)
{
final BitSet bs = cellsList.get(var);
final int firstOnBit = bs.nextSetBit(0);
if (firstOnBit == -1)
{
System.out.println("** Unexpected empty variable.");
return 0;
}
if (bs.nextSetBit(firstOnBit+1) == -1)
return firstOnBit;
else
return 0;
}
} | 9,962 | 21.090909 | 97 | java |
Ludii | Ludii-master/Core/src/other/state/stacking/BaseContainerStateStacking.java | package other.state.stacking;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import other.state.State;
import other.state.container.BaseContainerState;
/**
* Global State for a stacking container item.
*
* @author Eric.Piette
*/
public abstract class BaseContainerStateStacking extends BaseContainerState
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The base container stack for a stacking container.
*
* @param game The game.
* @param container The container.
* @param numSites The number of sites.
*/
public BaseContainerStateStacking(final Game game, final Container container, final int numSites)
{
super(game, container, numSites);
}
/**
* Copy constructor.
*
* @param other The object to copy.
*/
public BaseContainerStateStacking(final BaseContainerStateStacking other)
{
super(other);
}
@Override
public int what(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whatCell(site);
else if (graphElementType == SiteType.Edge)
return whatEdge(site);
else
return whatVertex(site);
}
@Override
public int who(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whoCell(site);
else if (graphElementType == SiteType.Edge)
return whoEdge(site);
else
return whoVertex(site);
}
@Override
public int count(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return countCell(site);
else if (graphElementType == SiteType.Edge)
return countEdge(site);
else
return countVertex(site);
}
@Override
public int sizeStack(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return sizeStackCell(site);
else if (graphElementType == SiteType.Edge)
return sizeStackEdge(site);
else
return sizeStackVertex(site);
}
@Override
public int state(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return stateCell(site);
else if (graphElementType == SiteType.Edge)
return stateEdge(site);
else
return stateVertex(site);
}
//-----------------METHODS USING LEVEL--------------------------------------
@Override
public int what(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whatCell(site, level);
else if (graphElementType == SiteType.Edge)
return whatEdge(site, level);
else
return whatVertex(site, level);
}
@Override
public int who(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return whoCell(site, level);
else if (graphElementType == SiteType.Edge)
return whoEdge(site, level);
else
return whoVertex(site, level);
}
@Override
public int state(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return stateCell(site, level);
else if (graphElementType == SiteType.Edge)
return stateEdge(site, level);
else
return stateVertex(site, level);
}
@Override
public int rotation(final int site, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return rotationCell(site);
else if (graphElementType == SiteType.Edge)
return rotationEdge(site);
else
return rotationVertex(site);
}
@Override
public int rotation(final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return rotationCell(site, level);
else if (graphElementType == SiteType.Edge)
return rotationEdge(site, level);
else
return rotationVertex(site, level);
}
@Override
public boolean isEmpty(final int site, final SiteType type)
{
if (type == SiteType.Cell || container().index() != 0 || type == null)
return isEmptyCell(site);
else if (type.equals(SiteType.Edge))
return isEmptyEdge(site);
else
return isEmptyVertex(site);
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game,
final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
addItem(trialState, site, whatValue, whoId, game);
else if (graphElementType == SiteType.Vertex)
addItemVertex(trialState, site, whatValue, whoId, game);
else
addItemEdge(trialState, site, whatValue, whoId, game);
}
@Override
public void addItemGeneric(final State trialState, final int site, final int what, final int who,
final int stateVal, final int rotationVal, int valueVal, final Game game, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
addItem(trialState, site, what, who, stateVal, rotationVal, valueVal, game);
else if (graphElementType == SiteType.Vertex)
addItemVertex(trialState, site, what, who, stateVal, rotationVal, valueVal, game);
else
addItemEdge(trialState, site, what, who, stateVal, rotationVal, valueVal, game);
}
@Override
public void addItemGeneric(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked, SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
addItem(trialState, site, whatValue, whoId, game, hiddenValues, masked);
else if (graphElementType == SiteType.Vertex)
addItemVertex(trialState, site, whatValue, whoId, game, hiddenValues, masked);
else
addItemEdge(trialState, site, whatValue, whoId, game, hiddenValues, masked);
}
@Override
public void removeStackGeneric(State trialState, int site, SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
removeStack(trialState, site);
else if (graphElementType == SiteType.Vertex)
removeStackVertex(trialState, site);
else
removeStackEdge(trialState, site);
}
@Override
public boolean isEmptyVertex(final int vertex)
{
return true;
}
@Override
public boolean isEmptyEdge(final int edge)
{
return true;
}
@Override
public boolean isEmptyCell(final int site)
{
return empty.contains(site - offset);
}
}
| 7,041 | 29.617391 | 116 | java |
Ludii | Ludii-master/Core/src/other/state/stacking/ContainerGraphStateStacks.java | package other.state.stacking;
import java.util.Arrays;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.equipment.Region;
import main.Constants;
import other.state.State;
import other.state.zhash.HashedBitSet;
import other.state.zhash.HashedChunkStack;
import other.state.zhash.ZobristHashGenerator;
import other.state.zhash.ZobristHashUtilities;
import other.topology.Vertex;
/**
* Container state for stacks in the vertices or in the edges.
*
* @author Eric.Piette
*/
public class ContainerGraphStateStacks extends ContainerStateStacks
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The stacks on the vertices. */
private final HashedChunkStack[] chunkStacksVertex;
/** Playable vertices (for boardless games). */
private final HashedBitSet playableVertex;
/** The stack on the edges. */
private final HashedChunkStack[] chunkStacksEdge;
/** Playable edges (for boardless games). */
private final HashedBitSet playableEdge;
/** Which edge slots are empty. */
private final Region emptyEdge;
/** Which vertex slots are empty. */
private final Region emptyVertex;
private final long[][][] chunkStacksWhatVertexHash;
private final long[][][] chunkStacksWhoVertexHash;
private final long[][][] chunkStacksStateVertexHash;
private final long[][][] chunkStacksRotationVertexHash;
private final long[][][] chunkStacksValueVertexHash;
private final long[][] chunkStacksSizeVertexHash;
private final long[][][] chunkStacksHiddenVertexHash;
private final long[][][] chunkStacksHiddenWhatVertexHash;
private final long[][][] chunkStacksHiddenWhoVertexHash;
private final long[][][] chunkStacksHiddenStateVertexHash;
private final long[][][] chunkStacksHiddenRotationVertexHash;
private final long[][][] chunkStacksHiddenValueVertexHash;
private final long[][][] chunkStacksHiddenCountVertexHash;
private final long[][][] chunkStacksWhatEdgeHash;
private final long[][][] chunkStacksWhoEdgeHash;
private final long[][][] chunkStacksStateEdgeHash;
private final long[][][] chunkStacksRotationEdgeHash;
private final long[][][] chunkStacksValueEdgeHash;
private final long[][] chunkStacksSizeEdgeHash;
private final long[][][] chunkStacksHiddenEdgeHash;
private final long[][][] chunkStacksHiddenWhatEdgeHash;
private final long[][][] chunkStacksHiddenWhoEdgeHash;
private final long[][][] chunkStacksHiddenStateEdgeHash;
private final long[][][] chunkStacksHiddenRotationEdgeHash;
private final long[][][] chunkStacksHiddenValueEdgeHash;
private final long[][][] chunkStacksHiddenCountEdgeHash;
private final boolean hiddenVertexInfo;
private final boolean hiddenEdgeInfo;
/**
* Constructor.
*
* @param generator
* @param game
* @param container
* @param type
*/
public ContainerGraphStateStacks(final ZobristHashGenerator generator, final Game game, final Container container,
final int type)
{
super(generator, game, container, type);
final int numEdges = game.board().topology().edges().size();
final int numVertice = game.board().topology().vertices().size();
chunkStacksVertex = new HashedChunkStack[numVertice];
chunkStacksEdge = new HashedChunkStack[numEdges];
final int maxValWhat = numComponents;
final int maxValWho = numPlayers + 1;
final int maxValState = numStates;
final int maxValRotation = numRotation;
final int maxPieceValue = Constants.MAX_VALUE_PIECE;
chunkStacksWhatVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT,
maxValWhat + 1);
chunkStacksWhoVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT,
maxValWho + 1);
chunkStacksStateVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT,
maxValState + 1);
chunkStacksRotationVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, maxValRotation + 1);
chunkStacksValueVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, maxPieceValue + 1);
chunkStacksSizeVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT);
chunkStacksWhatEdgeHash = ZobristHashUtilities.getSequence(generator, numEdges, Constants.MAX_STACK_HEIGHT,
maxValWhat + 1);
chunkStacksWhoEdgeHash = ZobristHashUtilities.getSequence(generator, numEdges, Constants.MAX_STACK_HEIGHT,
maxValWho + 1);
chunkStacksStateEdgeHash = ZobristHashUtilities.getSequence(generator, numEdges, Constants.MAX_STACK_HEIGHT,
maxValState + 1);
chunkStacksRotationEdgeHash = ZobristHashUtilities.getSequence(generator, numEdges, Constants.MAX_STACK_HEIGHT, maxValRotation + 1);
chunkStacksValueEdgeHash = ZobristHashUtilities.getSequence(generator, numEdges, Constants.MAX_STACK_HEIGHT, maxPieceValue + 1);
chunkStacksSizeEdgeHash = ZobristHashUtilities.getSequence(generator, numEdges, Constants.MAX_STACK_HEIGHT);
if ((game.gameFlags() & GameType.HiddenInfo) == 0L)
{
chunkStacksHiddenVertexHash = null;
chunkStacksHiddenWhatVertexHash = null;
chunkStacksHiddenWhoVertexHash = null;
chunkStacksHiddenStateVertexHash = null;
chunkStacksHiddenRotationVertexHash = null;
chunkStacksHiddenValueVertexHash = null;
chunkStacksHiddenCountVertexHash = null;
hiddenVertexInfo = false;
chunkStacksHiddenEdgeHash = null;
chunkStacksHiddenWhatEdgeHash = null;
chunkStacksHiddenWhoEdgeHash = null;
chunkStacksHiddenStateEdgeHash = null;
chunkStacksHiddenRotationEdgeHash = null;
chunkStacksHiddenValueEdgeHash = null;
chunkStacksHiddenCountEdgeHash = null;
hiddenEdgeInfo = false;
}
else
{
chunkStacksHiddenVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenWhatVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenWhoVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenStateVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenRotationVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenValueVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenCountVertexHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
hiddenVertexInfo = true;
chunkStacksHiddenEdgeHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenWhatEdgeHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenWhoEdgeHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenStateEdgeHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenRotationEdgeHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenValueEdgeHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenCountEdgeHash = ZobristHashUtilities.getSequence(generator, numVertice, Constants.MAX_STACK_HEIGHT, 2);
hiddenEdgeInfo = true;
}
if (!game.isBoardless())
{
playableVertex = null;
playableEdge = null;
}
else
{
playableVertex = new HashedBitSet(generator, numVertice);
playableEdge = new HashedBitSet(generator, numEdges);
}
this.emptyEdge = new Region(numEdges);
this.emptyVertex = new Region(numVertice);
}
/**
* Copy constructor.
*
* @param other
*/
public ContainerGraphStateStacks(final ContainerGraphStateStacks other)
{
super(other);
playableVertex = (other.playableVertex == null) ? null : other.playableVertex.clone();
playableEdge = (other.playableEdge == null) ? null : other.playableEdge.clone();
if (other.chunkStacksVertex == null)
{
chunkStacksVertex = null;
}
else
{
chunkStacksVertex = new HashedChunkStack[other.chunkStacksVertex.length];
for (int i = 0; i < other.chunkStacksVertex.length; ++i)
{
final HashedChunkStack otherChunkStack = other.chunkStacksVertex[i];
if (otherChunkStack != null)
{
chunkStacksVertex[i] = otherChunkStack.clone();
}
}
}
if (other.chunkStacksEdge == null)
{
chunkStacksEdge = null;
}
else
{
chunkStacksEdge = new HashedChunkStack[other.chunkStacksEdge.length];
for (int i = 0; i < other.chunkStacksEdge.length; ++i)
{
final HashedChunkStack otherChunkStack = other.chunkStacksEdge[i];
if (otherChunkStack != null)
{
chunkStacksEdge[i] = otherChunkStack.clone();
}
}
}
chunkStacksWhatVertexHash = other.chunkStacksWhatVertexHash;
chunkStacksWhoVertexHash = other.chunkStacksWhoVertexHash;
chunkStacksStateVertexHash = other.chunkStacksStateVertexHash;
chunkStacksRotationVertexHash = other.chunkStacksRotationVertexHash;
chunkStacksValueVertexHash = other.chunkStacksValueVertexHash;
chunkStacksSizeVertexHash = other.chunkStacksSizeVertexHash;
hiddenVertexInfo = other.hiddenVertexInfo;
chunkStacksWhatEdgeHash = other.chunkStacksWhatEdgeHash;
chunkStacksWhoEdgeHash = other.chunkStacksWhoEdgeHash;
chunkStacksStateEdgeHash = other.chunkStacksStateEdgeHash;
chunkStacksRotationEdgeHash = other.chunkStacksRotationEdgeHash;
chunkStacksValueEdgeHash = other.chunkStacksValueEdgeHash;
chunkStacksSizeEdgeHash = other.chunkStacksSizeEdgeHash;
hiddenEdgeInfo = other.hiddenEdgeInfo;
if (other.chunkStacksHiddenVertexHash == null)
{
chunkStacksHiddenVertexHash = null;
chunkStacksHiddenWhatVertexHash = null;
chunkStacksHiddenWhoVertexHash = null;
chunkStacksHiddenStateVertexHash = null;
chunkStacksHiddenRotationVertexHash = null;
chunkStacksHiddenValueVertexHash = null;
chunkStacksHiddenCountVertexHash = null;
}
else
{
chunkStacksHiddenVertexHash = other.chunkStacksHiddenVertexHash;
chunkStacksHiddenWhatVertexHash = other.chunkStacksHiddenWhatVertexHash;
chunkStacksHiddenWhoVertexHash = other.chunkStacksHiddenWhoVertexHash;
chunkStacksHiddenStateVertexHash = other.chunkStacksHiddenStateVertexHash;
chunkStacksHiddenRotationVertexHash = other.chunkStacksHiddenRotationVertexHash;
chunkStacksHiddenValueVertexHash = other.chunkStacksHiddenValueVertexHash;
chunkStacksHiddenCountVertexHash = other.chunkStacksHiddenCountVertexHash;
}
if (other.chunkStacksHiddenEdgeHash == null)
{
chunkStacksHiddenEdgeHash = null;
chunkStacksHiddenWhatEdgeHash = null;
chunkStacksHiddenWhoEdgeHash = null;
chunkStacksHiddenStateEdgeHash = null;
chunkStacksHiddenRotationEdgeHash = null;
chunkStacksHiddenValueEdgeHash = null;
chunkStacksHiddenCountEdgeHash = null;
}
else
{
chunkStacksHiddenEdgeHash = other.chunkStacksHiddenEdgeHash;
chunkStacksHiddenWhatEdgeHash = other.chunkStacksHiddenWhatEdgeHash;
chunkStacksHiddenWhoEdgeHash = other.chunkStacksHiddenWhoEdgeHash;
chunkStacksHiddenStateEdgeHash = other.chunkStacksHiddenStateEdgeHash;
chunkStacksHiddenRotationEdgeHash = other.chunkStacksHiddenRotationEdgeHash;
chunkStacksHiddenValueEdgeHash = other.chunkStacksHiddenValueEdgeHash;
chunkStacksHiddenCountEdgeHash = other.chunkStacksHiddenCountEdgeHash;
}
this.emptyEdge = new Region(other.emptyEdge);
this.emptyVertex = new Region(other.emptyVertex);
}
//-------------------------------------------------------------------------
@Override
protected long calcCanonicalHash(final int[] siteRemap, final int[] edgeRemap, final int[] vertexRemap,
final int[] playerRemap, final boolean whoOnly)
{
if (offset != 0)
return 0; // Not the board!
long hash = super.calcCanonicalHash(siteRemap, edgeRemap, vertexRemap, playerRemap, whoOnly);
hash ^= calcCanonicalHashOverSites(chunkStacksVertex, siteRemap, chunkStacksWhatVertexHash,
chunkStacksWhoVertexHash, chunkStacksStateVertexHash, chunkStacksRotationVertexHash,
chunkStacksValueVertexHash, chunkStacksSizeVertexHash, whoOnly);
hash ^= calcCanonicalHashOverSites(chunkStacksEdge, siteRemap, chunkStacksWhatEdgeHash, chunkStacksWhoEdgeHash,
chunkStacksStateEdgeHash, chunkStacksRotationEdgeHash, chunkStacksValueEdgeHash,
chunkStacksSizeEdgeHash, whoOnly);
return hash;
}
private static long calcCanonicalHashOverSites(final HashedChunkStack[] stack, final int[] siteRemap,
final long[][][] whatHash, final long[][][] whoHash, final long[][][] stateHash,
final long[][][] rotationHash, final long[][][] valueHash, final long[][] sizeHash, final boolean whoOnly)
{
long hash = 0;
for (int pos = 0; pos < stack.length && pos < siteRemap.length; pos++)
{
final int newPos = siteRemap[pos];
if (stack[pos] == null)
continue;
hash ^= stack[pos].remapHashTo(whatHash[newPos], whoHash[newPos], stateHash[newPos], rotationHash[newPos],
valueHash[newPos],
sizeHash[newPos], whoOnly);
}
return hash;
}
//-------------------------------------------------------------------------
@Override
public void reset(final State trialState, final Game game)
{
super.reset(trialState, game);
final int numEdges = (game.board().defaultSite() == SiteType.Cell) ? game.board().topology().edges().size()
: game.board().topology().edges().size();
final int numVertices = (game.board().defaultSite() == SiteType.Cell)
? game.board().topology().vertices().size()
: game.board().topology().vertices().size();
for (final HashedChunkStack set : chunkStacksVertex)
{
if (set == null)
continue;
trialState.updateStateHash(set.calcHash());
}
Arrays.fill(chunkStacksVertex, null);
super.reset(trialState, game);
for (final HashedChunkStack set : chunkStacksEdge)
{
if (set == null)
continue;
trialState.updateStateHash(set.calcHash());
}
Arrays.fill(chunkStacksEdge, null);
emptyEdge.set(numEdges);
emptyVertex.set(numVertices);
}
private void verifyPresentVertex(final int site)
{
if (chunkStacksVertex[site] != null)
return;
chunkStacksVertex[site] = new HashedChunkStack(numComponents, numPlayers, numStates, numRotation, numValues,
type,
hiddenVertexInfo, chunkStacksWhatVertexHash[site], chunkStacksWhoVertexHash[site],
chunkStacksStateVertexHash[site], chunkStacksRotationVertexHash[site], chunkStacksValueVertexHash[site],
chunkStacksSizeVertexHash[site]);
}
private void verifyPresentEdge(final int site)
{
if (chunkStacksEdge[site] != null)
return;
chunkStacksEdge[site] = new HashedChunkStack(numComponents, numPlayers, numStates, numRotation, numValues, type,
hiddenEdgeInfo, chunkStacksWhatEdgeHash[site], chunkStacksWhoEdgeHash[site],
chunkStacksStateEdgeHash[site], chunkStacksRotationEdgeHash[site], chunkStacksValueEdgeHash[site],
chunkStacksSizeEdgeHash[site]);
}
private void checkPlayableVertex(final State trialState, final int site)
{
if (isOccupiedVertex(site))
{
setPlayableVertex(trialState, site, false);
return;
}
final Vertex v = container().topology().vertices().get(site);
for (final Vertex vNbors : v.adjacent())
if (isOccupiedVertex(vNbors.index()))
{
setPlayableVertex(trialState, site, true);
return;
}
setPlayable(trialState, site, false);
}
/**
* Make a vertex playable.
*
* @param trialState The state of the game.
* @param site The vertex.
* @param on The value to set.
*/
public void setPlayableVertex(final State trialState, final int site, final boolean on)
{
playableVertex.set(trialState, site, on);
}
/**
* @param site The vertex to look.
* @return True if the vertex is occupied.
*/
public boolean isOccupiedVertex(final int site)
{
return chunkStacksVertex[site] != null && chunkStacksVertex[site].what() != 0;
}
private void checkPlayableEdge(final State trialState, final int site)
{
if (isOccupiedEdge(site))
{
setPlayableEdge(trialState, site, false);
return;
}
setPlayable(trialState, site, false);
}
/**
* Make an edge playable.
*
* @param trialState The state of the game.
* @param site The edge.
* @param on The value to set.
*/
public void setPlayableEdge(final State trialState, final int site, final boolean on)
{
playableEdge.set(trialState, site, on);
}
/**
* @param site The edge to look.
* @return True if the edge is occupied.
*/
public boolean isOccupiedEdge(final int site)
{
return chunkStacksEdge[site] != null && chunkStacksEdge[site].what() != 0;
}
//-------------------------------------------------------------------------
@Override
public void setSite(final State trialState, final int site, final int whoVal, final int whatVal, final int countVal,
final int stateVal, final int rotationVal, final int valueVal, final SiteType type)
{
if (type == SiteType.Cell)
{
super.setSite(trialState, site, whoVal, whatVal, countVal, stateVal, rotationVal, valueVal, type);
}
else if (type == SiteType.Vertex)
{
verifyPresentVertex(site);
final boolean wasEmpty = isEmpty(site, SiteType.Vertex);
if (whoVal != Constants.UNDEFINED)
chunkStacksVertex[site].setWho(trialState, whoVal);
if (whatVal != Constants.UNDEFINED)
chunkStacksVertex[site].setWhat(trialState, whatVal);
if (stateVal != Constants.UNDEFINED)
chunkStacksVertex[site].setState(trialState, stateVal);
if (rotationVal != Constants.UNDEFINED)
chunkStacksVertex[site].setRotation(trialState, rotationVal);
if (valueVal != Constants.UNDEFINED)
chunkStacksVertex[site].setValue(trialState, valueVal);
final boolean isEmpty = isEmpty(site, SiteType.Vertex);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
{
addToEmpty(site, type);
if (playableVertex != null)
{
checkPlayableVertex(trialState, site - offset);
final Vertex v = container().topology().vertices().get(site);
for (final Vertex vNbors : v.adjacent())
checkPlayableVertex(trialState, vNbors.index());
}
}
else
{
removeFromEmpty(site, type);
if (playableVertex != null)
{
setPlayableVertex(trialState, site, false);
final Vertex v = container().topology().vertices().get(site);
for (final Vertex vNbors : v.adjacent())
if (!isOccupiedVertex(vNbors.index()))
setPlayableVertex(trialState, vNbors.index(), true);
}
}
}
else if (type == SiteType.Edge)
{
verifyPresentEdge(site);
final boolean wasEmpty = isEmpty(site, SiteType.Edge);
if (whoVal != Constants.UNDEFINED)
chunkStacksEdge[site].setWho(trialState, whoVal);
if (whatVal != Constants.UNDEFINED)
chunkStacksEdge[site].setWhat(trialState, whatVal);
if (stateVal != Constants.UNDEFINED)
chunkStacksEdge[site].setState(trialState, stateVal);
if (rotationVal != Constants.UNDEFINED)
chunkStacksEdge[site].setRotation(trialState, rotationVal);
if (valueVal != Constants.UNDEFINED)
chunkStacksEdge[site].setValue(trialState, valueVal);
final boolean isEmpty = isEmpty(site, SiteType.Edge);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
{
addToEmpty(site, type);
if (playableEdge != null)
{
checkPlayableEdge(trialState, site - offset);
}
}
else
{
removeFromEmpty(site, type);
if (playableEdge != null)
{
setPlayableEdge(trialState, site, false);
}
}
}
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game)
{
verifyPresentVertex(site);
chunkStacksVertex[site].incrementSize(trialState);
chunkStacksVertex[site].setWhat(trialState, whatValue);
chunkStacksVertex[site].setWho(trialState, whoId);
}
@Override
public void insertVertex(State trialState, int site, int level, int what, int who, final int state,
final int rotation, final int value, Game game)
{
verifyPresentVertex(site);
final int size = chunkStacksVertex[site - offset].size();
final boolean wasEmpty = (size == 0);
if (level == size)
{
chunkStacksVertex[site - offset].incrementSize(trialState);
chunkStacksVertex[site - offset].setWhat(trialState, what);
chunkStacksVertex[site - offset].setWho(trialState, who);
chunkStacksVertex[site - offset].setState(trialState, (state == Constants.UNDEFINED ? 0 : state));
chunkStacksVertex[site - offset].setRotation(trialState, (rotation == Constants.UNDEFINED ? 0 : rotation));
chunkStacksVertex[site - offset].setValue(trialState, 0, (value == Constants.UNDEFINED ? 0 : value));
}
else if (level < size)
{
chunkStacksVertex[site - offset].incrementSize(trialState);
for (int i = size - 1; i >= level; i--)
{
final int whatLevel = chunkStacksVertex[site - offset].what(i);
chunkStacksVertex[site - offset].setWhat(trialState, whatLevel, i + 1);
final int whoLevel = chunkStacksVertex[site - offset].who(i);
chunkStacksVertex[site - offset].setWho(trialState, whoLevel, i + 1);
final int rotationLevel = chunkStacksVertex[site - offset].rotation(i);
chunkStacksVertex[site - offset].setRotation(trialState, rotationLevel, i + 1);
final int valueLevel = chunkStacksVertex[site - offset].value(i);
chunkStacksVertex[site - offset].setValue(trialState, valueLevel, i + 1);
final int stateLevel = chunkStacksVertex[site - offset].state(i);
chunkStacksVertex[site - offset].setState(trialState, stateLevel, i + 1);
}
chunkStacksVertex[site - offset].setWhat(trialState, what, level);
chunkStacksVertex[site - offset].setWho(trialState, who, level);
chunkStacksVertex[site - offset].setState(trialState, (state == Constants.UNDEFINED ? 0 : state), level);
chunkStacksVertex[site - offset].setRotation(trialState, (rotation == Constants.UNDEFINED ? 0 : rotation),
level);
chunkStacksVertex[site - offset].setValue(trialState, (value == Constants.UNDEFINED ? 0 : value), level);
}
final boolean isEmpty = (chunkStacksVertex[site - offset].size() == 0);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmpty(site, SiteType.Vertex);
else
removeFromEmpty(site, SiteType.Vertex);
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game)
{
verifyPresentVertex(site);
chunkStacksVertex[site].incrementSize(trialState);
chunkStacksVertex[site].setWhat(trialState, whatValue);
chunkStacksVertex[site].setWho(trialState, whoId);
chunkStacksVertex[site].setState(trialState, stateVal);
chunkStacksVertex[site].setRotation(trialState, rotationVal);
chunkStacksVertex[site].setValue(trialState, valueVal);
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
verifyPresentVertex(site);
chunkStacksVertex[site].incrementSize(trialState);
chunkStacksVertex[site].setWhat(trialState, whatValue);
chunkStacksVertex[site].setWho(trialState, whoId);
}
@Override
public void removeStackVertex(State trialState, int site)
{
if (chunkStacksVertex[site] == null)
return;
trialState.updateStateHash(chunkStacksVertex[site].calcHash());
chunkStacksVertex[site] = null;
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game)
{
verifyPresentEdge(site);
chunkStacksEdge[site].incrementSize(trialState);
chunkStacksEdge[site].setWhat(trialState, whatValue);
chunkStacksEdge[site].setWho(trialState, whoId);
}
@Override
public void insertEdge
(
final State trialState,
final int site,
final int level,
final int what,
final int who,
final int state,
final int rotation,
final int value,
final Game game
)
{
verifyPresentEdge(site);
final int size = chunkStacksEdge[site - offset].size();
final boolean wasEmpty = (size == 0);
if (level == size)
{
chunkStacksEdge[site - offset].incrementSize(trialState);
chunkStacksEdge[site - offset].setWhat(trialState, what);
chunkStacksEdge[site - offset].setWho(trialState, who);
chunkStacksEdge[site - offset].setState(trialState, (state == Constants.UNDEFINED ? 0 : state));
chunkStacksEdge[site - offset].setRotation(trialState, (rotation == Constants.UNDEFINED ? 0 : rotation));
chunkStacksEdge[site - offset].setValue(trialState, (value == Constants.UNDEFINED ? 0 : value));
}
else if (level < size)
{
chunkStacksEdge[site - offset].incrementSize(trialState);
for (int i = size - 1; i >= level; i--)
{
final int whatLevel = chunkStacksEdge[site - offset].what(i);
chunkStacksEdge[site - offset].setWhat(trialState, whatLevel, i + 1);
final int whoLevel = chunkStacksEdge[site - offset].who(i);
chunkStacksEdge[site - offset].setWho(trialState, whoLevel, i + 1);
final int rotationLevel = chunkStacksEdge[site - offset].rotation(i);
chunkStacksEdge[site - offset].setRotation(trialState, rotationLevel, i + 1);
final int valueLevel = chunkStacksEdge[site - offset].value(i);
chunkStacksEdge[site - offset].setValue(trialState, valueLevel, i + 1);
final int stateLevel = chunkStacksEdge[site - offset].state(i);
chunkStacksEdge[site - offset].setState(trialState, stateLevel, i + 1);
}
chunkStacksEdge[site - offset].setWhat(trialState, what, level);
chunkStacksEdge[site - offset].setWho(trialState, who, level);
chunkStacksEdge[site - offset].setState(trialState, (state == Constants.UNDEFINED ? 0 : state), level);
chunkStacksEdge[site - offset].setRotation(trialState, (rotation == Constants.UNDEFINED ? 0 : rotation), level);
chunkStacksEdge[site - offset].setValue(trialState, (value == Constants.UNDEFINED ? 0 : value), level);
}
final boolean isEmpty = (chunkStacksEdge[site - offset].size() == 0);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmpty(site, SiteType.Edge);
else
removeFromEmpty(site, SiteType.Edge);
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal, Game game)
{
verifyPresentEdge(site);
chunkStacksEdge[site].incrementSize(trialState);
chunkStacksEdge[site].setWhat(trialState, whatValue);
chunkStacksEdge[site].setWho(trialState, whoId);
chunkStacksEdge[site].setState(trialState, stateVal);
chunkStacksEdge[site].setRotation(trialState, rotationVal);
chunkStacksEdge[site].setValue(trialState, valueVal);
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
verifyPresentEdge(site);
chunkStacksEdge[site].incrementSize(trialState);
chunkStacksEdge[site].setWhat(trialState, whatValue);
chunkStacksEdge[site].setWho(trialState, whoId);
}
@Override
public void removeStackEdge(State trialState, int site)
{
if (chunkStacksEdge[site] == null)
return;
trialState.updateStateHash(chunkStacksEdge[site].calcHash());
chunkStacksEdge[site] = null;
}
@Override
public int whoVertex(int site)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].who();
}
@Override
public int whoVertex(int site, int level)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].who(level);
}
@Override
public int whatVertex(int site)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].what();
}
@Override
public int whatVertex(int site, int level)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].what(level);
}
@Override
public int stateVertex(int site)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].state();
}
@Override
public int stateVertex(int site, int level)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].state(level);
}
@Override
public int rotationVertex(int site)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].rotation();
}
@Override
public int rotationVertex(int site, int level)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].rotation(level);
}
@Override
public int valueVertex(int site)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].value();
}
@Override
public int valueVertex(int site, int level)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].value(level);
}
@Override
public int sizeStackVertex(final int site)
{
if (chunkStacksVertex[site] == null)
return 0;
return chunkStacksVertex[site].size();
}
@Override
public int whoEdge(int site)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].who();
}
@Override
public int whoEdge(int site, int level)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].who(level);
}
@Override
public int whatEdge(int site)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].what();
}
@Override
public int whatEdge(int site, int level)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].what(level);
}
@Override
public int stateEdge(int site)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].state();
}
@Override
public int stateEdge(int site, int level)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].state(level);
}
@Override
public int rotationEdge(int site)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].rotation();
}
@Override
public int rotationEdge(int site, int level)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].rotation(level);
}
@Override
public int valueEdge(int site)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].value();
}
@Override
public int valueEdge(int site, int level)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].value(level);
}
@Override
public int sizeStackEdge(final int site)
{
if (chunkStacksEdge[site] == null)
return 0;
return chunkStacksEdge[site].size();
}
@Override
public int remove(final State state, final int site, final SiteType graphElement)
{
if (graphElement == SiteType.Cell)
return super.remove(state, site, graphElement);
else if (graphElement == SiteType.Vertex)
{
if (chunkStacksVertex[site] == null)
return 0;
final int componentRemove = chunkStacksVertex[site].what();
chunkStacksVertex[site].setWhat(state, 0);
chunkStacksVertex[site].setWho(state, 0);
chunkStacksVertex[site].setState(state, 0);
chunkStacksVertex[site].setRotation(state, 0);
chunkStacksVertex[site].setValue(state, 0);
chunkStacksVertex[site].decrementSize(state);
return componentRemove;
}
// Edge
if (chunkStacksEdge[site] == null)
return 0;
final int componentRemove = chunkStacksEdge[site].what();
chunkStacksEdge[site].setWhat(state, 0);
chunkStacksEdge[site].setWho(state, 0);
chunkStacksEdge[site].setState(state, 0);
chunkStacksEdge[site].setRotation(state, 0);
chunkStacksEdge[site].setValue(state, 0);
chunkStacksEdge[site].decrementSize(state);
return componentRemove;
}
@Override
public int remove(final State state, final int site, final int level, final SiteType graphElement)
{
if (graphElement == SiteType.Cell)
return super.remove(state, site, level, graphElement);
else if (graphElement == SiteType.Vertex)
{
if (chunkStacksVertex[site] == null)
return 0;
final int componentRemove = chunkStacksVertex[site].what(level);
for (int i = level; i < sizeStack(site, graphElement) - 1; i++)
{
chunkStacksVertex[site].setWhat(state, chunkStacksVertex[site].what(i + 1), i);
chunkStacksVertex[site].setWho(state, chunkStacksVertex[site].who(i + 1), i);
chunkStacksVertex[site].setState(state, chunkStacksVertex[site].state(i + 1), i);
chunkStacksVertex[site].setRotation(state, chunkStacksVertex[site].rotation(i + 1), i);
chunkStacksVertex[site].setValue(state, chunkStacksVertex[site].value(i + 1), i);
}
chunkStacksVertex[site].setWhat(state, 0);
chunkStacksVertex[site].setWho(state, 0);
chunkStacksVertex[site].decrementSize(state);
return componentRemove;
}
// Edge
if (chunkStacksEdge[site] == null)
return 0;
final int componentRemove = chunkStacksEdge[site].what(level);
for (int i = level; i < sizeStack(site, graphElement) - 1; i++)
{
chunkStacksEdge[site].setWhat(state, chunkStacksEdge[site].what(i + 1), i);
chunkStacksEdge[site].setWho(state, chunkStacksEdge[site].who(i + 1), i);
chunkStacksEdge[site].setState(state, chunkStacksEdge[site].state(i + 1), i);
chunkStacksEdge[site].setRotation(state, chunkStacksEdge[site].rotation(i + 1), i);
chunkStacksEdge[site].setValue(state, chunkStacksEdge[site].value(i + 1), i);
}
chunkStacksEdge[site].setWhat(state, 0);
chunkStacksEdge[site].setWho(state, 0);
chunkStacksEdge[site].decrementSize(state);
return componentRemove;
}
@Override
public void addToEmpty(final int site, final SiteType graphType)
{
if (graphType.equals(SiteType.Cell))
empty.add(site - offset);
else if (graphType.equals(SiteType.Edge))
emptyEdge.add(site);
else
emptyVertex.add(site);
}
@Override
public void removeFromEmpty(final int site, final SiteType graphType)
{
if (graphType.equals(SiteType.Cell))
empty.remove(site - offset);
else if (graphType.equals(SiteType.Edge))
emptyEdge.remove(site);
else
emptyVertex.remove(site);
}
@Override
public ContainerStateStacks deepClone()
{
return new ContainerGraphStateStacks(this);
}
@Override
public boolean isHidden(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHidden(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return chunkStacksEdge[site - offset].isHidden(player, site, level, graphElementType);
}
else
{
if (!hiddenVertexInfo)
return false;
return chunkStacksVertex[site - offset].isHidden(player, site, level, graphElementType);
}
}
@Override
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenWhat(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return chunkStacksEdge[site - offset].isHiddenWhat(player, site, level, graphElementType);
}
else
{
if (!hiddenVertexInfo)
return false;
return chunkStacksVertex[site - offset].isHiddenWhat(player, site, level, graphElementType);
}
}
@Override
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenWho(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return chunkStacksEdge[site - offset].isHiddenWho(player, site, level, graphElementType);
}
else
{
if (!hiddenVertexInfo)
return false;
return chunkStacksVertex[site - offset].isHiddenWho(player, site, level, graphElementType);
}
}
@Override
public boolean isHiddenState(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenState(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return chunkStacksEdge[site - offset].isHiddenState(player, site, level, graphElementType);
}
else
{
if (!hiddenVertexInfo)
return false;
return chunkStacksVertex[site - offset].isHiddenState(player, site, level, graphElementType);
}
}
@Override
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenRotation(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return chunkStacksEdge[site - offset].isHiddenRotation(player, site, level, graphElementType);
}
else
{
if (!hiddenVertexInfo)
return false;
return chunkStacksVertex[site - offset].isHiddenRotation(player, site, level, graphElementType);
}
}
@Override
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenValue(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return chunkStacksEdge[site - offset].isHiddenValue(player, site, level, graphElementType);
}
else
{
if (!hiddenVertexInfo)
return false;
return chunkStacksVertex[site - offset].isHiddenValue(player, site, level, graphElementType);
}
}
@Override
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenCount(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return chunkStacksEdge[site - offset].isHiddenCount(player, site, level, graphElementType);
}
else
{
if (!hiddenVertexInfo)
return false;
return chunkStacksVertex[site - offset].isHiddenCount(player, site, level, graphElementType);
}
}
@Override
public void setHidden(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHidden(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
chunkStacksEdge[site - offset].setHidden(state, player, site, level, graphElementType, on);
}
else
{
if (!hiddenVertexInfo)
return;
chunkStacksVertex[site - offset].setHidden(state, player, site, level, graphElementType, on);
}
}
@Override
public void setHiddenWhat(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenWhat(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
chunkStacksEdge[site - offset].setHiddenWhat(state, player, site, level, graphElementType, on);
}
else
{
if (!hiddenVertexInfo)
return;
chunkStacksVertex[site - offset].setHiddenWhat(state, player, site, level, graphElementType, on);
}
}
@Override
public void setHiddenWho(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenWho(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
chunkStacksEdge[site - offset].setHiddenWho(state, player, site, level, graphElementType, on);
}
else
{
if (!hiddenVertexInfo)
return;
chunkStacksVertex[site - offset].setHiddenWho(state, player, site, level, graphElementType, on);
}
}
@Override
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenState(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
chunkStacksEdge[site - offset].setHiddenState(state, player, site, level, graphElementType, on);
}
else
{
if (!hiddenVertexInfo)
return;
chunkStacksVertex[site - offset].setHiddenState(state, player, site, level, graphElementType, on);
}
}
@Override
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenRotation(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
chunkStacksEdge[site - offset].setHiddenRotation(state, player, site, level, graphElementType, on);
}
else
{
if (!hiddenVertexInfo)
return;
chunkStacksVertex[site - offset].setHiddenRotation(state, player, site, level, graphElementType, on);
}
}
@Override
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenValue(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
chunkStacksEdge[site - offset].setHiddenValue(state, player, site, level, graphElementType, on);
}
else
{
if (!hiddenVertexInfo)
return;
chunkStacksVertex[site - offset].setHiddenValue(state, player, site, level, graphElementType, on);
}
}
@Override
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenCount(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
chunkStacksEdge[site - offset].setHiddenCount(state, player, site, level, graphElementType, on);
}
else
{
if (!hiddenVertexInfo)
return;
chunkStacksVertex[site - offset].setHiddenCount(state, player, site, level, graphElementType, on);
}
}
@Override
public Region emptyRegion(final SiteType graphType)
{
if (graphType.equals(SiteType.Cell))
return empty;
else if (graphType.equals(SiteType.Edge))
return emptyEdge;
else
return emptyVertex;
}
@Override
public int countVertex(int site)
{
return whoVertex(site) == 0 ? 0 : 1;
}
@Override
public int countEdge(int site)
{
return whoEdge(site) == 0 ? 0 : 1;
}
@Override
public boolean isEmptyVertex(final int vertex)
{
return emptyVertex.contains(vertex);
}
@Override
public boolean isEmptyEdge(final int edge)
{
return emptyEdge.contains(edge);
}
}
| 44,248 | 30.38227 | 138 | java |
Ludii | Ludii-master/Core/src/other/state/stacking/ContainerGraphStateStacksLarge.java | package other.state.stacking;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.equipment.Region;
import main.Constants;
import main.collections.ListStack;
import other.state.State;
import other.state.zhash.ZobristHashGenerator;
/**
* Container state for large stacks on the vertices or on the edges.
*
* @author Eric.Piette
*/
public class ContainerGraphStateStacksLarge extends ContainerStateStacksLarge
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The stacks on the vertices. */
private ListStack[] listStacksVertex;
/** The stack on the edges. */
private ListStack[] listStacksEdge;
/** Which edge slots are empty. */
private final Region emptyEdge;
/** Which vertex slots are empty. */
private final Region emptyVertex;
private final boolean hiddenVertexInfo;
private final boolean hiddenEdgeInfo;
/**
* Constructor.
*
* @param generator
* @param game
* @param container
* @param type
*/
public ContainerGraphStateStacksLarge(final ZobristHashGenerator generator, final Game game, final Container container,
final int type)
{
super(generator, game, container, type);
final int numEdges = game.board().topology().edges().size();
final int numVertice = game.board().topology().vertices().size();
listStacksVertex = new ListStack[numVertice];
listStacksEdge = new ListStack[numEdges];
if ((game.gameFlags() & GameType.HiddenInfo) == 0L)
{
hiddenVertexInfo = false;
hiddenEdgeInfo = false;
}
else
{
hiddenVertexInfo = true;
hiddenEdgeInfo = true;
}
this.emptyEdge = new Region(numEdges);
this.emptyVertex = new Region(numVertice);
for (int i = 0 ; i < listStacksVertex.length; i++)
listStacksVertex[i] = new ListStack(numComponents, numPlayers, numStates, numRotation, numValues, type, hiddenVertexInfo);
for (int i = 0 ; i < listStacksEdge.length; i++)
listStacksEdge[i] = new ListStack(numComponents, numPlayers, numStates, numRotation, numValues, type, hiddenVertexInfo);
}
/**
* Copy constructor.
*
* @param other
*/
public ContainerGraphStateStacksLarge(final ContainerGraphStateStacksLarge other)
{
super(other);
if (other.listStacksVertex == null)
{
listStacksVertex = null;
}
else
{
listStacksVertex = new ListStack[other.listStacksVertex.length];
for(int i = 0 ; i < listStacksVertex.length; i++)
listStacksVertex[i] = new ListStack(other.listStacksVertex[i]);
}
if (other.listStacksEdge == null)
{
listStacksEdge = null;
}
else
{
listStacksEdge = new ListStack[other.listStacksEdge.length];
for(int i = 0 ; i < listStacksEdge.length; i++)
listStacksEdge[i] = new ListStack(other.listStacksEdge[i]);
}
hiddenVertexInfo = other.hiddenVertexInfo;
hiddenEdgeInfo = other.hiddenEdgeInfo;
this.emptyEdge = new Region(other.emptyEdge);
this.emptyVertex = new Region(other.emptyVertex);
}
@Override
public ContainerStateStacksLarge deepClone()
{
return new ContainerGraphStateStacksLarge(this);
}
//-------------------------------------------------------------------------
@Override
protected long calcCanonicalHash(final int[] siteRemap, final int[] edgeRemap, final int[] vertexRemap, final int[] playerRemap, final boolean whoOnly)
{
return 0; // To do.
}
//-------------------------------------------------------------------------
@Override
public void reset(final State trialState, final Game game)
{
super.reset(trialState, game);
final int numEdges = game.board().topology().edges().size();
final int numVertices = game.board().topology().vertices().size();
listStacksVertex = new ListStack[numVertices];
for (int i = 0 ; i < listStacksVertex.length; i++)
listStacksVertex[i] = new ListStack(numComponents, numPlayers, numStates, numRotation, numValues, type, hiddenVertexInfo);
listStacksEdge = new ListStack[numEdges];
for (int i = 0 ; i < listStacksEdge.length; i++)
listStacksEdge[i] = new ListStack(numComponents, numPlayers, numStates, numRotation, numValues, type, hiddenVertexInfo);
emptyEdge.set(numEdges);
emptyVertex.set(numVertices);
}
private void verifyPresentVertex(final int site)
{
if (listStacksVertex[site] != null)
return;
}
private void verifyPresentEdge(final int site)
{
if (listStacksEdge[site] != null)
return;
}
/**
* @param site The vertex to look.
* @return True if the vertex is occupied.
*/
public boolean isOccupiedVertex(final int site)
{
return listStacksVertex[site] != null && listStacksVertex[site].what() != 0;
}
/**
* @param site The edge to look.
* @return True if the edge is occupied.
*/
public boolean isOccupiedEdge(final int site)
{
return listStacksEdge[site] != null && listStacksEdge[site].what() != 0;
}
//-------------------------------------------------------------------------
@Override
public void setSite(final State trialState, final int site, final int whoVal, final int whatVal, final int countVal,
final int stateVal, final int rotationVal, final int valueVal, final SiteType type)
{
if (type == SiteType.Cell)
{
super.setSite(trialState, site, whoVal, whatVal, countVal, stateVal, rotationVal, valueVal, type);
}
else if (type == SiteType.Vertex)
{
verifyPresentVertex(site);
final boolean wasEmpty = isEmpty(site, SiteType.Vertex);
if (whoVal != Constants.UNDEFINED)
listStacksVertex[site].setWho(whoVal);
if (whatVal != Constants.UNDEFINED)
listStacksVertex[site].setWhat(whatVal);
if (stateVal != Constants.UNDEFINED)
listStacksVertex[site].setState(stateVal);
if (rotationVal != Constants.UNDEFINED)
listStacksVertex[site].setRotation(rotationVal);
if (valueVal != Constants.UNDEFINED)
listStacksVertex[site].setValue(valueVal);
final boolean isEmpty = isEmpty(site, SiteType.Vertex);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmpty(site, type);
else
removeFromEmpty(site, type);
}
else if (type == SiteType.Edge)
{
verifyPresentEdge(site);
final boolean wasEmpty = isEmpty(site, SiteType.Edge);
if (whoVal != Constants.UNDEFINED)
listStacksEdge[site].setWho(whoVal);
if (whatVal != Constants.UNDEFINED)
listStacksEdge[site].setWhat(whatVal);
if (stateVal != Constants.UNDEFINED)
listStacksEdge[site].setState(stateVal);
if (rotationVal != Constants.UNDEFINED)
listStacksEdge[site].setRotation(rotationVal);
if (valueVal != Constants.UNDEFINED)
listStacksEdge[site].setValue(valueVal);
final boolean isEmpty = isEmpty(site, SiteType.Edge);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmpty(site, type);
else
removeFromEmpty(site, type);
}
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game)
{
verifyPresentVertex(site);
listStacksVertex[site].incrementSize();
listStacksVertex[site].setWhat(whatValue);
listStacksVertex[site].setWho(whoId);
}
@Override
public void insertVertex(State trialState, int site, int level, int what, int who, final int state,
final int rotation, final int value, Game game)
{
verifyPresentVertex(site);
final int size = listStacksVertex[site].size();
final boolean wasEmpty = (size == 0);
if (level == size)
{
listStacksVertex[site].incrementSize();
listStacksVertex[site].setWhat(what);
listStacksVertex[site].setWho(who);
listStacksVertex[site].setState((state == Constants.UNDEFINED ? 0 : state));
listStacksVertex[site].setRotation((rotation == Constants.UNDEFINED ? 0 : rotation));
listStacksVertex[site].setValue(0, (value == Constants.UNDEFINED ? 0 : value));
}
else if (level < size)
{
listStacksVertex[site].incrementSize();
for (int i = size - 1; i >= level; i--)
{
final int whatLevel = listStacksVertex[site].what(i);
listStacksVertex[site].setWhat(whatLevel, i + 1);
final int whoLevel = listStacksVertex[site].who(i);
listStacksVertex[site].setWho(whoLevel, i + 1);
final int rotationLevel = listStacksVertex[site].rotation(i);
listStacksVertex[site].setRotation(rotationLevel, i + 1);
final int valueLevel = listStacksVertex[site].value(i);
listStacksVertex[site].setValue(valueLevel, i + 1);
final int stateLevel = listStacksVertex[site].state(i);
listStacksVertex[site].setState(stateLevel, i + 1);
}
listStacksVertex[site].setWhat(what, level);
listStacksVertex[site].setWho(who, level);
listStacksVertex[site].setState((state == Constants.UNDEFINED ? 0 : state), level);
listStacksVertex[site].setRotation((rotation == Constants.UNDEFINED ? 0 : rotation),
level);
listStacksVertex[site].setValue((value == Constants.UNDEFINED ? 0 : value), level);
}
final boolean isEmpty = (listStacksVertex[site].size() == 0);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmpty(site, SiteType.Vertex);
else
removeFromEmpty(site, SiteType.Vertex);
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal, Game game)
{
verifyPresentVertex(site);
listStacksVertex[site].incrementSize();
listStacksVertex[site].setWhat(whatValue);
listStacksVertex[site].setWho(whoId);
listStacksVertex[site].setState(stateVal);
listStacksVertex[site].setRotation(rotationVal);
listStacksVertex[site].setValue(valueVal);
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
verifyPresentVertex(site);
listStacksVertex[site].incrementSize();
listStacksVertex[site].setWhat(whatValue);
listStacksVertex[site].setWho(whoId);
}
@Override
public void removeStackVertex(State trialState, int site)
{
if (listStacksVertex[site] == null)
return;
listStacksVertex[site] = null;
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game)
{
verifyPresentEdge(site);
listStacksEdge[site].incrementSize();
listStacksEdge[site].setWhat(whatValue);
listStacksEdge[site].setWho(whoId);
}
@Override
public void insertEdge(State trialState, int site, int level, int what, int who, final int state,
final int rotation, final int value, Game game)
{
verifyPresentEdge(site);
final int size = listStacksEdge[site].size();
final boolean wasEmpty = (size == 0);
if (level == size)
{
listStacksEdge[site].incrementSize();
listStacksEdge[site].setWhat(what);
listStacksEdge[site].setWho(who);
listStacksEdge[site].setState((state == Constants.UNDEFINED ? 0 : state));
listStacksEdge[site].setRotation((rotation == Constants.UNDEFINED ? 0 : rotation));
listStacksEdge[site].setValue(0, (value == Constants.UNDEFINED ? 0 : value));
}
else if (level < size)
{
listStacksEdge[site].incrementSize();
for (int i = size - 1; i >= level; i--)
{
final int whatLevel = listStacksEdge[site].what(i);
listStacksEdge[site].setWhat(whatLevel, i + 1);
final int whoLevel = listStacksEdge[site].who(i);
listStacksEdge[site].setWho(whoLevel, i + 1);
final int rotationLevel = listStacksEdge[site].rotation(i);
listStacksEdge[site].setRotation(rotationLevel, i + 1);
final int valueLevel = listStacksEdge[site].value(i);
listStacksEdge[site].setValue(valueLevel, i + 1);
final int stateLevel = listStacksEdge[site].state(i);
listStacksEdge[site].setState(stateLevel, i + 1);
}
listStacksEdge[site].setWhat(what, level);
listStacksEdge[site].setWho(who, level);
listStacksEdge[site].setState((state == Constants.UNDEFINED ? 0 : state), level);
listStacksEdge[site].setRotation((rotation == Constants.UNDEFINED ? 0 : rotation),
level);
listStacksEdge[site].setValue((value == Constants.UNDEFINED ? 0 : value), level);
}
final boolean isEmpty = (listStacksEdge[site].size() == 0);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmpty(site, SiteType.Edge);
else
removeFromEmpty(site, SiteType.Edge);
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal, Game game)
{
verifyPresentEdge(site);
listStacksEdge[site].incrementSize();
listStacksEdge[site].setWhat(whatValue);
listStacksEdge[site].setWho(whoId);
listStacksEdge[site].setState(stateVal);
listStacksEdge[site].setRotation(rotationVal);
listStacksEdge[site].setValue(valueVal);
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
verifyPresentEdge(site);
listStacksEdge[site].incrementSize();
listStacksEdge[site].setWhat(whatValue);
listStacksEdge[site].setWho(whoId);
}
@Override
public void removeStackEdge(State trialState, int site)
{
if (listStacksEdge[site] == null)
return;
listStacksEdge[site] = null;
}
@Override
public int whoVertex(int site)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].who();
}
@Override
public int whoVertex(int site, int level)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].who(level);
}
@Override
public int whatVertex(int site)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].what();
}
@Override
public int whatVertex(int site, int level)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].what(level);
}
@Override
public int stateVertex(int site)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].state();
}
@Override
public int stateVertex(int site, int level)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].state(level);
}
@Override
public int rotationVertex(int site)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].rotation();
}
@Override
public int rotationVertex(int site, int level)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].rotation(level);
}
@Override
public int valueVertex(int site)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].value();
}
@Override
public int valueVertex(int site, int level)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].value(level);
}
@Override
public int sizeStackVertex(final int site)
{
if (listStacksVertex[site] == null)
return 0;
return listStacksVertex[site].size();
}
@Override
public int whoEdge(int site)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].who();
}
@Override
public int whoEdge(int site, int level)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].who(level);
}
@Override
public int whatEdge(int site)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].what();
}
@Override
public int whatEdge(int site, int level)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].what(level);
}
@Override
public int stateEdge(int site)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].state();
}
@Override
public int stateEdge(int site, int level)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].state(level);
}
@Override
public int rotationEdge(int site)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].rotation();
}
@Override
public int rotationEdge(int site, int level)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].rotation(level);
}
@Override
public int valueEdge(int site)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].value();
}
@Override
public int valueEdge(int site, int level)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].value(level);
}
@Override
public int sizeStackEdge(final int site)
{
if (listStacksEdge[site] == null)
return 0;
return listStacksEdge[site].size();
}
@Override
public int remove(final State state, final int site, final SiteType graphElement)
{
if (graphElement == SiteType.Cell)
return super.remove(state, site, graphElement);
else if (graphElement == SiteType.Vertex)
{
if (listStacksVertex[site] == null)
return 0;
final int componentRemove = listStacksVertex[site].what();
listStacksVertex[site - offset].remove();
listStacksVertex[site].decrementSize();
return componentRemove;
}
// Edge
if (listStacksEdge[site] == null)
return 0;
final int componentRemove = listStacksEdge[site].what();
listStacksEdge[site - offset].remove();
listStacksEdge[site].decrementSize();
return componentRemove;
}
@Override
public int remove(final State state, final int site, final int level, final SiteType graphElement)
{
if (graphElement == SiteType.Cell)
super.remove(state, site, level, graphElement);
else if (graphElement == SiteType.Vertex)
{
if (listStacksVertex[site] == null)
return 0;
final int componentRemove = listStacksVertex[site].what(level);
listStacksVertex[site - offset].remove(level);
listStacksVertex[site].decrementSize();
return componentRemove;
}
// Edge
if (listStacksEdge[site] == null)
return 0;
final int componentRemove = listStacksEdge[site].what(level);
listStacksEdge[site - offset].remove(level);
listStacksEdge[site].decrementSize();
return componentRemove;
}
@Override
public void addToEmpty(final int site, final SiteType graphType)
{
if (graphType.equals(SiteType.Cell))
empty.add(site - offset);
else if (graphType.equals(SiteType.Edge))
emptyEdge.add(site);
else
emptyVertex.add(site);
}
@Override
public void removeFromEmpty(final int site, final SiteType graphType)
{
if (graphType.equals(SiteType.Cell))
empty.remove(site - offset);
else if (graphType.equals(SiteType.Edge))
emptyEdge.remove(site);
else
emptyVertex.remove(site);
}
@Override
public boolean isHidden(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHidden(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return listStacksEdge[site].isHidden(player, level);
}
else
{
if (!hiddenVertexInfo)
return false;
return listStacksVertex[site].isHidden(player, level);
}
}
@Override
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenWhat(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return listStacksEdge[site].isHiddenWhat(player, level);
}
else
{
if (!hiddenVertexInfo)
return false;
return listStacksVertex[site].isHiddenWhat(player, level);
}
}
@Override
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenWho(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return listStacksEdge[site].isHiddenWho(player, level);
}
else
{
if (!hiddenVertexInfo)
return false;
return listStacksVertex[site].isHiddenWho(player, level);
}
}
@Override
public boolean isHiddenState(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenState(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return listStacksEdge[site].isHiddenState(player, level);
}
else
{
if (!hiddenVertexInfo)
return false;
return listStacksVertex[site].isHiddenState(player, level);
}
}
@Override
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenRotation(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return listStacksEdge[site].isHiddenRotation(player, level);
}
else
{
if (!hiddenVertexInfo)
return false;
return listStacksVertex[site].isHiddenRotation(player, level);
}
}
@Override
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenValue(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return listStacksEdge[site].isHiddenValue(player, level);
}
else
{
if (!hiddenVertexInfo)
return false;
return listStacksVertex[site].isHiddenValue(player, level);
}
}
@Override
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
return super.isHiddenCount(player, site, level, graphElementType);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return false;
return listStacksEdge[site].isHiddenCount(player, level);
}
else
{
if (!hiddenVertexInfo)
return false;
return listStacksVertex[site].isHiddenCount(player, level);
}
}
@Override
public void setHidden(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHidden(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
listStacksEdge[site].setHidden(player, level, on);
}
else
{
if (!hiddenVertexInfo)
return;
listStacksVertex[site].setHidden(player, level, on);
}
}
@Override
public void setHiddenWhat(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenWhat(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
listStacksEdge[site].setHiddenWhat(player, level, on);
}
else
{
if (!hiddenVertexInfo)
return;
listStacksVertex[site].setHiddenWhat(player, level, on);
}
}
@Override
public void setHiddenWho(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenWho(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
listStacksEdge[site].setHiddenWho(player, level, on);
}
else
{
if (!hiddenVertexInfo)
return;
listStacksVertex[site].setHiddenWho(player, level, on);
}
}
@Override
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenState(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
listStacksEdge[site].setHiddenState(player, level, on);
}
else
{
if (!hiddenVertexInfo)
return;
listStacksVertex[site].setHiddenState(player, level, on);
}
}
@Override
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenRotation(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
listStacksEdge[site].setHiddenRotation(player, level, on);
}
else
{
if (!hiddenVertexInfo)
return;
listStacksVertex[site].setHiddenRotation(player, level, on);
}
}
@Override
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenValue(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
listStacksEdge[site].setHiddenValue(player, level, on);
}
else
{
if (!hiddenVertexInfo)
return;
listStacksVertex[site].setHiddenValue(player, level, on);
}
}
@Override
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (graphElementType == SiteType.Cell || container().index() != 0 || graphElementType == null)
super.setHiddenCount(state, player, site, level, graphElementType, on);
else if (graphElementType == SiteType.Edge)
{
if (!hiddenEdgeInfo)
return;
listStacksEdge[site].setHiddenCount(player, level, on);
}
else
{
if (!hiddenVertexInfo)
return;
listStacksVertex[site].setHiddenCount(player, level, on);
}
}
@Override
public Region emptyRegion(final SiteType graphType)
{
if (graphType.equals(SiteType.Cell))
return empty;
else if (graphType.equals(SiteType.Edge))
return emptyEdge;
else
return emptyVertex;
}
@Override
public int countVertex(int site)
{
return whoVertex(site) == 0 ? 0 : 1;
}
@Override
public int countEdge(int site)
{
return whoEdge(site) == 0 ? 0 : 1;
}
@Override
public boolean isEmptyVertex(final int vertex)
{
return emptyVertex.contains(vertex);
}
@Override
public boolean isEmptyEdge(final int edge)
{
return emptyEdge.contains(edge);
}
}
| 27,256 | 24.959048 | 152 | java |
Ludii | Ludii-master/Core/src/other/state/stacking/ContainerStateStacks.java | package other.state.stacking;
import java.util.Arrays;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.state.GameType;
import main.Constants;
import main.collections.ChunkSet;
import other.state.State;
import other.state.zhash.HashedBitSet;
import other.state.zhash.HashedChunkStack;
import other.state.zhash.ZobristHashGenerator;
import other.state.zhash.ZobristHashUtilities;
import other.topology.Cell;
/**
* Global State for a stacking container item.
*
* @author Eric.Piette
*/
public class ContainerStateStacks extends BaseContainerStateStacking
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Type of Item on the stack on a site. */
private final HashedChunkStack[] chunkStacks;
/** Playable sites (for boardless games). */
private final HashedBitSet playable;
private final long[][][] chunkStacksWhatHash;
private final long[][][] chunkStacksWhoHash;
private final long[][][] chunkStacksStateHash;
private final long[][][] chunkStacksRotationHash;
private final long[][][] chunkStacksValueHash;
private final long[][][] chunkStacksHiddenHash;
private final long[][][] chunkStacksHiddenWhatHash;
private final long[][][] chunkStacksHiddenWhoHash;
private final long[][][] chunkStacksHiddenStateHash;
private final long[][][] chunkStacksHiddenRotationHash;
private final long[][][] chunkStacksHiddenValueHash;
private final long[][][] chunkStacksHiddenCountHash;
private final long[][] chunkStacksSizeHash;
/** The type of stack. */
protected final int type;
/** The number of components. */
public final int numComponents;
/** The number of players. */
public final int numPlayers;
/** The number of states. */
public final int numStates;
/** The number of rotations. */
public final int numRotation;
/** The number of piece values. */
public final int numValues;
/** True if the state involves hidden info. */
private final boolean hiddenInfo;
//-------------------------------------------------------------------------
/**
* Constructor.
* @param generator
* @param game
* @param container
* @param type
*/
public ContainerStateStacks
(
final ZobristHashGenerator generator,
final Game game,
final Container container,
final int type
)
{
super
(
game,
container,
container.numSites()
);
final int numSites = container.topology().cells().size();
chunkStacks = new HashedChunkStack[numSites];
this.numComponents = game.numComponents();
this.numPlayers = game.players().count();
this.numStates = game.maximalLocalStates();
this.numRotation = game.maximalRotationStates();
this.numValues = Constants.MAX_VALUE_PIECE;
final int maxValWhat = numComponents;
final int maxValWho = numPlayers + 1;
final int maxValState = numStates;
final int maxValRotation = numRotation;
final int maxValues = numValues;
chunkStacksWhatHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, maxValWhat + 1);
chunkStacksWhoHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, maxValWho + 1);
chunkStacksStateHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, maxValState + 1);
chunkStacksRotationHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, maxValRotation + 1);
chunkStacksValueHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, maxValues + 1);
chunkStacksSizeHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT);
this.type = type;
if ((game.gameFlags() & GameType.HiddenInfo) == 0L)
{
chunkStacksHiddenHash = null;
chunkStacksHiddenWhatHash = null;
chunkStacksHiddenWhoHash = null;
chunkStacksHiddenStateHash = null;
chunkStacksHiddenRotationHash = null;
chunkStacksHiddenValueHash = null;
chunkStacksHiddenCountHash = null;
hiddenInfo = false;
}
else
{
chunkStacksHiddenHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenWhatHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenWhoHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenStateHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenRotationHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenValueHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, 2);
chunkStacksHiddenCountHash = ZobristHashUtilities.getSequence(generator, numSites, Constants.MAX_STACK_HEIGHT, 2);
hiddenInfo = true;
}
if (game.isBoardless() && container.index() == 0)
{
playable = new HashedBitSet(generator, numSites);
}
else
{
playable = null;
}
}
/**
* Copy constructor.
*
* @param other
*/
public ContainerStateStacks(final ContainerStateStacks other)
{
super(other);
this.numComponents = other.numComponents;
this.numPlayers = other.numPlayers;
this.numStates = other.numStates;
this.numRotation = other.numRotation;
this.numValues = other.numValues;
playable = (other.playable == null) ? null : other.playable.clone();
if (other.chunkStacks == null)
{
chunkStacks = null;
}
else
{
chunkStacks = new HashedChunkStack[other.chunkStacks.length];
for (int i = 0; i < other.chunkStacks.length; ++i)
{
final HashedChunkStack otherChunkStack = other.chunkStacks[i];
if (otherChunkStack != null)
{
chunkStacks[i] = otherChunkStack.clone();
}
}
}
chunkStacksWhatHash = other.chunkStacksWhatHash;
chunkStacksWhoHash = other.chunkStacksWhoHash;
chunkStacksStateHash = other.chunkStacksStateHash;
chunkStacksRotationHash = other.chunkStacksRotationHash;
chunkStacksValueHash = other.chunkStacksValueHash;
chunkStacksSizeHash = other.chunkStacksSizeHash;
type = other.type;
hiddenInfo = other.hiddenInfo;
if (other.chunkStacksHiddenHash == null)
{
chunkStacksHiddenHash = null;
chunkStacksHiddenWhatHash = null;
chunkStacksHiddenWhoHash = null;
chunkStacksHiddenStateHash = null;
chunkStacksHiddenRotationHash = null;
chunkStacksHiddenValueHash = null;
chunkStacksHiddenCountHash = null;
}
else
{
chunkStacksHiddenHash = other.chunkStacksWhatHash;
chunkStacksHiddenWhatHash = other.chunkStacksHiddenWhatHash;
chunkStacksHiddenWhoHash = other.chunkStacksHiddenWhoHash;
chunkStacksHiddenStateHash = other.chunkStacksHiddenStateHash;
chunkStacksHiddenRotationHash = other.chunkStacksHiddenRotationHash;
chunkStacksHiddenValueHash = other.chunkStacksHiddenValueHash;
chunkStacksHiddenCountHash = other.chunkStacksHiddenCountHash;
}
}
//-------------------------------------------------------------------------
@Override
protected long calcCanonicalHash(final int[] siteRemap, final int[] edgeRemap, final int[] vertexRemap, final int[] playerRemap, final boolean whoOnly)
{
long hash = 0;
if (offset != 0) return 0; // Not the board!
for (int pos = 0; pos < chunkStacks.length && pos < siteRemap.length; pos++)
{
final int newPos = siteRemap[pos];
if (chunkStacks[pos] == null) continue;
hash ^= chunkStacks[pos].remapHashTo (
chunkStacksWhatHash[newPos],
chunkStacksWhoHash[newPos],
chunkStacksStateHash[newPos],
chunkStacksRotationHash[newPos],
chunkStacksValueHash[newPos],
chunkStacksSizeHash[newPos],
whoOnly);
}
return hash;
}
//-------------------------------------------------------------------------
@Override
public void reset(final State trialState, final Game game)
{
super.reset(trialState, game);
for (final HashedChunkStack set : chunkStacks)
{
if (set == null) continue;
trialState.updateStateHash(set.calcHash());
}
Arrays.fill(chunkStacks, null);
}
private void verifyPresent(final int site)
{
if (chunkStacks[site - offset] != null)
return;
chunkStacks[site - offset] = new HashedChunkStack(
numComponents, numPlayers, numStates, numRotation, numValues,
type, hiddenInfo,
chunkStacksWhatHash[site - offset],
chunkStacksWhoHash[site - offset],
chunkStacksStateHash[site - offset],
chunkStacksRotationHash[site - offset],
chunkStacksValueHash[site - offset],
chunkStacksSizeHash[site - offset]);
}
//-------------------------------------------------------------------------
@Override
public void addItem
(
final State trialState,
final int site,
final int what,
final int who,
final Game game
)
{
verifyPresent(site);
chunkStacks[site - offset].incrementSize(trialState);
chunkStacks[site - offset].setWhat(trialState, what);
chunkStacks[site - offset].setWho(trialState, who);
if (playable != null)
{
setPlayable(trialState, site - offset, false);
final Cell cell = container().topology().cells().get(site);
for (final Cell vNbors : cell.adjacent())
if (!isOccupied(vNbors.index()))
setPlayable(trialState, vNbors.index(), true);
}
}
@Override
public void addItem
(
final State trialState,
final int site,
final int what,
final int who,
final Game game,
final boolean[] hide,
final boolean masked
)
{
verifyPresent(site);
chunkStacks[site - offset].incrementSize(trialState);
chunkStacks[site - offset].setWhat(trialState, what);
chunkStacks[site - offset].setWho(trialState, who);
if (playable != null)
{
setPlayable(trialState, site, false);
final Cell cell = container().topology().cells().get(site);
for (final Cell vNbors : cell.adjacent())
if (!isOccupied(vNbors.index()))
setPlayable(trialState, vNbors.index(), true);
}
}
@Override
public void addItem
(
final State trialState,
final int site,
final int what,
final int who,
final int stateVal,
final int rotationVal,
final int value,
final Game game
)
{
verifyPresent(site);
chunkStacks[site - offset].incrementSize(trialState);
chunkStacks[site - offset].setWhat(trialState, what);
chunkStacks[site - offset].setWho(trialState, who);
chunkStacks[site - offset].setState(trialState, stateVal);
chunkStacks[site - offset].setRotation(trialState, rotationVal);
chunkStacks[site - offset].setValue(trialState, value);
if (playable != null)
{
setPlayable(trialState, site, false);
final Cell cell = container().topology().cells().get(site);
for (final Cell vNbors : cell.adjacent())
if (!isOccupied(vNbors.index()))
setPlayable(trialState, vNbors.index(), true);
}
}
@Override
public void insert
(
final State trialState,
final SiteType siteType,
final int site,
final int level,
final int whatItem,
final int whoItem,
final int state,
final int rotation,
final int value,
Game game
)
{
if (siteType == null || siteType.equals(SiteType.Cell) || container().index() != 0)
insertCell(trialState, site, level, whatItem, whoItem, state, rotation, value, game);
else if (siteType.equals(SiteType.Edge))
insertEdge(trialState, site, level, whatItem, whoItem, state, rotation, value, game);
else
insertVertex(trialState, site, level, whatItem, whoItem, state, rotation, value, game);
}
@Override
public void insertCell
(
final State trialState,
final int site,
final int level,
final int what,
final int who,
final int state,
final int rotation,
final int value,
final Game game
)
{
verifyPresent(site);
final int size = chunkStacks[site - offset].size();
final boolean wasEmpty = (size == 0);
if (level == size)
{
chunkStacks[site - offset].incrementSize(trialState);
chunkStacks[site - offset].setWhat(trialState, what);
chunkStacks[site - offset].setWho(trialState, who);
chunkStacks[site - offset].setState(trialState, (state == Constants.UNDEFINED ? 0 : state));
chunkStacks[site - offset].setRotation(trialState, (rotation == Constants.UNDEFINED ? 0 : rotation));
chunkStacks[site - offset].setValue(trialState, (value == Constants.UNDEFINED ? 0 : value));
}
else if (level < size)
{
chunkStacks[site - offset].incrementSize(trialState);
for (int i = size - 1; i >= level; i--)
{
final int whatLevel = chunkStacks[site - offset].what(i);
chunkStacks[site - offset].setWhat(trialState, whatLevel, i + 1);
final int whoLevel = chunkStacks[site - offset].who(i);
chunkStacks[site - offset].setWho(trialState, whoLevel, i + 1);
final int rotationLevel = chunkStacks[site - offset].rotation(i);
chunkStacks[site - offset].setRotation(trialState, rotationLevel, i + 1);
final int valueLevel = chunkStacks[site - offset].value(i);
chunkStacks[site - offset].setValue(trialState, valueLevel, i + 1);
final int stateLevel = chunkStacks[site - offset].state(i);
chunkStacks[site - offset].setState(trialState, stateLevel, i + 1);
}
chunkStacks[site - offset].setWhat(trialState, what, level);
chunkStacks[site - offset].setWho(trialState, who, level);
chunkStacks[site - offset].setState(trialState, (state == Constants.UNDEFINED ? 0 : state), level);
chunkStacks[site - offset].setRotation(trialState, (rotation == Constants.UNDEFINED ? 0 : rotation), level);
chunkStacks[site - offset].setValue(trialState, (value == Constants.UNDEFINED ? 0 : value), level);
}
final boolean isEmpty = (chunkStacks[site - offset].size() == 0);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmptyCell(site);
else
removeFromEmptyCell(site);
}
@Override
public int whoCell(final int site)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].who();
}
@Override
public int whoCell(final int site, final int level)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].who(level);
}
@Override
public int whatCell(final int site)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].what();
}
@Override
public int whatCell(final int site, final int level)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].what(level);
}
//-------------------------------------------------------------------------
@Override
public void setSite
(
final State trialState,
final int site,
final int whoVal,
final int whatVal,
final int countVal,
final int stateVal,
final int rotationVal,
final int valueVal,
final SiteType type
)
{
if (type == SiteType.Cell)
{
verifyPresent(site);
final boolean wasEmpty = isEmpty(site, SiteType.Cell);
if (whoVal != Constants.UNDEFINED)
chunkStacks[site - offset].setWho(trialState, whoVal);
if (whatVal != Constants.UNDEFINED)
chunkStacks[site - offset].setWhat(trialState, whatVal);
if (stateVal != Constants.UNDEFINED)
chunkStacks[site - offset].setState(trialState, stateVal);
if (rotationVal != Constants.UNDEFINED)
chunkStacks[site - offset].setRotation(trialState, rotationVal);
if (valueVal != Constants.UNDEFINED)
chunkStacks[site - offset].setValue(trialState, valueVal);
final boolean isEmpty = isEmpty(site, SiteType.Cell);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
{
addToEmptyCell(site);
if (playable != null)
{
checkPlayable(trialState, site - offset);
final Cell v = container().topology().cells().get(site - offset);
for (final Cell vNbors : v.adjacent())
checkPlayable(trialState, vNbors.index());
}
}
else
{
removeFromEmptyCell(site - offset);
if (playable != null)
{
setPlayable(trialState, site - offset, false);
final Cell v = container().topology().cells().get(site - offset);
for (final Cell vNbors : v.adjacent())
if (!isOccupied(vNbors.index()))
setPlayable(trialState, vNbors.index(), true);
}
}
}
}
@Override
public void setSite
(
final State trialState,
final int site,
final int level,
final int whoVal,
final int whatVal,
final int countVal,
final int stateVal,
final int rotationVal,
final int valueVal
)
{
verifyPresent(site);
final boolean wasEmpty = isEmpty(site, SiteType.Cell);
if (whoVal != Constants.UNDEFINED) chunkStacks[site - offset].setWho(trialState, whoVal, level);
if (whatVal != Constants.UNDEFINED) chunkStacks[site - offset].setWhat(trialState, whatVal, level);
if (stateVal != Constants.UNDEFINED) chunkStacks[site - offset].setState(trialState, stateVal, level);
if (rotationVal != Constants.UNDEFINED) chunkStacks[site - offset].setRotation(trialState, rotationVal, level);
if (valueVal != Constants.UNDEFINED) chunkStacks[site - offset].setValue(trialState, valueVal, level);
final boolean isEmpty = isEmpty(site, SiteType.Cell);
if (wasEmpty == isEmpty) return;
if (isEmpty)
{
addToEmptyCell(site);
if (playable != null)
{
checkPlayable(trialState, site - offset);
final Cell v = container().topology().cells().get(site - offset);
for (final Cell vNbors : v.adjacent())
checkPlayable(trialState, vNbors.index());
}
}
else
{
removeFromEmptyCell(site - offset);
if (playable != null)
{
setPlayable(trialState, site - offset, false);
final Cell v = container().topology().cells().get(site - offset);
for (final Cell vNbors : v.adjacent())
if (!isOccupied(vNbors.index()))
setPlayable(trialState, vNbors.index(), true);
}
}
}
private void checkPlayable(final State trialState, final int site)
{
if (isOccupied(site - offset))
{
setPlayable(trialState, site - offset, false);
return;
}
final Cell v = container().topology().cells().get(site - offset);
for (final Cell vNbors : v.adjacent())
if (isOccupied(vNbors.index()))
{
setPlayable(trialState, site - offset, true);
return;
}
setPlayable(trialState, site - offset, false);
}
//-------------------------------------------------------------------------
@Override
public boolean isOccupied(final int site)
{
return chunkStacks[site - offset] != null && chunkStacks[site - offset].what() != 0;
}
//-------------------------------------------------------------------------
@Override
public int stateCell(final int site)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].state();
}
@Override
public int stateCell(final int site, final int level)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].state(level);
}
@Override
public int rotationCell(final int site)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].rotation();
}
@Override
public int rotationCell(final int site, final int level)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].rotation(level);
}
@Override
public int valueCell(final int site)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].value();
}
@Override
public int valueCell(final int site, final int level)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].value(level);
}
@Override
public int remove
(
final State state,
final int site,
final SiteType graphElement
)
{
if (chunkStacks[site - offset] == null)
return 0;
final int componentRemove = chunkStacks[site - offset].what();
chunkStacks[site - offset].setWhat(state, 0);
chunkStacks[site - offset].setWho(state, 0);
chunkStacks[site - offset].setState(state, 0);
chunkStacks[site - offset].setRotation(state, 0);
chunkStacks[site - offset].setValue(state, 0);
chunkStacks[site - offset].decrementSize(state);
return componentRemove;
}
@Override
public int remove
(
final State state,
final int site,
final int level,
final SiteType graphElement
)
{
if (chunkStacks[site - offset] == null)
return 0;
final int componentRemove = chunkStacks[site - offset].what(level);
for (int i = level; i < sizeStackCell(site) - 1; i++)
{
chunkStacks[site - offset].setWhat(state, chunkStacks[site - offset].what(i + 1), i);
chunkStacks[site - offset].setWho(state, chunkStacks[site - offset].who(i + 1), i);
chunkStacks[site - offset].setState(state, chunkStacks[site - offset].state(i + 1), i);
chunkStacks[site - offset].setRotation(state, chunkStacks[site - offset].rotation(i + 1), i);
chunkStacks[site - offset].setValue(state, chunkStacks[site - offset].value(i + 1), i);
}
chunkStacks[site - offset].setWhat(state, 0);
chunkStacks[site - offset].setWho(state, 0);
chunkStacks[site - offset].decrementSize(state);
return componentRemove;
}
@Override
public int remove
(
final State state,
final int site,
final int level
)
{
if (chunkStacks[site - offset] == null)
return 0;
final int componentRemove = chunkStacks[site - offset].what(level);
for (int i = level; i < sizeStackCell(site) - 1; i++)
{
chunkStacks[site - offset].setWhat(state, chunkStacks[site - offset].what(i + 1), i);
chunkStacks[site - offset].setWho(state, chunkStacks[site - offset].who(i + 1), i);
chunkStacks[site - offset].setState(state, chunkStacks[site - offset].state(i + 1), i);
chunkStacks[site - offset].setRotation(state, chunkStacks[site - offset].rotation(i + 1), i);
chunkStacks[site - offset].setValue(state, chunkStacks[site - offset].value(i + 1), i);
}
chunkStacks[site - offset].setWhat(state, 0);
chunkStacks[site - offset].setWho(state, 0);
chunkStacks[site - offset].decrementSize(state);
return componentRemove;
}
@Override
public void removeStack(final State state, final int site)
{
if (chunkStacks[site - offset] == null)
return;
state.updateStateHash(chunkStacks[site - offset].calcHash());
chunkStacks[site - offset] = null;
}
@Override
public int countCell(final int site)
{
return whoCell(site) == 0 ? 0 : 1;
}
//-------------------------------------------------------------------------
@Override
public int sizeStackCell(final int site)
{
if (chunkStacks[site - offset] == null)
return 0;
return chunkStacks[site - offset].size();
}
@Override
public int sizeStackVertex(final int site)
{
return 0;
}
@Override
public int sizeStackEdge(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public ContainerStateStacks deepClone()
{
return new ContainerStateStacks(this);
}
//-------------------------------------------------------------------------
@Override
public boolean isHidden(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return chunkStacks[site - offset].isHidden(player, site, level, graphElementType);
}
@Override
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return chunkStacks[site - offset].isHiddenWhat(player, site, level, graphElementType);
}
@Override
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return chunkStacks[site - offset].isHiddenWho(player, site, level, graphElementType);
}
@Override
public boolean isHiddenState(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return chunkStacks[site - offset].isHiddenState(player, site, level, graphElementType);
}
@Override
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return chunkStacks[site - offset].isHiddenRotation(player, site, level, graphElementType);
}
@Override
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return chunkStacks[site - offset].isHiddenValue(player, site, level, graphElementType);
}
@Override
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return chunkStacks[site - offset].isHiddenCount(player, site, level, graphElementType);
}
@Override
public void setHidden(final State state, final int player, final int site, final int level, final SiteType graphElementType,
final boolean on)
{
if (!hiddenInfo)
return;
chunkStacks[site - offset].setHidden(state, player, site, level, graphElementType, on);
}
@Override
public void setHiddenWhat(final State state, final int player, final int site, final int level, final SiteType graphElementType,
final boolean on)
{
if (!hiddenInfo)
return;
chunkStacks[site - offset].setHiddenWhat(state, player, site, level, graphElementType, on);
}
@Override
public void setHiddenWho(final State state, final int player, final int site, final int level, final SiteType graphElementType,
final boolean on)
{
if (!hiddenInfo)
return;
chunkStacks[site - offset].setHiddenWho(state, player, site, level, graphElementType, on);
}
@Override
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
chunkStacks[site - offset].setHiddenState(state, player, site, level, graphElementType, on);
}
@Override
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
chunkStacks[site - offset].setHiddenRotation(state, player, site, level, graphElementType, on);
}
@Override
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
chunkStacks[site - offset].setHiddenValue(state, player, site, level, graphElementType, on);
}
@Override
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
chunkStacks[site - offset].setHiddenCount(state, player, site, level, graphElementType, on);
}
//-------------------------------------------------------------------------
@Override
public boolean isPlayable(final int site)
{
if (playable == null)
throw new RuntimeException("Tried to access playable bitset in non-boardless game.");
return playable.get(site - offset);
}
@Override
public void setPlayable(final State trialState, final int site, final boolean on)
{
playable.set(trialState, site - offset, on);
}
@Override
public int whoEdge(final int edge)
{
return 0;
}
@Override
public int whoVertex(final int vertex)
{
return 0;
}
@Override
public int whatEdge(int site)
{
return 0;
}
@Override
public int countEdge(int site)
{
return 0;
}
@Override
public int stateEdge(int site)
{
return 0;
}
@Override
public int rotationEdge(int site)
{
return 0;
}
@Override
public int valueEdge(int site)
{
return 0;
}
@Override
public int whatVertex(int site)
{
return 0;
}
@Override
public int countVertex(int site)
{
return 0;
}
@Override
public int stateVertex(int site)
{
return 0;
}
@Override
public int rotationVertex(int site)
{
return 0;
}
@Override
public int valueVertex(int site)
{
return 0;
}
@Override
public int whoVertex(int site, int level)
{
return 0;
}
@Override
public int whatVertex(int site, int level)
{
return 0;
}
@Override
public int stateVertex(int site, int level)
{
return 0;
}
@Override
public int rotationVertex(int site, int level)
{
return 0;
}
@Override
public int valueVertex(int site, int level)
{
return 0;
}
@Override
public int whoEdge(int site, int level)
{
return 0;
}
@Override
public int whatEdge(int site, int level)
{
return 0;
}
@Override
public int stateEdge(int site, int level)
{
return 0;
}
@Override
public int rotationEdge(int site, int level)
{
return 0;
}
@Override
public int valueEdge(int site, int level)
{
return 0;
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing todo.
}
@Override
public void insertVertex(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// Nothing todo.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game)
{
// Nothing todo.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing todo.
}
@Override
public void removeStackVertex(State trialState, int site)
{
// Nothing todo.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing todo.
}
@Override
public void insertEdge(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// Nothing todo.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game)
{
// Nothing todo.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing todo.
}
@Override
public void removeStackEdge(State trialState, int site)
{
// Nothing todo.
}
//-------------------------------------------------------------------------
@Override
public void setValueCell(final State trialState, final int site, final int valueVal)
{
// Nothing to do.
}
@Override
public void setCount(final State trialState, final int site, final int countVal)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override public ChunkSet emptyChunkSetCell() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet emptyChunkSetVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet emptyChunkSetEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhoVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhoCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhoEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhoVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhoCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhoEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhatVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhatCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhatEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhatVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhatCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhatEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoVertex(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoCell(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoEdge(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatVertex(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatCell(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatEdge(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoVertex(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoCell(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoEdge(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatVertex(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatCell(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatEdge(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhoVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhoCell() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhoEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhatVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhatCell() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhatEdge() { throw new UnsupportedOperationException("TODO"); }
}
| 36,205 | 28.459723 | 157 | java |
Ludii | Ludii-master/Core/src/other/state/stacking/ContainerStateStacksLarge.java | package other.state.stacking;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.state.GameType;
import main.Constants;
import main.collections.ChunkSet;
import main.collections.ListStack;
import other.state.State;
import other.state.zhash.ZobristHashGenerator;
/**
* Container State for large stacks on cell.
*
* @author Eric.Piette and mrraow
*/
public class ContainerStateStacksLarge extends BaseContainerStateStacking
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Type of Item on the stack on a site. */
private ListStack[] listStacks;
/** The type of stack. */
protected final int type;
/** The number of components. */
public final int numComponents;
/** The number of players. */
public final int numPlayers;
/** The number of states. */
public final int numStates;
/** The number of rotations. */
public final int numRotation;
/** The number of piece values. */
public final int numValues;
/** True if the state involves hidden info. */
private final boolean hiddenInfo;
//-------------------------------------------------------------------------
/**
* @param generator
* @param game
* @param container
* @param type
*/
public ContainerStateStacksLarge
(
final ZobristHashGenerator generator,
final Game game,
final Container container,
final int type
)
{
super(game, container, container.numSites());
this.type = type;
final int numSites = container.topology().cells().size();
listStacks = new ListStack[numSites];
this.numComponents = game.numComponents();
this.numPlayers = game.players().count();
this.numStates = game.maximalLocalStates();
this.numRotation = game.maximalRotationStates();
this.numValues = Constants.MAX_VALUE_PIECE;
if ((game.gameFlags() & GameType.HiddenInfo) == 0L)
hiddenInfo = false;
else
hiddenInfo = true;
for (int i = 0 ; i < listStacks.length; i++)
listStacks[i] = new ListStack(numComponents, numPlayers, numStates, numRotation, numValues, type, hiddenInfo);
}
/**
* Copy constructor.
*
* @param other
*/
public ContainerStateStacksLarge(final ContainerStateStacksLarge other)
{
super(other);
this.numComponents = other.numComponents;
this.numPlayers = other.numPlayers;
this.numStates = other.numStates;
this.numRotation = other.numRotation;
this.numValues = other.numValues;
if (other.listStacks == null)
{
listStacks = null;
}
else
{
listStacks = new ListStack[other.listStacks.length];
for(int i = 0 ; i < listStacks.length; i++)
listStacks[i] = new ListStack(other.listStacks[i]);
}
type = other.type;
hiddenInfo = other.hiddenInfo;
}
@Override
public ContainerStateStacksLarge deepClone()
{
return new ContainerStateStacksLarge(this);
}
//-------------------------------------------------------------------------
@Override
protected long calcCanonicalHash (final int[] siteRemap, final int[] edgeRemap, final int[] vertexRemap, final int[] playerRemap, final boolean whoOnly)
{
return 0; // To do.
}
//-------------------------------------------------------------------------
@Override
public void reset(final State trialState, final Game game)
{
super.reset(trialState, game);
listStacks = new ListStack[game.equipment().totalDefaultSites()];
for (int i = 0 ; i < listStacks.length; i++)
listStacks[i] = new ListStack(numComponents, numPlayers, numStates, numRotation, numValues, type, hiddenInfo);
}
private void verifyPresent(final int site)
{
if (listStacks[site - offset] != null)
return;
}
//-------------------------------------------------------------------------
@Override
public void addItem
(
final State trialState,
final int site,
final int what,
final int who,
final Game game
)
{
verifyPresent(site);
listStacks[site - offset].incrementSize();
listStacks[site - offset].setWhat(what);
listStacks[site - offset].setWho(who);
}
@Override
public void addItem
(
final State trialState,
final int site,
final int what,
final int who,
final Game game,
final boolean[] hidden,
final boolean masked
)
{
verifyPresent(site);
listStacks[site - offset].incrementSize();
listStacks[site - offset].setWhat(what);
listStacks[site - offset].setWho(who);
}
@Override
public void addItem
(
final State trialState,
final int site,
final int what,
final int who,
final int stateVal,
final int rotationVal,
final int value,
final Game game
)
{
verifyPresent(site);
listStacks[site - offset].incrementSize();
listStacks[site - offset].setWhat(what);
listStacks[site - offset].setWho(who);
listStacks[site - offset].setState(stateVal);
listStacks[site - offset].setRotation(rotationVal);
listStacks[site - offset].setValue(value);
}
@Override
public void insert
(
final State trialState,
final SiteType siteType,
final int site,
final int level,
final int whatItem,
final int whoItem,
final int state,
final int rotation,
final int value,
final Game game
)
{
if (siteType == null || siteType.equals(SiteType.Cell) || container().index() != 0)
insertCell(trialState, site, level, whatItem, whoItem, state, rotation, value, game);
else if (siteType.equals(SiteType.Edge))
insertEdge(trialState, site, level, whatItem, whoItem, state, rotation, value, game);
else
insertVertex(trialState, site, level, whatItem, whoItem, state, rotation, value, game);
}
@Override
public void insertCell
(
final State trialState,
final int site,
final int level,
final int what,
final int who,
final int state,
final int rotation,
final int value,
final Game game
)
{
verifyPresent(site);
final int size = listStacks[site - offset].size();
final boolean wasEmpty = (size == 0);
if (level == size)
{
listStacks[site - offset].incrementSize();
listStacks[site - offset].setWhat(what);
listStacks[site - offset].setWho(who);
listStacks[site - offset].setState((state == Constants.UNDEFINED ? 0 : state));
listStacks[site - offset].setRotation((rotation == Constants.UNDEFINED ? 0 : rotation));
listStacks[site - offset].setValue((value == Constants.UNDEFINED ? 0 : value));
}
else if (level < size)
{
listStacks[site - offset].incrementSize();
for (int i = size - 1; i >= level; i--)
{
final int whatLevel = listStacks[site - offset].what(i);
listStacks[site - offset].setWhat(whatLevel, i + 1);
final int whoLevel = listStacks[site - offset].who(i);
listStacks[site - offset].setWho(whoLevel, i + 1);
final int rotationLevel = listStacks[site - offset].rotation(i);
listStacks[site - offset].setRotation(rotationLevel, i + 1);
final int valueLevel = listStacks[site - offset].value(i);
listStacks[site - offset].setValue(valueLevel, i + 1);
final int stateLevel = listStacks[site - offset].state(i);
listStacks[site - offset].setState(stateLevel, i + 1);
}
listStacks[site - offset].setWhat(what, level);
listStacks[site - offset].setWho(who, level);
listStacks[site - offset].setState((state == Constants.UNDEFINED ? 0 : state), level);
listStacks[site - offset].setRotation((rotation == Constants.UNDEFINED ? 0 : rotation), level);
listStacks[site - offset].setValue((value == Constants.UNDEFINED ? 0 : value), level);
}
final boolean isEmpty = (listStacks[site - offset].size() == 0);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmptyCell(site);
else
removeFromEmptyCell(site);
}
@Override
public int whoCell(final int site)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].who();
}
@Override
public int whoCell(final int site, final int level)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].who(level);
}
@Override
public int whatCell(final int site)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].what();
}
@Override
public int whatCell(final int site, final int level)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].what(level);
}
//-------------------------------------------------------------------------
@Override
public void setSite
(
final State trialState,
final int site,
final int whoVal,
final int whatVal,
final int countVal,
final int stateVal,
final int rotationVal,
final int valueVal,
final SiteType type
)
{
if (type == SiteType.Cell)
{
verifyPresent(site);
final boolean wasEmpty = isEmpty(site, SiteType.Cell);
if (whoVal != Constants.UNDEFINED)
listStacks[site - offset].setWho(whoVal);
if (whatVal != Constants.UNDEFINED)
listStacks[site - offset].setWhat(whatVal);
if (stateVal != Constants.UNDEFINED)
listStacks[site - offset].setState(stateVal);
if (rotationVal != Constants.UNDEFINED)
listStacks[site - offset].setRotation(rotationVal);
if (valueVal != Constants.UNDEFINED)
listStacks[site - offset].setValue(valueVal);
final boolean isEmpty = isEmpty(site, SiteType.Cell);
if (wasEmpty == isEmpty)
return;
if (isEmpty)
addToEmptyCell(site);
else
removeFromEmptyCell(site - offset);
}
}
@Override
public void setSite
(
final State trialState,
final int site,
final int level,
final int whoVal,
final int whatVal,
final int countVal,
final int stateVal,
final int rotationVal,
final int valueVal
)
{
verifyPresent(site);
final boolean wasEmpty = isEmpty(site, SiteType.Cell);
if (whoVal != Constants.UNDEFINED) listStacks[site - offset].setWho(whoVal, level);
if (whatVal != Constants.UNDEFINED) listStacks[site - offset].setWhat(whatVal, level);
if (stateVal != Constants.UNDEFINED) listStacks[site - offset].setState(stateVal, level);
if (rotationVal != Constants.UNDEFINED) listStacks[site - offset].setRotation(rotationVal, level);
if (valueVal != Constants.UNDEFINED) listStacks[site - offset].setValue(valueVal, level);
final boolean isEmpty = isEmpty(site, SiteType.Cell);
if (wasEmpty == isEmpty) return;
if (isEmpty)
addToEmptyCell(site);
else
removeFromEmptyCell(site - offset);
}
@Override
public boolean isOccupied(final int site)
{
return listStacks[site - offset] != null && listStacks[site - offset].what() != 0;
}
//-------------------------------------------------------------------------
@Override
public int stateCell(final int site)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].state();
}
@Override
public int stateCell(final int site, final int level)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].state(level);
}
@Override
public int rotationCell(final int site)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].rotation();
}
@Override
public int rotationCell(final int site, final int level)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].rotation(level);
}
@Override
public int valueCell(final int site)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].value();
}
@Override
public int valueCell(final int site, final int level)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].value(level);
}
@Override
public int remove
(
final State state,
final int site,
final SiteType graphElement
)
{
if (listStacks[site - offset] == null)
return 0;
final int componentRemove = listStacks[site - offset].what();
listStacks[site - offset].decrementSize();
listStacks[site - offset].remove();
return componentRemove;
}
@Override
public int remove
(
final State state,
final int site,
final int level,
final SiteType graphElement
)
{
if (listStacks[site - offset] == null)
return 0;
final int componentRemove = listStacks[site - offset].what(level);
listStacks[site - offset].remove(level);
listStacks[site - offset].decrementSize();
return componentRemove;
}
@Override
public int remove
(
final State state,
final int site,
final int level
)
{
if (listStacks[site - offset] == null)
return 0;
final int componentRemove = listStacks[site - offset].what(level);
for (int i = level; i < sizeStackCell(site) - 1; i++)
{
listStacks[site - offset].setWhat(listStacks[site - offset].what(i + 1), i);
listStacks[site - offset].setWho(listStacks[site - offset].who(i + 1), i);
listStacks[site - offset].setState(listStacks[site - offset].state(i + 1), i);
listStacks[site - offset].setRotation(listStacks[site - offset].rotation(i + 1), i);
listStacks[site - offset].setValue(listStacks[site - offset].value(i + 1), i);
}
listStacks[site - offset].setWhat(0);
listStacks[site - offset].setWho(0);
listStacks[site - offset].decrementSize();
return componentRemove;
}
@Override
public void removeStack(final State state, final int site)
{
if (listStacks[site - offset] == null)
return;
listStacks[site - offset] = null;
}
@Override
public int countCell(final int site)
{
return whoCell(site) == 0 ? 0 : 1;
}
//-------------------------------------------------------------------------
@Override
public int sizeStackCell(final int site)
{
if (listStacks[site - offset] == null)
return 0;
return listStacks[site - offset].size();
}
@Override
public int sizeStackVertex(final int site)
{
return 0;
}
@Override
public int sizeStackEdge(final int site)
{
return 0;
}
//-------------------------------------------------------------------------
@Override
public boolean isHidden(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return listStacks[site - offset].isHidden(player, level);
}
@Override
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return listStacks[site - offset].isHiddenWhat(player, level);
}
@Override
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return listStacks[site - offset].isHiddenWho(player, level);
}
@Override
public boolean isHiddenState(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return listStacks[site - offset].isHiddenState(player, level);
}
@Override
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return listStacks[site - offset].isHiddenRotation(player, level);
}
@Override
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return listStacks[site - offset].isHiddenValue(player, level);
}
@Override
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType graphElementType)
{
if (!hiddenInfo)
return false;
return listStacks[site - offset].isHiddenCount(player, level);
}
@Override
public void setHidden(final State state, final int player, final int site, final int level, final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
listStacks[site - offset].setHidden(player, level, on);
}
@Override
public void setHiddenWhat(final State state, final int player, final int site, final int level, final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
listStacks[site - offset].setHiddenWhat(player, level, on);
}
@Override
public void setHiddenWho(final State state, final int player, final int site, final int level, final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
listStacks[site - offset].setHiddenWho(player, level, on);
}
@Override
public void setHiddenState(final State state, final int player, final int site, final int level, final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
listStacks[site - offset].setHiddenState(player, level, on);
}
@Override
public void setHiddenRotation(final State state, final int player, final int site, final int level, final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
listStacks[site - offset].setHiddenRotation(player, level, on);
}
@Override
public void setHiddenValue(final State state, final int player, final int site, final int level, final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
listStacks[site - offset].setHiddenValue(player, level, on);
}
@Override
public void setHiddenCount(final State state, final int player, final int site, final int level, final SiteType graphElementType, final boolean on)
{
if (!hiddenInfo)
return;
listStacks[site - offset].setHiddenCount(player, level, on);
}
//-------------------------------------------------------------------------
@Override
public boolean isPlayable(final int site)
{
return listStacks[site - offset] != null;
}
@Override
public int whoEdge(final int edge)
{
return 0;
}
@Override
public int whoVertex(final int vertex)
{
return 0;
}
@Override
public int whatEdge(int site)
{
return 0;
}
@Override
public int countEdge(int site)
{
return 0;
}
@Override
public int stateEdge(int site)
{
return 0;
}
@Override
public int rotationEdge(int site)
{
return 0;
}
@Override
public int valueEdge(int site)
{
return 0;
}
@Override
public int whatVertex(int site)
{
return 0;
}
@Override
public int countVertex(int site)
{
return 0;
}
@Override
public int stateVertex(int site)
{
return 0;
}
@Override
public int rotationVertex(int site)
{
return 0;
}
@Override
public int valueVertex(int site)
{
return 0;
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing to do.
}
@Override
public void insertVertex(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// Nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game)
{
// Nothing to do.
}
@Override
public void addItemVertex(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing to do.
}
@Override
public void removeStackVertex(State trialState, int site)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game)
{
// Nothing to do.
}
@Override
public void insertEdge(State trialState, int site, int level, int whatValue, int whoId, final int state,
final int rotation, final int value, Game game)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, int stateVal, int rotationVal,
int valueVal,
Game game)
{
// Nothing to do.
}
@Override
public void addItemEdge(State trialState, int site, int whatValue, int whoId, Game game, boolean[] hiddenValues,
boolean masked)
{
// Nothing to do.
}
@Override
public void removeStackEdge(State trialState, int site)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public void setValueCell(final State trialState, final int site, final int valueVal)
{
// Nothing to do.
}
@Override
public void setCount(final State trialState, final int site, final int countVal)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override public ChunkSet emptyChunkSetCell() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet emptyChunkSetVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet emptyChunkSetEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhoVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhoCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhoEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhoVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhoCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhoEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhatVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhatCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int numChunksWhatEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhatVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhatCell() { throw new UnsupportedOperationException("TODO"); }
@Override public int chunkSizeWhatEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoVertex(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoCell(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhoEdge(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatVertex(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatCell(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean matchesWhatEdge(final int wordIdx, final long mask, final long matchingWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatVertex(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatCell(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatEdge(ChunkSet mask, ChunkSet pattern) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoVertex(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoCell(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhoEdge(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatVertex(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatCell(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public boolean violatesNotWhatEdge(ChunkSet mask, ChunkSet pattern, int startWord) { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhoVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhoCell() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhoEdge() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhatVertex() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhatCell() { throw new UnsupportedOperationException("TODO"); }
@Override public ChunkSet cloneWhatEdge() { throw new UnsupportedOperationException("TODO"); }
@Override
public int whoVertex(int site, int level)
{
return 0;
}
@Override
public int whatVertex(int site, int level)
{
return 0;
}
@Override
public int stateVertex(int site, int level)
{
return 0;
}
@Override
public int rotationVertex(int site, int level)
{
return 0;
}
@Override
public int valueVertex(int site, int level)
{
return 0;
}
@Override
public int whoEdge(int site, int level)
{
return 0;
}
@Override
public int whatEdge(int site, int level)
{
return 0;
}
@Override
public int stateEdge(int site, int level)
{
return 0;
}
@Override
public int rotationEdge(int site, int level)
{
return 0;
}
@Override
public int valueEdge(int site, int level)
{
return 0;
}
}
| 26,494 | 26.314433 | 157 | java |
Ludii | Ludii-master/Core/src/other/state/symmetry/AcceptAll.java | package other.state.symmetry;
/**
* Universal acceptor; all symmetries are valid
* @author mrraow
*/
public class AcceptAll implements SymmetryValidator
{
@Override
public boolean isValid(SymmetryType type, int angleIndex, int maxAngles)
{
return true;
}
}
| 270 | 15.9375 | 74 | java |
Ludii | Ludii-master/Core/src/other/state/symmetry/AcceptNone.java | package other.state.symmetry;
/**
* Universal rejector; no symmetries are valid, except the identity
* @author mrraow
*/
public class AcceptNone implements SymmetryValidator
{
@Override
public boolean isValid(final SymmetryType type, final int symmetryIndex, final int symmetryCount)
{
switch (type)
{
case REFLECTIONS: return false;
case ROTATIONS: return symmetryIndex==0;
case SUBSTITUTIONS: return symmetryIndex==0;
}
return false;
}
}
| 465 | 20.181818 | 99 | java |
Ludii | Ludii-master/Core/src/other/state/symmetry/ReflectionsOnly.java | package other.state.symmetry;
/**
* Only reflections are valid
* @author mrraow
*/
public class ReflectionsOnly implements SymmetryValidator
{
@Override
public boolean isValid (final SymmetryType type, final int symmetryIndex, final int symmetryCount)
{
switch(type) {
case REFLECTIONS: return true;
case ROTATIONS: return symmetryIndex==0; // Identity (element 0) only
case SUBSTITUTIONS: return symmetryIndex==0; // Identity (element 0) only
}
return true;
}
}
| 488 | 22.285714 | 100 | java |
Ludii | Ludii-master/Core/src/other/state/symmetry/RotationsOnly.java | package other.state.symmetry;
/**
* Only rotational symmetries and identity operators are valid
* @author mrraow
*/
public class RotationsOnly implements SymmetryValidator
{
@Override
public boolean isValid(final SymmetryType type, final int symmetryIndex, final int symmetryCount)
{
switch(type) {
case REFLECTIONS: return false;
case ROTATIONS: return true;
case SUBSTITUTIONS: return symmetryIndex==0; // Identity (element 0) only
}
return true;
}
}
| 477 | 21.761905 | 99 | java |
Ludii | Ludii-master/Core/src/other/state/symmetry/SubstitutionsOnly.java | package other.state.symmetry;
/**
* Only player substitutions are valid
* @author mrraow
*/
public class SubstitutionsOnly implements SymmetryValidator
{
@Override
public boolean isValid(final SymmetryType type, final int symmetryIndex, final int symmetryCount)
{
switch(type) {
case REFLECTIONS: return false;
case ROTATIONS: return symmetryIndex==0; // Identity (element 0) only
case SUBSTITUTIONS: return true;
}
return true;
}
}
| 457 | 20.809524 | 99 | java |
Ludii | Ludii-master/Core/src/other/state/symmetry/SymmetryType.java | package other.state.symmetry;
import java.util.EnumSet;
/**
* All supported types of symmetry
* @author mrraow
*/
public enum SymmetryType
{
/**
* Rotation symmetries.
*/
ROTATIONS,
/**
* Reflections symmetries.
*/
REFLECTIONS,
/**
* Substitutions symmetries.
*/
SUBSTITUTIONS;
/**
* All symmetries
*/
public static final EnumSet<SymmetryType> ALL = EnumSet.allOf(SymmetryType.class);
/**
* No symmetries
*/
public static final EnumSet<SymmetryType> NONE = EnumSet.noneOf(SymmetryType.class);
}
| 546 | 14.194444 | 85 | java |
Ludii | Ludii-master/Core/src/other/state/symmetry/SymmetryUtils.java | package other.state.symmetry;
import java.awt.geom.Point2D;
import java.util.BitSet;
/**
* Utilities to support symmetry processing
* @author mrraow
*/
public class SymmetryUtils
{
/**
* Note that ludii counts players from 1 upwards, with element 0 reserved for 'empty' and other shenanigans
* This function will provide all permutations of { 1... n } keel=ping 0 in the bottom index
* @param numPlayers
* @return a valid permutation of these players
*/
public static final int[][] playerPermutations (int numPlayers)
{
// Special case; if there are > 4 players, we have too many cases to sensibly identify, so just return the identity operator
if (numPlayers > 4)
{
int[][] permutations = new int[1][numPlayers+1];
for (int who = 1; who <= numPlayers; who++)
permutations[0][who] = who;
return permutations;
}
// Degenerate case
if (numPlayers==1) return new int[][] { { 0, 1 } };
// On with the plot
int[][] permutations = new int[factorial(numPlayers)][numPlayers+1];
for (int who = 1; who <= numPlayers; who++)
permutations[0][who] = who;
for (int p = 1; p < permutations.length; p++)
permutations[p] = nextPermutation(permutations[p-1]);
return permutations;
}
/**
* @param numPlayers
* @return numPlayers!
*/
private static int factorial(int numPlayers)
{
int product = 1;
for (int n = 1; n <= numPlayers; n++)
product *= n;
return product;
}
private static int[] nextPermutation (final int[] previous)
{
final int[] next = previous.clone();
// Find last j : next[j] < next[j+1]
int j = previous.length - 2;
while (j >= 1 && next[j] > next[j+1]) j--;
// Find last l : next[j] <= next[l]
int l = previous.length - 1;
while (next[j] > next[l]) l--;
// Swap
swap (next, j, l);
// L4: Reverse elements j+1 ... count-1:
int lo = j + 1;
int hi = previous.length - 1;
while (lo < hi) swap(next, lo++, hi--);
return next;
}
private static final void swap (final int[] array, final int idx1, final int idx2)
{
final int temp = array[idx1];
array[idx1] = array[idx2];
array[idx2] = temp;
}
/**
* @param op1
* @param op2
* @return the result when op1 then op2 are applied in order
*/
public static int[] combine(int[] op1, int[] op2)
{
final int[] result = new int[op1.length];
for (int idx = 0; idx < op1.length; idx++)
result[idx] = op2[op1[idx]];
return result;
}
/**
* @param origin
* @param source
* @param steps
* @param numSymmetries
* @return a point corresponding to source rotated around origin by the specified fraction of a circle
*/
public static Point2D rotateAroundPoint (final Point2D origin, final Point2D source, final int steps, final int numSymmetries)
{
final double angle = Math.PI * 2.0 * steps / numSymmetries;
final double normalisedX = source.getX() - origin.getX();
final double normalisedY = source.getY() - origin.getY();
final double rotatedX = normalisedX*Math.cos(angle) - normalisedY*Math.sin(angle);
final double rotatedY = normalisedY*Math.cos(angle) + normalisedX*Math.sin(angle);
return new Point2D.Double(origin.getX()+rotatedX, origin.getY()+rotatedY);
}
/**
* @param origin
* @param source
* @param steps
* @param numSymmetries
* @return a point corresponding to source reflected around a line through origin with the specified angle
*/
public static Point2D reflectAroundLine (final Point2D origin, final Point2D source, final int steps, final int numSymmetries)
{
// Special cases because tan(PI/2) is asymptotic
if (2*steps == numSymmetries)
{
final double reflectedY = source.getY();
final double reflectedX = origin.getX()*2 - source.getX();
return new Point2D.Double(reflectedX, reflectedY);
}
final double angle = Math.PI * steps / numSymmetries;
// Find the line y = mx+c
final double m = Math.tan(angle);
final double c = origin.getY() - m * origin.getX(); // calculate c = y - mx
// Reflect around the line...
final double d = (source.getX() + (source.getY() - c)*m)/(1 + m*m);
final double reflectedX = 2*d - source.getX();
final double reflectedY = 2*d*m - source.getY() + 2*c;
return new Point2D.Double(reflectedX, reflectedY);
}
/**
* @param p1
* @param p2
* @param allowedError
* @return true if two points are close enough to be considered the same (allows for precision errors in trig functions)
*/
public static boolean closeEnough (final Point2D p1, final Point2D p2, final double allowedError)
{
return p1.distance(p2) <= allowedError;
}
/**
* @param mapping
* @return Returns true if the mapping maps every entry uniquely to a number in the range 0... length-1
*/
public static boolean isBijective (final int[] mapping)
{
BitSet set = new BitSet(mapping.length);
for (int cell : mapping)
{
if (cell < 0 || cell >= mapping.length) return false;
set.set(cell);
}
return set.cardinality() == mapping.length;
}
}
| 5,097 | 27.322222 | 127 | java |
Ludii | Ludii-master/Core/src/other/state/symmetry/SymmetryValidator.java | package other.state.symmetry;
/**
* Validates a symmetry, to see if it is useful in this context.
* @author [email protected]
*/
public interface SymmetryValidator
{
/**
* NOTE: This function should almost always return true when symmetryIndex==0 - this will probably be the identity operator
*
* @param type The type of symmetry, e.g. reflection, rotation
* @param symmetryIndex index of this symmetry, often an angle
* @param symmetryCount number of symmetries
* @return Whether the symmetry suits this context.
*/
public boolean isValid(final SymmetryType type, final int symmetryIndex, final int symmetryCount);
}
| 640 | 32.736842 | 125 | java |
Ludii | Ludii-master/Core/src/other/state/track/OnTrackIndices.java | package other.state.track;
import java.util.ArrayList;
import java.util.List;
import game.equipment.container.board.Track;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import main.collections.FastTIntArrayList;
/**
* Structure used to know where are each kind of piece on each track.
* Note: TrackIndex --> IndexComponent --> IndexOnTrack --> Count.
*
* @author Eric.Piette
*/
public class OnTrackIndices
{
/** The map for each track to know where are the pieces on each track. */
protected final List<FastTIntArrayList>[] onTrackIndices;
/**
* The map between the index of the tracks and the corresponding sites.
*/
protected final TIntObjectMap<FastTIntArrayList>[] locToIndex;
/**
* Constructor.
*
* @param tracks The list of tracks.
* @param numWhat The number of components.
*/
@SuppressWarnings("unchecked")
public OnTrackIndices(final List<Track> tracks, final int numWhat)
{
onTrackIndices = new List[tracks.size()];
locToIndex = new TIntObjectMap[tracks.size()];
for (int trackIdx = 0; trackIdx < tracks.size(); ++trackIdx)
{
final Track track = tracks.get(trackIdx);
final int size = track.elems().length;
final List<FastTIntArrayList> onTracks = new ArrayList<FastTIntArrayList>();
for (int i = 0; i < numWhat; i++)
{
final FastTIntArrayList indicesTrack = new FastTIntArrayList();
for (int j = 0; j < size; j++)
indicesTrack.add(0);
onTracks.add(indicesTrack);
}
onTrackIndices[trackIdx] = onTracks;
final TIntObjectMap<FastTIntArrayList> locToIndexTrack = new TIntObjectHashMap<FastTIntArrayList>();
for (int j = 0; j < size; j++)
{
final int site = track.elems()[j].site;
if (locToIndexTrack.get(site) == null)
locToIndexTrack.put(site, new FastTIntArrayList());
locToIndexTrack.get(site).add(j);
}
locToIndex[trackIdx] = locToIndexTrack;
}
}
/**
* Deep copy.
* @param other Structure to be copied
*/
@SuppressWarnings("unchecked")
public OnTrackIndices(final OnTrackIndices other)
{
final List<FastTIntArrayList>[] otherOnTrackIndices = other.onTrackIndices;
onTrackIndices = new List[otherOnTrackIndices.length];
for (int i = 0; i < otherOnTrackIndices.length; ++i)
{
final List<FastTIntArrayList> otherOnTracks = otherOnTrackIndices[i];
final List<FastTIntArrayList> onTracks = new ArrayList<FastTIntArrayList>(otherOnTracks.size());
for (final FastTIntArrayList whatOtherOnTrack : otherOnTracks)
onTracks.add(new FastTIntArrayList(whatOtherOnTrack));
onTrackIndices[i] = onTracks;
}
// This can just be copied by reference
locToIndex = other.locToIndex;
}
/**
* Constructor that directly uses the given references for its data.
*
* @param onTrackIndices
* @param locToIndex
*/
protected OnTrackIndices
(
final List<FastTIntArrayList>[] onTrackIndices,
final TIntObjectMap<FastTIntArrayList>[] locToIndex
)
{
this.onTrackIndices = onTrackIndices;
this.locToIndex = locToIndex;
}
//------------------------------------------------------------------------
/**
* NOTE: callers should not modify the returned list or its contents!
*
* @param trackIdx The index of the track
* @return The onTracks for a what on a track.
*/
public List<FastTIntArrayList> whats(final int trackIdx)
{
return this.onTrackIndices[trackIdx];
}
/**
* NOTE: callers should not modify the returned list or its contents!
*
* @return The onTracks for each what on a track.
*/
public List<FastTIntArrayList>[] onTrackIndices()
{
return this.onTrackIndices;
}
/**
* NOTE: callers should not modify the returned list!
*
* @param trackIdx The index of the track
* @param what The component to look.
* @return The onTracks for a component on a track.
*/
public FastTIntArrayList whats(final int trackIdx, final int what)
{
return this.onTrackIndices[trackIdx].get(what);
}
/**
* @param trackIdx The index of the track
* @param what The component to look.
* @param index The index on the track.
* @return The number of pieces corresponding to the what at that index on the
* track.
*/
public int whats(final int trackIdx, final int what, final int index)
{
return this.onTrackIndices[trackIdx].get(what).getQuick(index);
}
/**
* To add some pieces to a specific index of a track.
*
* @param trackIdx The index of the track
* @param what The index of the component.
* @param count The number of pieces.
* @param index The index on the track.
*/
public void add(final int trackIdx, final int what, final int count, final int index)
{
final int currentCount = this.onTrackIndices[trackIdx].get(what).getQuick(index);
this.onTrackIndices[trackIdx].get(what).setQuick(index, currentCount + count);
}
/**
* To remove some pieces to a specific index of a track.
*
* @param trackIdx The index of the track
* @param what The index of the component.
* @param count The number of pieces.
* @param index The index on the track.
*/
public void remove(final int trackIdx, final int what, final int count, final int index)
{
final int currentCount = this.onTrackIndices[trackIdx].get(what).getQuick(index);
this.onTrackIndices[trackIdx].get(what).setQuick(index, currentCount - count);
}
/**
* NOTE: callers should not modify the returned list!
*
* @param trackIdx The index of the track
* @param what The index of the component.
* @return The list of indices on the track with at least a component on that
* type on them.
*/
public FastTIntArrayList indicesWithWhat(final int trackIdx, final int what)
{
final FastTIntArrayList indicesWithThatComponent = new FastTIntArrayList();
final FastTIntArrayList indicesOnTrack = this.onTrackIndices[trackIdx].get(what);
for (int i = 0; i < indicesOnTrack.size(); i++)
if (indicesOnTrack.getQuick(i) != 0)
indicesWithThatComponent.add(i);
return indicesWithThatComponent;
}
//------------------------------------------------------------------------
/**
* NOTE: callers should not modify the returned map or its contents!
*
* @param trackIdx The track indices.
*
* @return The map between the site and the indices of a specific track.
*/
public TIntObjectMap<FastTIntArrayList> locToIndex(final int trackIdx)
{
return locToIndex[trackIdx];
}
/**
* NOTE: callers should not modify the returned list!
*
* @param trackIdx The track indices.
* @param site The site index.
*
* @return All the indices of a specific track corresponding to a specific site.
*/
public FastTIntArrayList locToIndex(final int trackIdx, final int site)
{
final FastTIntArrayList indices = locToIndex[trackIdx].get(site);
if (indices == null)
return new FastTIntArrayList();
return indices;
}
/**
* NOTE: callers should not modify the returned list!
*
* @param trackIdx The track indices.
* @param site The site index.
* @param from The last index reached.
*
* @return All the indices of a specific track corresponding to a specific site.
*/
public FastTIntArrayList locToIndexFrom(final int trackIdx, final int site, final int from)
{
final FastTIntArrayList indices = locToIndex[trackIdx].get(site);
if (indices == null)
return new FastTIntArrayList();
final FastTIntArrayList indicesToReturn = new FastTIntArrayList();
for (int i = 0; i < indices.size(); i++)
if (indices.get(i) > from)
indicesToReturn.add(indices.get(i));
return indicesToReturn;
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof OnTrackIndices))
return false;
final OnTrackIndices other = (OnTrackIndices) obj;
if(locToIndex.length != other.locToIndex.length)
return false;
if(onTrackIndices.length != other.onTrackIndices.length)
return false;
for(int i = 0; i < locToIndex.length; i++)
if(!locToIndex[i].equals(other.locToIndex[i]))
return false;
for(int i = 0; i < onTrackIndices.length; i++)
if(!onTrackIndices[i].equals(other.onTrackIndices[i]))
return false;
return true;
}
//------------------------------------------------------------------------
@Override
public String toString()
{
String str = "OnTrackIndices:\n";
for (int i = 0; i < onTrackIndices.length; ++i)
{
str += "Track: " + i + "\n";
final List<FastTIntArrayList> whatOnTracks = onTrackIndices[i];
for (int what = 0; what < whatOnTracks.size(); what++)
{
final TIntArrayList onTracks = whatOnTracks.get(what);
for (int j = 0; j < onTracks.size(); j++)
{
if (onTracks.get(j) > 0)
str += "Component " + what + " at index " + i + " count = " + onTracks.get(j) + "\n";
}
}
str += "\n";
}
return str;
}
@Override
public int hashCode()
{
return super.hashCode();
}
}
| 8,965 | 26.931464 | 103 | java |
Ludii | Ludii-master/Core/src/other/state/track/OnTrackIndicesCOW.java | package other.state.track;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import main.collections.FastTIntArrayList;
/**
* A subclass of OnTrackIndices, with copy-on-write (COW) optimisations.
*
* @author Dennis Soemers
*/
public class OnTrackIndicesCOW extends OnTrackIndices
{
//------------------------------------------------------------------------
/** Did we make a deep copy for given onTrackIndices at given trackIdx? */
private final boolean[] copiedOnTrackIndices;
//------------------------------------------------------------------------
/**
* Copy constructor (with copy-on-write behaviour)
*
* @param other
*/
public OnTrackIndicesCOW(final OnTrackIndices other)
{
// We just copy the references
super(Arrays.copyOf(other.onTrackIndices, other.onTrackIndices.length), other.locToIndex);
// Remember that we didn't make any deep copies yet
copiedOnTrackIndices = new boolean[onTrackIndices.length];
}
//------------------------------------------------------------------------
@Override
public void add(final int trackIdx, final int what, final int count, final int index)
{
ensureDeepCopy(trackIdx);
super.add(trackIdx, what, count, index);
}
@Override
public void remove(final int trackIdx, final int what, final int count, final int index)
{
ensureDeepCopy(trackIdx);
super.remove(trackIdx, what, count, index);
}
//------------------------------------------------------------------------
/**
* Ensures that we made a deep copy of the data for the given track index
* @param trackIdx
*/
public void ensureDeepCopy(final int trackIdx)
{
// We're about to make a modification to data for given track index, so should
// make sure that we're operating on a deep copy
if (!copiedOnTrackIndices[trackIdx])
{
// Didn't deep copy yet, so need to do so now
final List<FastTIntArrayList> otherOnTracks = onTrackIndices[trackIdx];
final List<FastTIntArrayList> onTracks = new ArrayList<FastTIntArrayList>(otherOnTracks.size());
for (final FastTIntArrayList whatOtherOnTrack : otherOnTracks)
onTracks.add(new FastTIntArrayList(whatOtherOnTrack));
onTrackIndices[trackIdx] = onTracks;
copiedOnTrackIndices[trackIdx] = true;
}
}
//------------------------------------------------------------------------
}
| 2,365 | 27.853659 | 99 | java |
Ludii | Ludii-master/Core/src/other/state/zhash/HashedBitSet.java | package other.state.zhash;
import java.io.Serializable;
import java.util.BitSet;
import other.state.State;
/**
* Wrapper around ChunkSet, to make sure it is managed correctly
* If ChunkSet were an interface, I'd use the decorator pattern...
*
* @author mrraow
*/
public class HashedBitSet implements Serializable
{
private static final long serialVersionUID = 1L;
/** Which sites are hidden to which players. */
private final BitSet internalState;
private final long[] hashes;
/**
* @param generator
* @param numSites
*/
public HashedBitSet(final ZobristHashGenerator generator, final int numSites)
{
internalState = new BitSet(numSites);
hashes = ZobristHashUtilities.getSequence(generator, numSites);
}
/**
* Copy constructor, used by clone()
* @param that
*/
private HashedBitSet(final HashedBitSet that)
{
this.internalState = (BitSet) that.internalState.clone();
this.hashes = that.hashes; // Safe to just store a reference
}
/* ----------------------------------------------------------------------------------------------------
* The following methods change state, and therefore need to manage the hash value
* ---------------------------------------------------------------------------------------------------- */
/**
* Performance warning - this method will iterate through all sites to update
* the hash, so avoid at runtime
*
* @param trialState
*/
public void clear(final State trialState)
{
long hashDelta = 0L;
for (int site = internalState.nextSetBit(0); site >= 0; site = internalState.nextSetBit(site + 1))
{
hashDelta ^= hashes[site];
}
internalState.clear();
trialState.updateStateHash(hashDelta);
}
/**
* Calculates the hash of this object after the specified remapping. Either the
* sites, or the values, will be remapped and the new hash calculated. Intended
* for calculating canonical hashes.
*
* Performance Warning: this is slow; do not call during a search.
*
* @param siteRemap may be null
* @param invert
* @return the hash of this chunk, when subjected to the specified
* transformation
*/
public long calculateHashAfterRemap (final int[] siteRemap, final boolean invert)
{
long hashDelta = 0L;
if (siteRemap == null)
{
for (int site = 0; site < hashes.length; site++)
{
final boolean siteValue = internalState.get(site);
final boolean newValue = invert ? !siteValue : siteValue;
if (newValue) hashDelta ^= hashes[site];
}
return hashDelta;
}
for (int site = 0; site < hashes.length; site++)
{
final int newSite = siteRemap[site];
final boolean siteValue = internalState.get(site);
final boolean newValue = invert ? !siteValue : siteValue;
if (newValue) hashDelta ^= hashes[newSite];
}
return hashDelta;
}
/**
* Makes this a copy of src - equivalent to clear followed by or
* Performance warning - this method will iterate through all sites to update the hash, so avoid at runtime
* @param trialState
* @param src
*/
public void setTo(final State trialState, final HashedBitSet src)
{
// Possible performance improvement: calculate xor of two bitsets, iterate through all 1s in resultant set
long hashDelta = 0L;
for (int site = 0; site < hashes.length; site++)
if (internalState.get(site) != src.internalState.get(site))
hashDelta ^= hashes[site];
internalState.clear();
internalState.or(src.internalState);
trialState.updateStateHash(hashDelta);
}
/**
* To set the bits
*
* @param trialState
* @param bitIndex
* @param on
*/
public void set(final State trialState, final int bitIndex, final boolean on)
{
if (on != internalState.get(bitIndex)) trialState.updateStateHash(hashes[bitIndex]);
internalState.set(bitIndex, on);
}
/* ----------------------------------------------------------------------------------------------------
* The following methods are read-only, and do not need to manage their internal states
* ---------------------------------------------------------------------------------------------------- */
@Override
public HashedBitSet clone()
{
return new HashedBitSet(this);
}
/**
* @return copy of the internal state of this hashed bitset
*/
public BitSet internalStateCopy() { return (BitSet) internalState.clone(); }
/**
* @return The internal state of this hashed bitset
*/
public BitSet internalState() { return internalState; }
/**
* @param bitIndex The index of the bit.
* @return The bit value.
* @see #util.ChunkSet.get(int)
*/
public boolean get (final int bitIndex) { return internalState.get(bitIndex); }
/**
* @param fromIndex
* @return The index of the first bit that is set to true
* that occurs on or after the specified starting index.
* If no such bit exists then -1 is returned.
*/
public int nextSetBit(final int fromIndex)
{
return internalState.nextSetBit(fromIndex);
}
}
| 4,965 | 27.215909 | 108 | java |
Ludii | Ludii-master/Core/src/other/state/zhash/HashedChunkSet.java | package other.state.zhash;
import java.io.Serializable;
import main.collections.ChunkSet;
import main.math.BitTwiddling;
import other.state.State;
//-----------------------------------------------------------------------------
/**
* Wrapper around ChunkSet, to make sure it is managed correctly
* If ChunkSet were an interface, I'd use the decorator pattern...
*
* @author mrraow
*/
public class HashedChunkSet implements Serializable
{
private static final long serialVersionUID = 1L;
/** Which sites are hidden to which players. */
private final ChunkSet internalState;
private final long[][] hashes;
/**
* @param generator
* @param maxChunkVal
* @param numChunks
*/
public HashedChunkSet(final ZobristHashGenerator generator, final int maxChunkVal, final int numChunks)
{
internalState = new ChunkSet(BitTwiddling.nextPowerOf2(BitTwiddling.bitsRequired(maxChunkVal)), numChunks);
hashes = ZobristHashUtilities.getSequence(generator, numChunks, maxChunkVal + 1);
}
/**
* @param hashes
* @param maxChunkVal
* @param numSites
*/
public HashedChunkSet(final long[][] hashes, final int maxChunkVal, final int numSites)
{
internalState = new ChunkSet(BitTwiddling.nextPowerOf2(BitTwiddling.bitsRequired(maxChunkVal)), numSites);
this.hashes = hashes;
}
/**
* Copy constructor, used by clone()
* @param that
*/
private HashedChunkSet(final HashedChunkSet that)
{
this.internalState = that.internalState.clone();
this.hashes = that.hashes; // Safe to just store a reference
}
/* ----------------------------------------------------------------------------------------------------
* The following methods change state, and therefore need to manage the hash value
* ---------------------------------------------------------------------------------------------------- */
/**
* Performance warning - this method will iterate through all sites to update the hash, so avoid at runtime
* @param trialState
*/
public void clear(final State trialState)
{
long hashDelta = 0L;
for (int site = 0; site < hashes.length; site++)
hashDelta ^= hashes[site][internalState.getChunk(site)];
internalState.clear();
trialState.updateStateHash(hashDelta);
}
/**
* Calculates the hash of this object after the specified remapping.
* Either the sites, or the values, or possibly both will be remapped and the new hash calculated.
* Intended for calculating canonical hashes.
* BUGFIX: the length of the set may be longer than the remap values. This occurs when connections have been modified, and the graph compacted.
*
* Performance Warning: this is slow; do not call during a search.
*
* @param siteRemap may be null
* @param valueRemap may be null
* @return the hash of this chunk, when subjected to the specified transformation
*/
public long calculateHashAfterRemap (final int[] siteRemap, final int[] valueRemap)
{
long hashDelta = 0L;
if (valueRemap == null)
{
for (int site = 0; site < hashes.length && site < siteRemap.length; site++)
{
final int newSite = siteRemap[site];
final int siteValue = internalState.getChunk(site);
hashDelta ^= hashes[newSite][siteValue] ^ hashes[newSite][0];
}
return hashDelta;
}
if (siteRemap == null)
{
for (int site = 0; site < hashes.length; site++)
{
final int siteValue = internalState.getChunk(site);
final int newValue = valueRemap[siteValue];
hashDelta ^= hashes[site][newValue] ^ hashes[site][0];
}
return hashDelta;
}
for (int site = 0; site < hashes.length && site < siteRemap.length; site++)
{
final int siteValue = internalState.getChunk(site);
final int newValue = valueRemap[siteValue];
final int newSite = siteRemap[site];
hashDelta ^= hashes[newSite][newValue] ^ hashes[newSite][0];
}
return hashDelta;
}
/**
* Makes this a copy of src - equivalent to clear followed by or
* Performance warning - this method will iterate through all sites to update the hash, so avoid at runtime
* @param trialState
* @param src
*/
public void setTo(final State trialState, final HashedChunkSet src)
{
long hashDelta = 0L;
for (int site = 0; site < hashes.length; site++)
hashDelta ^= hashes[site][internalState.getChunk(site)] ^ hashes[site][src.internalState.getChunk(site)];
internalState.clear();
internalState.or(src.internalState);
trialState.updateStateHash(hashDelta);
}
/**
* @param trialState
* @param chunk
* @param bit
* @param value
*/
public void setBit(final State trialState, final int chunk, final int bit, final boolean value)
{
long hashDelta = hashes[chunk][internalState.getChunk(chunk)];
internalState.setBit(chunk, bit, value);
hashDelta ^= hashes[chunk][internalState.getChunk(chunk)];
trialState.updateStateHash(hashDelta);
}
/**
* @param trialState
* @param site
* @param val
*/
public void setChunk(final State trialState, final int site, final int val)
{
long hashDelta = hashes[site][internalState.getAndSetChunk(site, val)];
hashDelta ^= hashes[site][val];
trialState.updateStateHash(hashDelta);
}
/* ----------------------------------------------------------------------------------------------------
* The following methods are read-only, and do not need to manage their internal states
* ---------------------------------------------------------------------------------------------------- */
@Override
public HashedChunkSet clone()
{
return new HashedChunkSet(this);
}
/**
* @return copy of the internal state of this hashed chunkset
*/
public ChunkSet internalStateCopy() { return internalState.clone(); }
/**
* @param site The site.
* @param location The location.
* @return The bit.
* @see #util.ChunkSet.getBit(int, int)
*/
public int getBit (final int site, final int location) { return internalState.getBit(site, location); }
/**
* @param site The site.
* @return The chunk.
* @see #util.ChunkSet.getChunk(int)
*/
public int getChunk (final int site) { return internalState.getChunk(site); }
/**
* @return The number of chunks.
* @see #util.ChunkSet.numChunks()
*/
public int numChunks() { return internalState.numChunks(); }
/**
* @param mask The mask.
* @param pattern The patten.
* @return True if the pattern matched.
* @see #util.ChunkSet.matches(ChunkSet, ChunkSet)
*/
public boolean matches(final ChunkSet mask, final ChunkSet pattern) { return internalState.matches(mask, pattern); }
/**
* @param wordIdx
* @param mask
* @param matchingWord
* @return True if the word at wordIdx, after masking by mask, matches the given word
*/
public boolean matches(final int wordIdx, final long mask, final long matchingWord)
{
return internalState.matchesWord(wordIdx, mask, matchingWord);
}
/**
* @return The size of the chunk.
* @see #util.ChunkSet.chunkSize()
*/
public int chunkSize() { return internalState.chunkSize(); }
/**
* @param mask The chunkset mask.
* @param pattern The chunkset pattern
* @return True if this is not violated.
* @see #util.ChunkSet.violatesNot(ChunkSet, ChunkSet)
*/
public boolean violatesNot(final ChunkSet mask, final ChunkSet pattern) { return internalState.violatesNot(mask, pattern); }
/**
* @param mask The mask chunkset.
* @param pattern The patten chunkset.
* @param startWord The word to start.
* @return True if this is not violated.
* @see #util.ChunkSet.violatesNot(ChunkSet, ChunkSet, int)
*/
public boolean violatesNot(final ChunkSet mask, final ChunkSet pattern, final int startWord) { return internalState.violatesNot(mask, pattern, startWord); }
}
| 7,716 | 29.623016 | 157 | java |
Ludii | Ludii-master/Core/src/other/state/zhash/HashedChunkStack.java | package other.state.zhash;
import java.io.Serializable;
import game.types.board.SiteType;
import main.collections.ChunkStack;
import other.state.State;
/**
* Wrapper around ChunkSet, to make sure it is managed correctly
* If ChunkSet were an interface, I'd use the decorator pattern...
*
* @author mrraow
*/
public class HashedChunkStack implements Serializable
{
private static final long serialVersionUID = 1L;
/** The internal state of each site */
private final ChunkStack internalState;
private final long[][] whatHash;
private final long[][] whoHash;
private final long[][] stateHash;
private final long[][] rotationHash;
private final long[][] valueHash;
private final long[] sizeHash;
private long zhash = 0L;
/**
* @param numComponents
* @param numPlayers
* @param numStates
* @param numRotations
* @param numValues
* @param type
* @param hidden
* @param whatHash
* @param whoHash
* @param stateHash
* @param rotationHash
* @param valueHash
* @param sizeHash
*/
public HashedChunkStack
(
final int numComponents,
final int numPlayers,
final int numStates,
final int numRotations,
final int numValues,
final int type,
final boolean hidden,
final long[][] whatHash,
final long[][] whoHash,
final long[][] stateHash,
final long[][] rotationHash,
final long[][] valueHash,
final long[] sizeHash
)
{
this.internalState = new ChunkStack(numComponents, numPlayers, numStates, numRotations, numValues, type, hidden);
this.whatHash = whatHash;
this.whoHash = whoHash;
this.stateHash = stateHash;
this.rotationHash = rotationHash;
this.valueHash = valueHash;
this.sizeHash = sizeHash;
}
/**
* Copy constructor, used by clone()
* @param that
*/
private HashedChunkStack(final HashedChunkStack that)
{
this.internalState = new ChunkStack(that.internalState);
// Safe to just store a reference
this.whatHash = that.whatHash;
this.whoHash = that.whoHash;
this.stateHash = that.stateHash;
this.rotationHash = that.rotationHash;
this.valueHash = that.valueHash;
this.sizeHash = that.sizeHash;
this.zhash = that.zhash;
}
/**
* @return The long value of the hash.
*/
public long calcHash()
{
return zhash;
}
/**
* @param newWhatHash
* @param newWhoHash
* @param newStateHash
* @param newRotationHash
* @param newValueHash
* @param newSizeHash
* @param whoOnly
* @return the hash of this stack as if it were at a new location
*/
public long remapHashTo (
final long[][] newWhatHash,
final long[][] newWhoHash,
final long[][] newStateHash,
final long[][] newRotationHash,
final long[][] newValueHash,
final long[] newSizeHash,
final boolean whoOnly)
{
long hash = newSizeHash[internalState.size()];
for (int level = 0; level < internalState.size(); level++)
{
if (whoOnly )
{
hash ^= newWhoHash[level][internalState.who(level)];
}
else
{
hash ^= newStateHash[level][internalState.state(level)];
hash ^= newRotationHash[level][internalState.rotation(level)];
hash ^= newValueHash[level][internalState.value(level)];
hash ^= newWhoHash[level][internalState.who(level)];
hash ^= newWhatHash[level][internalState.what(level)];
}
}
return hash;
}
/* ----------------------------------------------------------------------------------------------------
* The following methods change state, and therefore need to manage the hash value
* ---------------------------------------------------------------------------------------------------- */
/**
* Set the state.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setState(final State trialState, final int val, final int level)
{
if (level >= internalState.size()) return;
long delta = stateHash[level][internalState.state(level)];
internalState.setState(val, level);
delta ^= stateHash[level][internalState.state(level)];
trialState.updateStateHash(delta);
zhash ^= delta;
}
/**
* Set the rotation.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setRotation(final State trialState, final int val, final int level)
{
if (level >= internalState.size())
return;
long delta = rotationHash[level][internalState.rotation(level)];
internalState.setRotation(val, level);
delta ^= rotationHash[level][internalState.rotation(level)];
trialState.updateStateHash(delta);
zhash ^= delta;
}
/**
* Set the value.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setValue(final State trialState, final int val, final int level)
{
if (level >= internalState.size())
return;
long delta = valueHash[level][internalState.value(level)];
internalState.setValue(val, level);
delta ^= valueHash[level][internalState.value(level)];
trialState.updateStateHash(delta);
zhash ^= delta;
}
/**
* Set the who.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setWho(final State trialState, final int val, final int level)
{
if (level >= internalState.size())
return;
long delta = whoHash[level][internalState.whoChunkSet().getAndSetChunk(level, val)];
delta ^= whoHash[level][internalState.who(level)];
trialState.updateStateHash(delta);
zhash ^= delta;
}
/**
* Set the what.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setWhat(final State trialState, final int val, final int level)
{
if (level >= internalState.size())
return;
long delta = whatHash[level][internalState.whatChunkSet().getAndSetChunk(level, val)];
delta ^= whatHash[level][internalState.what(level)];
trialState.updateStateHash(delta);
zhash ^= delta;
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the location is invisible.
*/
public boolean isHidden(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHidden(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the what information is not know.
*/
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenWhat(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the who information is not know.
*/
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenWho(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the state information is not know.
*/
public boolean isHiddenState(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenState(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the rotation information is not know.
*/
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenRotation(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the value information is not know.
*/
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenValue(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the count information is not know.
*/
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenCount(player, level);
}
/**
* To set the hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHidden(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHidden(player, level, on);
}
/**
* To set the what hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenWhat(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenWhat(player, level, on);
}
/**
* To set the who hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenWho(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenWho(player, level, on);
}
/**
* To set the state hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenState(player, level, on);
}
/**
* To set the rotation hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenRotation(player, level, on);
}
/**
* To set the piece value hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenValue(player, level, on);
}
/**
* To set the count hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenCount(player, level, on);
}
/**
* Decrement the size.
*
* @param trialState The state.
*/
public void decrementSize(final State trialState)
{
long delta = sizeHash[internalState.size()];
internalState.decrementSize();
delta ^= sizeHash[internalState.size()];
trialState.updateStateHash(delta);
zhash ^= delta;
}
/**
* Increment the size.
*
* @param trialState The state.
*/
public void incrementSize(final State trialState)
{
long delta = sizeHash[internalState.size()];
internalState.incrementSize();
delta ^= sizeHash[internalState.size()];
trialState.updateStateHash(delta);
zhash ^= delta;
}
/* ----------------------------------------------------------------------------------------------------
* The following methods delegate to a method which manages state
* ---------------------------------------------------------------------------------------------------- */
/**
* Set the rotation.
*
* @param trialState The state.
* @param val The value.
*/
public void setRotation(final State trialState, final int val)
{
final int size = internalState.size();
if (size <= 0)
return;
setRotation(trialState, val, size - 1);
}
/**
* Set the value.
*
* @param trialState The state.
* @param val The value.
*/
public void setValue(final State trialState, final int val)
{
final int size = internalState.size();
if (size <= 0)
return;
setValue(trialState, val, size - 1);
}
/**
* Set the state.
*
* @param trialState The state.
* @param val The value.
*/
public void setState(final State trialState, final int val) {
final int size = internalState.size();
if (size <= 0) return;
setState(trialState, val, size-1);
}
/**
* Set the who.
*
* @param trialState The state.
* @param val The value.
*/
public void setWho(final State trialState, final int val) {
final int size = internalState.size();
if (size <= 0)
return;
setWho(trialState, val, size-1);
}
/**
* Set the what.
*
* @param trialState The state.
* @param val The value.
*/
public void setWhat(final State trialState, final int val) {
final int size = internalState.size();
if (size <= 0) return;
setWhat(trialState, val, size-1);
}
/* ----------------------------------------------------------------------------------------------------
* The following methods are read-only, and do not need to manage their internal states
* ---------------------------------------------------------------------------------------------------- */
@Override
public HashedChunkStack clone()
{
return new HashedChunkStack(this);
}
/**
* @return The size.
*/
public int size() { return internalState.size(); }
/**
* @return The who value.
*/
public int who() {
return internalState.who();
}
/**
* @param level The level.
* @return The who value.
*/
public int who(int level) {
return internalState.who(level);
}
/**
* @return The what value.
*/
public int what() {
return internalState.what();
}
/**
* @param level The level.
* @return The what value.
*/
public int what(int level)
{
return internalState.what(level);
}
/**
* @return The state value.
*/
public int state() {
return internalState.state();
}
/**
* @param level The level.
* @return The state.
*/
public int state(int level) {
return internalState.state(level);
}
/**
* @return The rotation.
*/
public int rotation()
{
return internalState.rotation();
}
/**
* @param level The level.
* @return The rotation.
*/
public int rotation(int level)
{
return internalState.rotation(level);
}
/**
* @return The value.
*/
public int value()
{
return internalState.value();
}
/**
* @param level The level.
* @return The value.
*/
public int value(int level)
{
return internalState.value(level);
}
}
| 16,357 | 24.050536 | 117 | java |
Ludii | Ludii-master/Core/src/other/state/zhash/HashedChunkStackLarge.java | package other.state.zhash;
import java.io.Serializable;
import game.types.board.SiteType;
import main.collections.ListStack;
import other.state.State;
/**
* Wrapper around ListStack, still to do....
*
* @author mrraow
*/
public class HashedChunkStackLarge implements Serializable
{
private static final long serialVersionUID = 1L;
/** The internal state of each site */
private final ListStack internalState;
// private final long[][] whatHash;
// private final long[][] whoHash;
// private final long[][] stateHash;
// private final long[][] rotationHash;
// private final long[][] valueHash;
// private final long[] sizeHash;
private long zhash = 0L;
/**
* @param numComponents
* @param numPlayers
* @param numStates
* @param numRotations
* @param numValues
* @param type
* @param hidden
*/
public HashedChunkStackLarge
(
final int numComponents,
final int numPlayers,
final int numStates,
final int numRotations,
final int numValues,
final int type,
final boolean hidden
)
{
this.internalState = new ListStack(numComponents, numPlayers, numStates, numRotations, numValues, type, hidden);
// this.whatHash = whatHash;
// this.whoHash = whoHash;
// this.stateHash = stateHash;
// this.rotationHash = rotationHash;
// this.valueHash = valueHash;
// this.sizeHash = sizeHash;
}
/**
* Copy constructor, used by clone()
* @param that
*/
private HashedChunkStackLarge(final HashedChunkStackLarge that)
{
this.internalState = new ListStack(that.internalState);
// Safe to just store a reference
// this.whatHash = that.whatHash;
// this.whoHash = that.whoHash;
// this.stateHash = that.stateHash;
// this.rotationHash = that.rotationHash;
// this.valueHash = that.valueHash;
// this.sizeHash = that.sizeHash;
this.zhash = that.zhash;
}
/**
* @return The long value of the hash.
*/
public long calcHash()
{
return zhash;
}
/**
* @param newWhatHash
* @param newWhoHash
* @param newStateHash
* @param newRotationHash
* @param newValueHash
* @param newSizeHash
* @param whoOnly
* @return the hash of this stack as if it were at a new location
*/
public long remapHashTo (
final long[][] newWhatHash,
final long[][] newWhoHash,
final long[][] newStateHash,
final long[][] newRotationHash,
final long[][] newValueHash,
final long[] newSizeHash,
final boolean whoOnly)
{
long hash = newSizeHash[internalState.size()];
for (int level = 0; level < internalState.size(); level++)
{
if (whoOnly )
{
hash ^= newWhoHash[level][internalState.who(level)];
}
else
{
hash ^= newStateHash[level][internalState.state(level)];
hash ^= newRotationHash[level][internalState.rotation(level)];
hash ^= newValueHash[level][internalState.value(level)];
hash ^= newWhoHash[level][internalState.who(level)];
hash ^= newWhatHash[level][internalState.what(level)];
}
}
return hash;
}
/* ----------------------------------------------------------------------------------------------------
* The following methods change state, and therefore need to manage the hash value
* ---------------------------------------------------------------------------------------------------- */
/**
* Set the state.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setState(final State trialState, final int val, final int level)
{
if (level >= internalState.size()) return;
//long delta = stateHash[level][internalState.state(level)];
internalState.setState(val, level);
//delta ^= stateHash[level][internalState.state(level)];
//trialState.updateStateHash(delta);
//zhash ^= delta;
}
/**
* Set the rotation.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setRotation(final State trialState, final int val, final int level)
{
if (level >= internalState.size())
return;
//long delta = rotationHash[level][internalState.rotation(level)];
internalState.setRotation(val, level);
//delta ^= rotationHash[level][internalState.rotation(level)];
//trialState.updateStateHash(delta);
//zhash ^= delta;
}
/**
* Set the value.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setValue(final State trialState, final int val, final int level)
{
if (level >= internalState.size())
return;
//long delta = valueHash[level][internalState.value(level)];
internalState.setValue(val, level);
//delta ^= valueHash[level][internalState.value(level)];
//trialState.updateStateHash(delta);
//zhash ^= delta;
}
/**
* Set the who.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setWho(final State trialState, final int val, final int level)
{
if (level >= internalState.size())
return;
internalState.setWho(val, level);
//long delta = whoHash[level][internalState.whoChunkSet().getAndSetChunk(level, val)];
//delta ^= whoHash[level][internalState.who(level)];
//trialState.updateStateHash(delta);
//zhash ^= delta;
}
/**
* Set the what.
*
* @param trialState The state.
* @param val The value.
* @param level The level.
*/
public void setWhat(final State trialState, final int val, final int level)
{
if (level >= internalState.size())
return;
internalState.setWhat(val, level);
//long delta = whatHash[level][internalState.whatChunkSet().getAndSetChunk(level, val)];
//delta ^= whatHash[level][internalState.what(level)];
//trialState.updateStateHash(delta);
//zhash ^= delta;
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the location is invisible.
*/
public boolean isHidden(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHidden(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the what information is not know.
*/
public boolean isHiddenWhat(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenWhat(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the who information is not know.
*/
public boolean isHiddenWho(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenWho(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the state information is not know.
*/
public boolean isHiddenState(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenState(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the rotation information is not know.
*/
public boolean isHiddenRotation(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenRotation(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the value information is not know.
*/
public boolean isHiddenValue(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenValue(player, level);
}
/**
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @return True if the count information is not know.
*/
public boolean isHiddenCount(final int player, final int site, final int level, final SiteType type)
{
return internalState.isHiddenCount(player, level);
}
/**
* To set the hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHidden(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHidden(player, level, on);
}
/**
* To set the what hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenWhat(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenWhat(player, level, on);
}
/**
* To set the who hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenWho(final State state, final int player, final int site, final int level, final SiteType type,
final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenWho(player, level, on);
}
/**
* To set the state hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenState(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenState(player, level, on);
}
/**
* To set the rotation hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenRotation(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenRotation(player, level, on);
}
/**
* To set the piece value hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenValue(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenValue(player, level, on);
}
/**
* To set the count hidden information.
*
* @param state The state.
* @param player The index of the player.
* @param site The index of the site.
* @param level The index of the level.
* @param type The graph element type.
* @param on The new value.
*/
public void setHiddenCount(final State state, final int player, final int site, final int level,
final SiteType type, final boolean on)
{
if (level >= internalState.size())
return;
internalState.setHiddenCount(player, level, on);
}
/**
* Decrement the size.
*
* @param trialState The state.
*/
public void decrementSize(final State trialState)
{
//long delta = sizeHash[internalState.size()];
internalState.decrementSize();
//delta ^= sizeHash[internalState.size()];
//trialState.updateStateHash(delta);
//zhash ^= delta;
}
/**
* Increment the size.
*
* @param trialState The state.
*/
public void incrementSize(final State trialState)
{
//long delta = sizeHash[internalState.size()];
internalState.incrementSize();
//delta ^= sizeHash[internalState.size()];
//trialState.updateStateHash(delta);
//zhash ^= delta;
}
/* ----------------------------------------------------------------------------------------------------
* The following methods delegate to a method which manages state
* ---------------------------------------------------------------------------------------------------- */
/**
* Set the rotation.
*
* @param trialState The state.
* @param val The value.
*/
public void setRotation(final State trialState, final int val)
{
final int size = internalState.size();
if (size <= 0)
return;
setRotation(trialState, val, size - 1);
}
/**
* Set the value.
*
* @param trialState The state.
* @param val The value.
*/
public void setValue(final State trialState, final int val)
{
final int size = internalState.size();
if (size <= 0)
return;
setValue(trialState, val, size - 1);
}
/**
* Set the state.
*
* @param trialState The state.
* @param val The value.
*/
public void setState(final State trialState, final int val) {
final int size = internalState.size();
if (size <= 0) return;
setState(trialState, val, size-1);
}
/**
* Set the who.
*
* @param trialState The state.
* @param val The value.
*/
public void setWho(final State trialState, final int val) {
final int size = internalState.size();
if (size <= 0)
return;
setWho(trialState, val, size-1);
}
/**
* Set the what.
*
* @param trialState The state.
* @param val The value.
*/
public void setWhat(final State trialState, final int val) {
final int size = internalState.size();
if (size <= 0) return;
setWhat(trialState, val, size-1);
}
/* ----------------------------------------------------------------------------------------------------
* The following methods are read-only, and do not need to manage their internal states
* ---------------------------------------------------------------------------------------------------- */
@Override
public HashedChunkStackLarge clone()
{
return new HashedChunkStackLarge(this);
}
/**
* @return The size.
*/
public int size() { return internalState.size(); }
/**
* @return The who value.
*/
public int who() {
return internalState.who();
}
/**
* @param level The level.
* @return The who value.
*/
public int who(int level) {
return internalState.who(level);
}
/**
* @return The what value.
*/
public int what() {
return internalState.what();
}
/**
* @param level The level.
* @return The what value.
*/
public int what(int level)
{
return internalState.what(level);
}
/**
* @return The state value.
*/
public int state() {
return internalState.state();
}
/**
* @param level The level.
* @return The state.
*/
public int state(int level) {
return internalState.state(level);
}
/**
* @return The rotation.
*/
public int rotation()
{
return internalState.rotation();
}
/**
* @param level The level.
* @return The rotation.
*/
public int rotation(int level)
{
return internalState.rotation(level);
}
/**
* @return The value.
*/
public int value()
{
return internalState.value();
}
/**
* @param level The level.
* @return The value.
*/
public int value(int level)
{
return internalState.value(level);
}
}
| 16,165 | 24.180685 | 117 | java |
Ludii | Ludii-master/Core/src/other/state/zhash/ZobristHashGenerator.java | package other.state.zhash;
import org.apache.commons.rng.core.source64.SplitMix64;
/**
* Generates sequences for Zobrist hashing
* For now, just a wrapper around SplitMix64, but easy to change if that proves inadequate
*
* @author mrraow
*
*/
public class ZobristHashGenerator extends SplitMix64 {
private static final long RNG_SEED = 3544273448235996400L; // TODO: consider tuning the seed to minimise collisions
private int counter;
/**
* Base constructor
*/
public ZobristHashGenerator() {
super(Long.valueOf(RNG_SEED));
}
/**
* Creates a generator at the specified position - useful if you want to serialise/deserialise and trade file size for CPU time
* @param pos
*/
public ZobristHashGenerator(final int pos) {
super(Long.valueOf(RNG_SEED));
while (counter < pos) next();
}
/**
* Next 64 bit number in sequence
*/
@Override
public long next() {
counter++;
return super.next();
}
/**
* @return The sequence position.
*/
public int getSequencePosition() {
return counter;
}
}
| 1,044 | 19.9 | 128 | java |
Ludii | Ludii-master/Core/src/other/state/zhash/ZobristHashUtilities.java | package other.state.zhash;
/**
* Zobrist hashing - attempts to reduce a board state to a 64 bit number
*
* Basic contract:
* - same position in different parts of the tree should have the same hash
* - different positions will have different hashes _most_ of the time
* - fast to calculate via incremental updates
*
* Note 1: that collisions can largely be ignored: http://www.craftychess.com/hyatt/collisions.html
*
* Note 2: actions can be identified as oldPosition^newPosition - useful for RAVE, LGM, etc
*
* Note 3: the seed is fixed, and we are using a deterministic RNG, so the hashes can also be
* used to generate opening libraries and endgame libraries
*
* @author mrraow
*
*/
public final class ZobristHashUtilities
{
/** Initial value of a hash (0) */
public static final long INITIAL_VALUE = 0L;
/** Potentially useful value for signalling unknown hash */
public static final long UNKNOWN = -1L;
/**
* @return a new instance of a generator which will return a consistent set of hashes acropss different runs of the code
*/
public static final ZobristHashGenerator getHashGenerator()
{
return new ZobristHashGenerator();
}
/**
* @param generator - sequence generator
* @return next long in sequence
*/
public static final long getNext (final ZobristHashGenerator generator)
{
return generator.next();
}
/**
* @param generator - sequence generator
* @param dim - dimension of array
* @return 1d array of longs from sequence
*/
public static final long[] getSequence(final ZobristHashGenerator generator, final int dim)
{
final long[] results = new long[dim];
for (int i = 0; i < dim; i++) results[i] = generator.next();
return results;
}
/**
* @param generator - sequence generator
* @param dim1 first dimension of array
* @param dim2 second dimension of array
* @return 2d array of longs from sequence
*/
public static final long[][] getSequence(final ZobristHashGenerator generator, final int dim1, final int dim2)
{
final long[][] results = new long[dim1][];
for (int i = 0; i < dim1; i++) results[i] = getSequence(generator, dim2);
return results;
}
/**
* @param generator - sequence generator
* @param dim1 first dimension of array
* @param dim2 second dimension of array
* @param dim3 third dimension of array
* @return 2d array of longs from sequence
*/
public static final long[][][] getSequence(final ZobristHashGenerator generator, final int dim1, final int dim2, final int dim3)
{
final long[][][] results = new long[dim1][][];
for (int i = 0; i < dim1; i++) results[i] = getSequence(generator, dim2, dim3);
return results;
}
}
| 2,676 | 30.494118 | 130 | java |
Ludii | Ludii-master/Core/src/other/topology/AxisLabel.java | package other.topology;
import java.awt.geom.Point2D;
import java.io.Serializable;
//-----------------------------------------------------------------------------
/**
* Board cell.
*
* @author cambolbro
*/
public final class AxisLabel implements Serializable
{
private static final long serialVersionUID = 1L;
/** Label. */
private String label = "?";
/** Position. */
private final Point2D.Double posn = new Point2D.Double(0, 0);
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param label
* @param x
* @param y
*/
public AxisLabel(final String label, final double x, final double y)
{
this.label = label;
posn.setLocation(x, y);
}
//-------------------------------------------------------------------------
/**
* @return Cell label.
*/
public String label()
{
return label;
}
/**
* @return Centroid.
*/
public Point2D.Double posn()
{
return posn;
}
//-------------------------------------------------------------------------
}
| 1,047 | 16.762712 | 79 | java |
Ludii | Ludii-master/Core/src/other/topology/Cell.java | package other.topology;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import game.types.board.SiteType;
import main.math.Point3D;
/**
* Cell of the board (equivalent to a face of the graph).
*
* @author Eric.Piette and Matthew.Stephenson
*/
public final class Cell extends TopologyElement implements Serializable
{
private static final long serialVersionUID = 1L;
//-----------------------------------------------------------------------------
/** List of vertices of this cell. */
private List<Vertex> vertices = new ArrayList<Vertex>();
/** List of Edges using this edge. */
private final List<Edge> edges = new ArrayList<Edge>();
//----------------------------------------------------------------------------
/** Orthogonally connected vertices. */
private List<Cell> orthogonal = new ArrayList<Cell>();
/** Diagonally connected vertices. */
private List<Cell> diagonal = new ArrayList<Cell>();
/** Secondary diagonally connected vertices. */
private List<Cell> off = new ArrayList<Cell>();
/** Adjacent cells. */
private final List<Cell> adjacent = new ArrayList<Cell>();
/** Neighbours. */
private final List<Cell> neighbours = new ArrayList<Cell>();
//-------------------------------------------------------------------------
/**
* Definition of a cell.
*
* @param index The index of the cell.
* @param x The x coordinate.
* @param y The y coordinate.
* @param z The z coordinate.
*/
public Cell(final int index, final double x, final double y, final double z)
{
this.index = index;
label = index+"";
centroid = new Point3D(x, y, z);
}
//-------------------------------------------------------------------------
/**
* @return Orthogonally connected cells.
*/
@Override
public List<Cell> orthogonal()
{
return orthogonal;
}
/**
* To set the orthogonally connected cells.
*
* @param orthogonal The orthogonal cells.
*/
public void setOrthogonal(final List<Cell> orthogonal)
{
this.orthogonal = orthogonal;
}
/**
* @return Diagonally connected cells.
*/
@Override
public List<Cell> diagonal()
{
return diagonal;
}
/**
* To set the diagonally connected cells.
*
* @param diagonal The diagonal cells.
*/
public void setDiagonal(final List<Cell> diagonal)
{
this.diagonal = diagonal;
}
/**
* @return neighbours cells.
*/
@Override
public List<Cell> neighbours()
{
return neighbours;
}
/**
* @return Off connected cells.
*/
@Override
public List<Cell> off()
{
return off;
}
/**
* To set the off connected cells.
*
* @param off The off cells.
*/
public void setOff(final List<Cell> off)
{
this.off = off;
}
/**
* @return Adjacent cells.
*/
@Override
public List<Cell> adjacent()
{
return adjacent;
}
//-------------------------------------------------------------------------
/**
* @param x
* @param y
* @return True if the coord are the same.
*/
public boolean matchCoord(final int x, final int y)
{
if (coord.row() == x && coord.column() == y)
return true;
return false;
}
//-------------------------------------------------------------------------
/**
* @param x
* @param y
* @return Whether the specified position matches this cell.
*/
public boolean matches(final double x, final double y)
{
final double dx = x - centroid().getX();
final double dy = y - centroid().getY();
return Math.abs(dx) < 0.0001 && Math.abs(dy) < 0.0001;
}
/**
* @param other
* @return Whether the specified cell's position matches this vertex's.
*/
public boolean matches(final Cell other)
{
final double dx = other.centroid().getX() - centroid().getX();
final double dy = other.centroid().getY() - centroid().getY();
return Math.abs(dx) < 0.0001 && Math.abs(dy) < 0.0001;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "Cell: " + index;
return str;
}
//-------------------------------------------------------------------------
@Override
public boolean equals(final Object o)
{
final Cell cell = (Cell) o;
return cell != null && index == cell.index;
}
@Override
public int hashCode()
{
return index;
}
//-------------------------------------------------------------------------
/**
* @return Vertices of the cell.
*/
@Override
public List<Vertex> vertices()
{
return vertices;
}
/**
* To set the vertices of the cell.
* Note: Use only in BoardlessPlacement.
*
* @param v The new list of vertices.
*/
public void setVertices(final List<Vertex> v)
{
vertices = v;
}
/**
* @return Edges of the cell.
*/
@Override
public List<Edge> edges()
{
return edges;
}
@Override
public List<Cell> cells()
{
final ArrayList<Cell> cells = new ArrayList<>();
cells.add(this);
return cells;
}
//-------------------------------------------------------------------------
/**
* Optimises memory usage by this cell.
*/
public void optimiseMemory()
{
((ArrayList<Vertex>) vertices).trimToSize();
((ArrayList<Edge>) edges).trimToSize();
((ArrayList<Cell>) orthogonal).trimToSize();
((ArrayList<Cell>) diagonal).trimToSize();
((ArrayList<Cell>) off).trimToSize();
((ArrayList<Cell>) adjacent).trimToSize();
((ArrayList<Cell>) neighbours).trimToSize();
}
//-------------------------------------------------------------------------
@Override
public SiteType elementType()
{
return SiteType.Cell;
}
//-------------------------------------------------------------------------
@Override
public List<Vertex> regionVertices()
{
return vertices();
}
@Override
public List<Edge> regionEdges()
{
return edges();
}
@Override
public List<Cell> regionCells()
{
return cells();
}
}
| 5,850 | 19.245675 | 80 | java |
Ludii | Ludii-master/Core/src/other/topology/Edge.java | package other.topology;
import java.awt.geom.Point2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import game.types.board.RelationType;
import game.types.board.SiteType;
import main.math.Point3D;
import main.math.Vector;
/**
* Edge of the graph (equivalent to the edge of the board).
*
* @author Eric Piette and cambolbro
*/
public final class Edge extends TopologyElement implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Vertex end points. */
private final Vertex[] vertices = new Vertex[2];
/** The cells of the edge. */
private final List<Cell> cells = new ArrayList<Cell>();
/** Adjacent edges. */
private final List<Edge> adjacent = new ArrayList<Edge>();
/** Whether to use end point pivots to define curved edge. */
// private boolean curved = false;
private Vector tangentA = null;
private Vector tangentB = null;
//-------------------------------------------------------------------------
/** Edges crossed. */
private BitSet doesCross = new BitSet();
//---------------------------------------------------------------------------
/**
* Definition of an edge.
*
* @param v0 The first vertex of the edge.
* @param v1 The second vertex of the edge.
*/
public Edge(final Vertex v0, final Vertex v1)
{
index = -1;
vertices[0] = v0;
vertices[1] = v1;
// We compute the centroid.
final double x = (vertices[0].centroid3D().x() + vertices[1].centroid3D().x()) / 2.0;
final double y = (vertices[0].centroid3D().y() + vertices[1].centroid3D().y()) / 2.0;
final double z = (vertices[0].centroid3D().z() + vertices[1].centroid3D().z()) / 2.0;
centroid = new Point3D(x, y, z);
}
/**
* Edge with a specific index.
*
* @param index The index of the edge.
* @param v0 The first vertex of the edge.
* @param v1 The second vertex of the edge.
*/
public Edge(final int index, final Vertex v0, final Vertex v1)
{
this.index = index;
vertices[0] = v0;
vertices[1] = v1;
// We compute the centroid.
final double x = (vertices[0].centroid3D().x() + vertices[1].centroid3D().x()) / 2.0;
final double y = (vertices[0].centroid3D().y() + vertices[1].centroid3D().y()) / 2.0;
final double z = (vertices[0].centroid3D().z() + vertices[1].centroid3D().z()) / 2.0;
centroid = new Point3D(x, y, z);
}
//-------------------------------------------------------------------------
/**
* To set the bitset doesCross.
*
* @param doesCross The new bitset.
*/
public void setDoesCross(final BitSet doesCross)
{
this.doesCross = doesCross;
}
/**
* To set an edge crossing that one.
*
* @param indexEdge Index of the edge crossing.
*/
public void setDoesCross(final int indexEdge)
{
doesCross.set(indexEdge);
}
/**
* @param edge The index of the edge.
* @return True if the edge crosses this edge.
*/
public boolean doesCross(final int edge)
{
if (edge < 0 || edge >= doesCross.size())
return false;
return doesCross.get(edge);
}
/**
* @param which
* @return A vertex of the edge.
*/
public Vertex vertex(final int which)
{
return vertices[which];
}
/**
* @return The vertex A.
*/
public Vertex vA()
{
return vertices[0];
}
/**
* @return The vertex B.
*/
public Vertex vB()
{
return vertices[1];
}
/**
* @param v
*
* @return The vertex not given.
*/
public Vertex otherVertex(final Vertex v)
{
if (vertices[0] == v)
return vertices[1];
else if (vertices[1] == v)
return vertices[0];
else
return null;
}
// public boolean curved()
// {
// return curved;
// }
//
// 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;
}
//-------------------------------------------------------------------------
/**
* @return Whether this edge is curved.
*/
public boolean isCurved()
{
return tangentA != null && tangentB != null;
}
//-------------------------------------------------------------------------
/**
* @return Whether there is an arrow from B => A (directed).
*/
public static boolean toA()
{
// **
// ** TODO: Assume A => B always for the moment, but eventually this
// ** can be overrideable in the description.
// **
return false;
}
/**
* @return Whether there is an arrow from A => B (directed).
*/
public static boolean toB()
{
// **
// ** TODO: Assume A => B always for the moment, but eventually this
// ** can be overrideable in the description.
// **
return true;
}
//-------------------------------------------------------------------------
/**
* @return The type of the edge.
*/
public RelationType type()
{
if (vA().orthogonal().contains(vB()))
return RelationType.Orthogonal;
else if (vA().diagonal().contains(vB()))
return RelationType.Diagonal;
else
return RelationType.OffDiagonal;
}
/**
* @return cells of the edge.
*/
@Override
public List<Cell> cells()
{
return cells;
}
/**
* @return vertices of the edge.
*/
@Override
public List<Vertex> vertices()
{
return Arrays.asList(vertices);
}
@Override
public List<Edge> edges()
{
final ArrayList<Edge> edges = new ArrayList<>();
edges.add(this);
return edges;
}
//-------------------------------------------------------------------------
/**
* @param indexV
* @return True if v is used by the edge.
*/
public boolean containsVertex(final int indexV)
{
return indexV == vA().index() || vB().index() == indexV;
}
/**
* @param va The vertex A.
* @param vb The vertex B.
* @return Whether this edge matches the specified vertices in the graph.
*/
public boolean matches(final Vertex va, final Vertex vb)
{
return va.index() == vertices[0].index() && vb.index() == vertices[1].index()
|| va.index() == vertices[1].index() && vb.index() == vertices[0].index();
}
/**
* @param pa The point2D A.
* @param pb The point2D B.
* @return Whether this edge matches with the specified point.
*/
public boolean matches(final Point2D pa, final Point2D pb)
{
return pa == vertices[0].centroid() && pb == vertices[1].centroid()
|| pa == vertices[1].centroid() && pb == vertices[0].centroid();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "Edge(" + vertices[0].index() + "-" + vertices[1].index() + ")";
return str;
}
//-------------------------------------------------------------------------
/**
* Optimises memory usage by this edge.
*/
public void optimiseMemory()
{
((ArrayList<Cell>) cells).trimToSize();
((ArrayList<Edge>) adjacent).trimToSize();
}
//-------------------------------------------------------------------------
@Override
public SiteType elementType()
{
return SiteType.Edge;
}
@Override
public String label()
{
return String.valueOf(index);
}
/**
* @return Orthogonally connected vertices.
*/
@Override
public List<Edge> orthogonal()
{
return adjacent;
}
/**
* @return Diagonally connected vertices.
*/
@Override
public List<Edge> diagonal()
{
return new ArrayList<Edge>();
}
/**
* @return Off connected vertices.
*/
@Override
public List<Edge> off()
{
return new ArrayList<Edge>();
}
/**
* @return All the adjacent neighbours.
*/
@Override
public List<Edge> adjacent()
{
return adjacent;
}
/**
* @return All the neighbours.
*/
@Override
public List<Edge> neighbours()
{
return adjacent;
}
//-------------------------------------------------------------------------
@Override
public List<Vertex> regionVertices()
{
return vertices();
}
@Override
public List<Edge> regionEdges()
{
return edges();
}
@Override
public List<Cell> regionCells()
{
return new ArrayList<>();
}
}
| 8,464 | 19.251196 | 87 | java |
Ludii | Ludii-master/Core/src/other/topology/SiteFinder.java | package other.topology;
import game.equipment.container.board.Board;
import game.types.board.SiteType;
/**
* Find a cell with a specified coordinate label.
*
* @author cambolbro and Eric.Piette
*/
public final class SiteFinder
{
/**
* @param board The board.
* @param coord The coordinate
* @param type The graph element type.
* @return Cell with specified coordinate label, else null if not found.
*/
public final static TopologyElement find(final Board board, final String coord, final SiteType type)
{
if ((type == null && board.defaultSite() == SiteType.Cell)
|| (type != null && type.equals(SiteType.Cell)))
{
for (final Cell cell : board.topology().cells())
if (cell.label().equals(coord))
return cell;
}
else if ((type == null && board.defaultSite() == SiteType.Vertex)
|| (type != null && type.equals(SiteType.Vertex)))
{
for (final Vertex vertex : board.topology().vertices())
if (vertex.label().equals(coord))
return vertex;
}
return null;
}
}
| 1,023 | 25.25641 | 101 | java |
Ludii | Ludii-master/Core/src/other/topology/Topology.java | package other.topology;
import java.awt.geom.Point2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import game.Game;
import game.equipment.container.Container;
import game.equipment.other.Regions;
import game.functions.region.RegionFunction;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.types.board.StepType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.CompassDirection;
import game.util.directions.DirectionFacing;
import game.util.graph.Graph;
import game.util.graph.GraphElement;
import game.util.graph.Perimeter;
import game.util.graph.Properties;
import game.util.graph.Radial;
import game.util.graph.Radials;
import game.util.graph.Step;
import game.util.graph.Trajectories;
import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import main.collections.ArrayUtils;
import main.math.MathRoutines;
import other.GraphUtilities;
import other.concept.Concept;
import other.context.Context;
import other.trial.Trial;
/**
* Topology of the graph of the game.
*
* @author Eric.Piette and cambolbro and Dennis Soemers
*/
public class Topology implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** List of cells. */
private final List<Cell> cells = new ArrayList<Cell>();
/** List of edges. */
private final List<Edge> edges = new ArrayList<Edge>();
/** List of vertices. */
private final List<Vertex> vertices = new ArrayList<Vertex>();
/** Reference to generating graph, so board styles and designs can determine underlying basis. */
private Graph graph = null;
/** The number of edges of each tiling only if the graph uses a regular tiling. */
private int numEdges = Constants.UNDEFINED;
//----------------------Pre-generated parameters-----------------
/**
* Record of relations between elements within a graph.
*/
private Trajectories trajectories;
/** Supported directions for each element type. */
private final Map<SiteType, List<DirectionFacing>> supportedDirections = new EnumMap<SiteType, List<DirectionFacing>>(SiteType.class);
/** Supported Orthogonal directions for each element type. */
private final Map<SiteType, List<DirectionFacing>> supportedOrthogonalDirections = new EnumMap<SiteType, List<DirectionFacing>>(SiteType.class);
/** Supported Diagonal directions for each element type. */
private final Map<SiteType, List<DirectionFacing>> supportedDiagonalDirections = new EnumMap<SiteType, List<DirectionFacing>>(SiteType.class);
/** Supported Adjacent directions for each element type. */
private final Map<SiteType, List<DirectionFacing>> supportedAdjacentDirections = new EnumMap<SiteType, List<DirectionFacing>>(SiteType.class);
/** Supported Off directions for each element type. */
private final Map<SiteType, List<DirectionFacing>> supportedOffDirections = new EnumMap<SiteType, List<DirectionFacing>>(SiteType.class);
/** List of corners sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> corners = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of convex corners sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> cornersConvex = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of concave corners sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> cornersConcave = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of major generator sites in tiling for each graph element. */
private final Map<SiteType, List<TopologyElement>> major = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of minor generator sites in tiling for each graph element. */
private final Map<SiteType, List<TopologyElement>> minor = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of outer sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> outer = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of perimeter sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> perimeter = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of inner sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> inner = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of interlayer sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> interlayer = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of top sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> top = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of left sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> left = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of right sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> right = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of bottom sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> bottom = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of centre sites for each graph element. */
private final Map<SiteType, List<TopologyElement>> centre = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of column sites for each graph element. */
private final Map<SiteType, List<List<TopologyElement>>> columns = new EnumMap<SiteType, List<List<TopologyElement>>>(SiteType.class);
/** List of row sites for each graph element. */
private final Map<SiteType, List<List<TopologyElement>>> rows = new EnumMap<SiteType, List<List<TopologyElement>>>(SiteType.class);
/** List of sites in a specific phase for each graph element. */
private final Map<SiteType, List<List<TopologyElement>>> phases = new EnumMap<SiteType, List<List<TopologyElement>>>(SiteType.class);
/** List of sides according to a direction for each graph element. */
private final Map<SiteType, Map<DirectionFacing, List<TopologyElement>>> sides = new EnumMap<SiteType, Map<DirectionFacing, List<TopologyElement>>>(SiteType.class);
/** Distances from every graph element to each other graph element of the same type. */
private final Map<SiteType, int[][]> distanceToOtherSite = new EnumMap<SiteType, int[][]>(SiteType.class);
/** Distances from every graph element to its closest corner. */
private final Map<SiteType, int[]> distanceToCorners = new EnumMap<SiteType, int[]>(SiteType.class);
/** Distances from every graph element to its closest side. */
private final Map<SiteType, int[]> distanceToSides = new EnumMap<SiteType, int[]>(SiteType.class);
/** Distances from every graph element to its closest center. */
private final Map<SiteType, int[]> distanceToCentre = new EnumMap<SiteType, int[]>(SiteType.class);
/** List of layers sites for each graph element. */
private final Map<SiteType, List<List<TopologyElement>>> layers = new EnumMap<SiteType, List<List<TopologyElement>>>(SiteType.class);
/** List of diagonal sites for each graph element. */
private final Map<SiteType, List<List<TopologyElement>>> diagonals = new EnumMap<SiteType, List<List<TopologyElement>>>(SiteType.class);
/** List of axials sites for each graph element. Computed currently only for edges. */
private final Map<SiteType, List<TopologyElement>> axials = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of horizontal sites for each graph element. Computed currently only for edges. */
private final Map<SiteType, List<TopologyElement>> horizontal = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of vertical sites for each graph element. Computed currently only for edges. */
private final Map<SiteType, List<TopologyElement>> vertical = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of angled sites for each graph element. Computed currently only for edges. */
private final Map<SiteType, List<TopologyElement>> angled = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of slash sites for each graph element. Computed currently only for edges. */
private final Map<SiteType, List<TopologyElement>> slash = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/** List of slosh sites for each graph element. Computed currently only for edges. */
private final Map<SiteType, List<TopologyElement>> slosh = new EnumMap<SiteType, List<TopologyElement>>(SiteType.class);
/**
* For every region in equipment, a table of distances for graph element to that
* region. Contains null arrays for regions that are not static.
*/
private final Map<SiteType, int[][]> distanceToRegions = new EnumMap<SiteType, int[][]>(SiteType.class);
/** Cross reference of phase by element index. */
private final Map<SiteType, int[]> phaseByElementIndex = new EnumMap<SiteType, int[]>(SiteType.class);
// ----- Pre-generated stuff for Features-----------------------------
/** Different numbers of true-ortho-connectivity that different elements in our graph have */
private final Map<SiteType, TIntArrayList> connectivities = new EnumMap<SiteType, TIntArrayList>(SiteType.class);
// /**
// * We'll store all the relations between Vertex pairs that were removed during graph
// * construction here, so we can patch up the connectivity data for features. Will
// * clean this memory up when we're done with preprocessing for features
// */
// private Map<Vertex, List<RemovedRelationData>> removedRelations = new HashMap<Vertex, List<RemovedRelationData>>();
//------------------------------------------------------------------------------
/**
* 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 List<Perimeter> perimeters = new ArrayList<Perimeter>();
/**
* Constructor to init each list of sites pre-generated.
*/
public Topology()
{
for (final SiteType type : SiteType.values())
{
corners.put(type, new ArrayList<TopologyElement>());
cornersConcave.put(type, new ArrayList<TopologyElement>());
cornersConvex.put(type, new ArrayList<TopologyElement>());
major.put(type, new ArrayList<TopologyElement>());
minor.put(type, new ArrayList<TopologyElement>());
outer.put(type, new ArrayList<TopologyElement>());
perimeter.put(type, new ArrayList<TopologyElement>());
inner.put(type, new ArrayList<TopologyElement>());
interlayer.put(type, new ArrayList<TopologyElement>());
top.put(type, new ArrayList<TopologyElement>());
bottom.put(type, new ArrayList<TopologyElement>());
left.put(type, new ArrayList<TopologyElement>());
right.put(type, new ArrayList<TopologyElement>());
centre.put(type, new ArrayList<TopologyElement>());
phases.put(type, new ArrayList<List<TopologyElement>>());
for (int i = 0; i < Constants.MAX_CELL_COLOURS; i++)
phases.get(type).add(new ArrayList<TopologyElement>());
rows.put(type, new ArrayList<List<TopologyElement>>());
columns.put(type, new ArrayList<List<TopologyElement>>());
layers.put(type, new ArrayList<List<TopologyElement>>());
diagonals.put(type, new ArrayList<List<TopologyElement>>());
axials.put(type, new ArrayList<TopologyElement>());
horizontal.put(type, new ArrayList<TopologyElement>());
vertical.put(type, new ArrayList<TopologyElement>());
angled.put(type, new ArrayList<TopologyElement>());
slash.put(type, new ArrayList<TopologyElement>());
slosh.put(type, new ArrayList<TopologyElement>());
sides.put(type, new HashMap<DirectionFacing, List<TopologyElement>>());
for (final CompassDirection direction : CompassDirection.values())
sides.get(type).put(direction, new ArrayList<TopologyElement>());
supportedDirections.put(type, new ArrayList<DirectionFacing>());
supportedOrthogonalDirections.put(type, new ArrayList<DirectionFacing>());
supportedDiagonalDirections.put(type, new ArrayList<DirectionFacing>());
supportedAdjacentDirections.put(type, new ArrayList<DirectionFacing>());
supportedOffDirections.put(type, new ArrayList<DirectionFacing>());
}
}
//-----Methods--------------------------------------------------------------------------
/**
* @return The corresponding graph.
*/
public Graph graph()
{
return graph;
}
/**
* To set the graph.
*
* @param gr The new graph.
*/
public void setGraph(final Graph gr)
{
graph = gr;
}
/* Rotations and reflections of cells, edges, vertices */
private int[][] cellRotationSymmetries;
private int[][] cellReflectionSymmetries;
private int[][] edgeRotationSymmetries;
private int[][] edgeReflectionSymmetries;
private int[][] vertexRotationSymmetries;
private int[][] vertexReflectionSymmetries;
/**
* @param cellRotationSymmetries the cellRotationSymmetries to set
*/
public void setCellRotationSymmetries(final int[][] cellRotationSymmetries) {
this.cellRotationSymmetries = cellRotationSymmetries;
}
/**
* @param cellReflectionSymmetries the cellReflectionSymmetries to set
*/
public void setCellReflectionSymmetries(final int[][] cellReflectionSymmetries) {
this.cellReflectionSymmetries = cellReflectionSymmetries;
}
/**
* @param edgeRotationSymmetries the edgeRotationSymmetries to set
*/
public void setEdgeRotationSymmetries(final int[][] edgeRotationSymmetries) {
this.edgeRotationSymmetries = edgeRotationSymmetries;
}
/**
* @param edgeReflectionSymmetries the edgeReflectionSymmetries to set
*/
public void setEdgeReflectionSymmetries(final int[][] edgeReflectionSymmetries) {
this.edgeReflectionSymmetries = edgeReflectionSymmetries;
}
/**
* @param vertexRotationSymmetries the vertexRotationSymmetries to set
*/
public void setVertexRotationSymmetries(final int[][] vertexRotationSymmetries) {
this.vertexRotationSymmetries = vertexRotationSymmetries;
}
/**
* @param vertexReflectionSymmetries the vertexReflectionSymmetries to set
*/
public void setVertexReflectionSymmetries(final int[][] vertexReflectionSymmetries) {
this.vertexReflectionSymmetries = vertexReflectionSymmetries;
}
/**
* @return the cellRotationSymmetries
*/
public int[][] cellRotationSymmetries() {
return cellRotationSymmetries;
}
/**
* @return the cellReflectionSymmetries
*/
public int[][] cellReflectionSymmetries() {
return cellReflectionSymmetries;
}
/**
* @return the edgeRotationSymmetries
*/
public int[][] edgeRotationSymmetries() {
return edgeRotationSymmetries;
}
/**
* @return the edgeReflectionSymmetries
*/
public int[][] edgeReflectionSymmetries() {
return edgeReflectionSymmetries;
}
/**
* @return the vertexRotationSymmetries
*/
public int[][] vertexRotationSymmetries() {
return vertexRotationSymmetries;
}
/**
* @return the vertexReflectionSymmetries
*/
public int[][] vertexReflectionSymmetries() {
return vertexReflectionSymmetries;
}
// ---------------------------------Methods------------------------------------------
/**
* @param type The graph element type.
* @return List of corner sites.
*/
public List<TopologyElement> corners(final SiteType type)
{
return corners.get(type);
}
/**
* @param type The graph element type.
* @return List of concave corner sites.
*/
public List<TopologyElement> cornersConcave(final SiteType type)
{
return cornersConcave.get(type);
}
/**
* @param type The graph element type.
* @return List of convex corner sites.
*/
public List<TopologyElement> cornersConvex(final SiteType type)
{
return cornersConvex.get(type);
}
/**
* @param type The graph element type.
* @return List of major sites.
*/
public List<TopologyElement> major(final SiteType type)
{
return major.get(type);
}
/**
* @param type The graph element type.
* @return List of minor sites.
*/
public List<TopologyElement> minor(final SiteType type)
{
return minor.get(type);
}
/**
* @param type The graph element type.
* @return List of outer sites.
*/
public List<TopologyElement> outer(final SiteType type)
{
return outer.get(type);
}
/**
* @param type The graph element type.
* @return List of perimeter sites.
*/
public List<TopologyElement> perimeter(final SiteType type)
{
return perimeter.get(type);
}
/**
* @param type The graph element type.
* @return List of top sites.
*/
public List<TopologyElement> top(final SiteType type)
{
return top.get(type);
}
/**
* @param type The graph element type.
* @return List of bottom sites.
*/
public List<TopologyElement> bottom(final SiteType type)
{
return bottom.get(type);
}
/**
* @param type The graph element type.
* @return List of left sites.
*/
public List<TopologyElement> left(final SiteType type)
{
return left.get(type);
}
/**
* @param type The graph element type.
* @return List of right sites.
*/
public List<TopologyElement> right(final SiteType type)
{
return right.get(type);
}
/**
* @param type The graph element type.
* @return List of centre sites.
*/
public List<TopologyElement> centre(final SiteType type)
{
return centre.get(type);
}
/**
* @param type The graph element type.
* @return List of axial sites.
*/
public List<TopologyElement> axial(final SiteType type)
{
return axials.get(type);
}
/**
* @param type The graph element type.
* @return List of horizontal sites.
*/
public List<TopologyElement> horizontal(final SiteType type)
{
return horizontal.get(type);
}
/**
* @param type The graph element type.
* @return List of vertical sites.
*/
public List<TopologyElement> vertical(final SiteType type)
{
return vertical.get(type);
}
/**
* @param type The graph element type.
* @return List of angled sites.
*/
public List<TopologyElement> angled(final SiteType type)
{
return angled.get(type);
}
/**
* @param type The graph element type.
* @return List of slash sites.
*/
public List<TopologyElement> slash(final SiteType type)
{
return slash.get(type);
}
/**
* @param type The graph element type.
* @return List of slosh sites.
*/
public List<TopologyElement> slosh(final SiteType type)
{
return slosh.get(type);
}
/**
* @param type The graph element type.
* @return List of inner sites.
*/
public List<TopologyElement> inner(final SiteType type)
{
return inner.get(type);
}
/**
* @param type The graph element type.
* @return List of interlayer sites.
*/
public List<TopologyElement> interlayer(final SiteType type)
{
return interlayer.get(type);
}
/**
* @param type The graph element type.
* @return List of rows sites.
*/
public List<List<TopologyElement>> rows(final SiteType type)
{
return rows.get(type);
}
/**
* @param type The graph element type.
* @return List of columns sites.
*/
public List<List<TopologyElement>> columns(final SiteType type)
{
return columns.get(type);
}
/**
* @param type The graph element type.
* @return List of layers sites.
*/
public List<List<TopologyElement>> layers(final SiteType type)
{
return layers.get(type);
}
/**
* @param type The graph element type.
* @return List of diagonal sites.
*/
public List<List<TopologyElement>> diagonals(final SiteType type)
{
return diagonals.get(type);
}
/**
* @param type The graph element type.
* @return List of sites in a specific phase.
*/
public List<List<TopologyElement>> phases(final SiteType type)
{
return phases.get(type);
}
/**
* @param type The graph element type.
* @return List of sites on a side of the board.
*/
public Map<DirectionFacing, List<TopologyElement>> sides(final SiteType type)
{
return sides.get(type);
}
/**
* @return List of cells.
*/
public List<Cell> cells()
{
return cells;
}
/**
* @return List of edges.
*/
public List<Edge> edges()
{
return edges;
}
/**
* @return List of vertices.
*/
public List<Vertex> vertices()
{
return vertices;
}
/**
* @param relationType The relation type.
* @param type The graph element type.
*
* @return The list of supported directions according to a type of relation for
* a type of graph element.
*/
public List<DirectionFacing> supportedDirections(final RelationType relationType, final SiteType type)
{
switch (relationType)
{
case Adjacent:
return this.supportedAdjacentDirections.get(type);
case Diagonal:
return this.supportedDiagonalDirections.get(type);
case All:
return this.supportedDirections.get(type);
case OffDiagonal:
return this.supportedOffDirections.get(type);
case Orthogonal:
return this.supportedOrthogonalDirections.get(type);
default:
break;
}
return this.supportedDirections.get(type);
}
/**
* @param type The graph element type.
*
* @return The list of supported directions for a type of graph element.
*/
public List<DirectionFacing> supportedDirections(final SiteType type)
{
return this.supportedDirections.get(type);
}
/**
* @param type The graph element type.
*
* @return The list of orthogonal supported directions for a type of graph
* element.
*/
public List<DirectionFacing> supportedOrthogonalDirections(final SiteType type)
{
return this.supportedOrthogonalDirections.get(type);
}
/**
* @param type The graph element type.
*
* @return The list of off supported directions for a type of graph element.
*/
public List<DirectionFacing> supportedOffDirections(final SiteType type)
{
return this.supportedOffDirections.get(type);
}
/**
* @param type The graph element type.
*
* @return The list of diagonal supported directions for a type of graph
* element.
*/
public List<DirectionFacing> supportedDiagonalDirections(final SiteType type)
{
return this.supportedDiagonalDirections.get(type);
}
/**
* @param type The graph element type.
*
* @return Tist of adjacent supported directions for a type of graph element.
*/
public List<DirectionFacing> supportedAdjacentDirections(final SiteType type)
{
return this.supportedAdjacentDirections.get(type);
}
/**
* @param type The graph element type.
* @return Array of distances to corners for all graph elements.
*/
public int[] distancesToCorners(final SiteType type)
{
return distanceToCorners.get(type);
}
/**
* @param type The graph element type.
* @return Array of distances to sides for all graph elements.
*/
public int[] distancesToSides(final SiteType type)
{
return distanceToSides.get(type);
}
/**
* @param type The graph element type.
* @return Array of distances to centre for all graph elements.
*/
public int[] distancesToCentre(final SiteType type)
{
return distanceToCentre.get(type);
}
/**
* @param type The graph element type.
* @return Array of distances to other graph element of the same type.
*/
public int[][] distancesToOtherSite(final SiteType type)
{
return distanceToOtherSite.get(type);
}
/**
* @param type The graph element type.
* @return Array with, for every region, an array of distances to regions.
* Non-static regions will have null arrays.
*/
public int[][] distancesToRegions(final SiteType type)
{
return distanceToRegions.get(type);
}
/**
* Sets distances to corners
*
* @param type The graph element type.
* @param distanceToCorners
*/
public void setDistanceToCorners(final SiteType type, final int[] distanceToCorners)
{
this.distanceToCorners.put(type, distanceToCorners);
}
/**
* Sets distances to sides
*
* @param type The graph element type.
* @param distanceToSides
*/
public void setDistanceToSides(final SiteType type, final int[] distanceToSides)
{
this.distanceToSides.put(type, distanceToSides);
}
/**
* Sets distances to centres .
*
* @param type The graph element type.
* @param distanceToCentre
*/
public void setDistanceToCentre(final SiteType type, final int[] distanceToCentre)
{
this.distanceToCentre.put(type, distanceToCentre);
}
/**
* @return The number of edges of each tiling, only if the graph uses a regular
* tiling.
*/
public int numEdges()
{
return this.numEdges;
}
/**
* @param type
* @param index
* @return Phase of specified element.
*/
public int phaseByElementIndex(final SiteType type, final int index)
{
return phaseByElementIndex.get(type)[index];
}
//-------------------------------------------------------------------------
/**
* @param x
* @param y
* @return Matching cell, else null.
*/
public Cell findCell(final double x, final double y)
{
// Check for existing cell.
for (final Cell cell : cells)
if (cell.matches(x, y))
return cell;
return null;
}
//-------------------------------------------------------------------------
/**
* @param va
* @param vb
* @return Matching edge, else null.
*/
public Edge findEdge(final Vertex va, final Vertex vb)
{
// Check for existing edge
for (final Edge edge : edges)
if (edge.matches(va, vb))
return edge;
return null;
}
/**
* @param pa
* @param pb
* @return Matching edge, else null.
*/
public Edge findEdge(final Point2D pa, final Point2D pb)
{
// Check for existing edge
for (final Edge edge : edges)
if (edge.matches(pa, pb))
return edge;
return null;
}
/**
* @param midpoint
* @return true if the midpoint is used by an edge.
*/
public Edge midpointEdgeUsed(final Point2D midpoint)
{
for (final Edge edge : edges)
if (Math.abs(edge.centroid().getX() - midpoint.getX()) < 0.0001
&& Math.abs(edge.centroid().getY() - midpoint.getY()) < 0.0001)
return edge;
return null;
}
/**
* @param row
* @param col
* @param level
* @return Cell with the correct coordinates. If not exists null.
*/
public Cell getCellWithCoords(final int row, final int col, final int level)
{
for (final Cell v : cells)
{
if (v.row() == row && v.col() == col && v.layer() == level)
return v;
}
return null;
}
/**
* @param row
* @param col
* @param level
* @return Vertex with the correct coordinates. If not exists null.
*/
public Vertex getVertexWithCoords(final int row, final int col, final int level)
{
for (final Vertex v : vertices)
{
if (v.row() == row && v.col() == col && v.layer() == level)
return v;
}
return null;
}
//-------------------------------------------------------------------------
/**
* @param graphElementType
* @param index
* @return Graph element of given type at given index
*/
public TopologyElement getGraphElement(final SiteType graphElementType, final int index)
{
switch(graphElementType)
{
case Vertex: return vertices().get(index);
case Edge: return edges().get(index);
case Cell: return cells().get(index);
default: return null;
}
}
/**
* @param graphElementType
* @return List of all graph elements of given type
*/
public List<? extends TopologyElement> getGraphElements(final SiteType graphElementType)
{
switch(graphElementType)
{
case Vertex: return vertices();
case Edge: return edges();
case Cell: return cells();
default: return null;
}
}
/**
* @param type
* @return Number of sites we have for given site type
*/
public int numSites(final SiteType type)
{
switch(type)
{
case Vertex: return vertices().size();
case Edge: return edges().size();
case Cell: return cells().size();
default: return Constants.UNDEFINED;
}
}
//-------------------------------------------------------------------------
/**
* @return all elements of the graph.
*/
public ArrayList<TopologyElement> getAllGraphElements()
{
final ArrayList<TopologyElement> allGraphElements = new ArrayList<>();
allGraphElements.addAll(vertices());
allGraphElements.addAll(edges());
allGraphElements.addAll(cells());
return allGraphElements;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return All elements of this graph that are used for some game rule, based on the concepts.
* Used for evaluation Metrics.
*/
public ArrayList<TopologyElement> getAllUsedGraphElements(Game game)
{
final ArrayList<TopologyElement> allUsedGraphElements = new ArrayList<>();
if (game.booleanConcepts().get(Concept.Vertex.id()))
allUsedGraphElements.addAll(vertices());
if (game.booleanConcepts().get(Concept.Edge.id()))
allUsedGraphElements.addAll(edges());
if (game.booleanConcepts().get(Concept.Cell.id()))
allUsedGraphElements.addAll(cells());
return allUsedGraphElements;
}
//-------------------------------------------------------------------------
/**
* Pre-generates tables of distances to each element to each other.
*
* @param type The graph element type.
* @param relation The relation type of the distance to compute.
*/
public void preGenerateDistanceToEachElementToEachOther(final SiteType type, final RelationType relation)
{
if (this.distanceToOtherSite.get(type) != null)
return;
final List<? extends TopologyElement> elements = getGraphElements(type);
final int[][] distances = new int[elements.size()][elements.size()];
for (int idElem = 0; idElem < elements.size(); idElem++)
{
final TopologyElement element = elements.get(idElem);
int currDist = 0;
final TIntArrayList currList = new TIntArrayList();
switch (relation)
{
case Adjacent:
for (final TopologyElement elem : element.adjacent())
currList.add(elem.index());
break;
case All:
for (final TopologyElement elem : element.neighbours())
currList.add(elem.index());
break;
case Diagonal:
for (final TopologyElement elem : element.diagonal())
currList.add(elem.index());
break;
case OffDiagonal:
for (final TopologyElement elem : element.off())
currList.add(elem.index());
break;
case Orthogonal:
for (final TopologyElement elem : element.orthogonal())
currList.add(elem.index());
break;
default:
break;
}
final TIntArrayList nextList = new TIntArrayList();
while (!currList.isEmpty())
{
++currDist;
for (int i = 0; i < currList.size(); i++)
{
final int idNeighbour = currList.getQuick(i);
if (idNeighbour == idElem || distances[idElem][idNeighbour] > 0)
continue;
distances[idElem][idNeighbour] = currDist;
switch (relation)
{
case Adjacent:
for (final TopologyElement elem : elements.get(idNeighbour).adjacent())
if (!nextList.contains(elem.index()) && !currList.contains(elem.index()))
nextList.add(elem.index());
break;
case All:
for (final TopologyElement elem : elements.get(idNeighbour).neighbours())
if (!nextList.contains(elem.index()) && !currList.contains(elem.index()))
nextList.add(elem.index());
break;
case Diagonal:
for (final TopologyElement elem : elements.get(idNeighbour).diagonal())
if (!nextList.contains(elem.index()) && !currList.contains(elem.index()))
nextList.add(elem.index());
break;
case OffDiagonal:
for (final TopologyElement elem : elements.get(idNeighbour).off())
if (!nextList.contains(elem.index()) && !currList.contains(elem.index()))
nextList.add(elem.index());
break;
case Orthogonal:
for (final TopologyElement elem : elements.get(idNeighbour).orthogonal())
if (!nextList.contains(elem.index()) && !currList.contains(elem.index()))
nextList.add(elem.index());
break;
default:
break;
}
}
currList.clear();
currList.addAll(nextList);
nextList.clear();
}
}
this.distanceToOtherSite.put(type, distances);
for (int idElem = 0; idElem < elements.size(); idElem++)
{
final TopologyElement element = elements.get(idElem);
element.sitesAtDistance().clear();
int maxDistance = 0;
for (int idOtherElem = 0; idOtherElem < elements.size(); idOtherElem++)
{
if (maxDistance < distancesToOtherSite(type)[idElem][idOtherElem])
maxDistance++;
}
// We add itself at distance zero.
final List<TopologyElement> distanceZero = new ArrayList<TopologyElement>();
distanceZero.add(element);
element.sitesAtDistance().add(distanceZero);
for (int distance = 1; distance <= maxDistance; distance++)
{
final List<TopologyElement> sitesAtDistance = new ArrayList<TopologyElement>();
for (int idOtherElem = 0; idOtherElem < elements.size(); idOtherElem++)
if (distancesToOtherSite(type)[idElem][idOtherElem] == distance)
sitesAtDistance.add(elements.get(idOtherElem));
element.sitesAtDistance().add(sitesAtDistance);
}
}
}
/**
* Pre-generates tables of distances to regions (for cells).
*
* @param game The game.
* @param regions The regions.
*/
public void preGenerateDistanceToRegionsCells(final Game game, final Regions[] regions)
{
final int numCells = cells.size();
if (numCells == 0)
return;
final int[][] distances = new int[regions.length][];
final Context dummyContext = new Context(game, new Trial(game));
for (int i = 0; i < regions.length; ++i)
{
distances[i] = null;
final Regions region = regions[i];
int[] regionSites = null;
if (region.region() != null)
{
boolean allStatic = true;
for (final RegionFunction regionFunc : region.region())
{
if (regionFunc.type(game) != SiteType.Cell)
{
// We'll skip this one for now TODO should think of a nicer solution for this case
allStatic = false;
continue;
}
else if (regionFunc.isStatic())
{
if (regionSites == null)
{
// regionSites = regionFunc.eval(null).sites();
regionSites = regionFunc.eval(dummyContext).sites();
}
else
{
// final int[] toAppend = regionFunc.eval(null).sites();
final int[] toAppend = regionFunc.eval(dummyContext).sites();
regionSites = Arrays.copyOf(regionSites, regionSites.length + toAppend.length);
System.arraycopy(toAppend, 0, regionSites, regionSites.length - toAppend.length,
toAppend.length);
}
}
else
{
allStatic = false;
break;
}
}
if (!allStatic)
continue;
}
else if (region.sites() == null)
{
continue;
}
else
{
regionSites = region.sites();
}
distances[i] = new int[numCells];
final boolean[] startingPoint = new boolean[numCells];
for (int j = 0; j < regionSites.length; ++j)
{
final int regionSite = regionSites[j];
if (regionSite >= cells.size())
continue;
final Cell regionCell = cells.get(regionSite);
// Start flood-fill from this region Cell
final boolean[] visited = new boolean[numCells];
int currDist = 0;
distances[i][regionSite] = currDist;
visited[regionSite] = true;
startingPoint[regionSite] = true;
final List<Cell> currNeighbourList = new ArrayList<Cell>();
currNeighbourList.addAll(regionCell.adjacent());
final List<Cell> nextNeighbourList = new ArrayList<Cell>();
while (!currNeighbourList.isEmpty())
{
++currDist;
for (final Cell neighbour : currNeighbourList)
{
final int idx = neighbour.index();
if (visited[idx] || startingPoint[idx])
continue;
if (distances[i][idx] > 0 && distances[i][idx] <= currDist)
continue;
distances[i][idx] = currDist;
nextNeighbourList.addAll(neighbour.adjacent());
}
currNeighbourList.clear();
currNeighbourList.addAll(nextNeighbourList);
nextNeighbourList.clear();
}
}
}
this.distanceToRegions.put(SiteType.Cell, distances);
}
/**
* Pre-generates tables of distances to regions (for vertices).
*
* @param game The game.
* @param regions The regions.
*/
public void preGenerateDistanceToRegionsVertices(final Game game, final Regions[] regions)
{
final int numVertices = vertices.size();
final int[][] distances = new int[regions.length][];
final Context dummyContext = new Context(game, new Trial(game));
for (int i = 0; i < regions.length; ++i)
{
distances[i] = null;
final Regions region = regions[i];
int[] regionSites = null;
if (region.region() != null)
{
boolean allStatic = true;
for (final RegionFunction regionFunc : region.region())
{
if (regionFunc.type(game) != SiteType.Vertex)
{
// We'll skip this one for now TODO should think of a nicer solution for this case
allStatic = false;
continue;
}
else if (regionFunc.isStatic())
{
if (regionSites == null)
{
regionSites = regionFunc.eval(null).sites();
}
else
{
// final int[] toAppend = regionFunc.eval(null).sites();
final int[] toAppend = regionFunc.eval(dummyContext).sites();
regionSites = Arrays.copyOf(regionSites, regionSites.length + toAppend.length);
System.arraycopy(toAppend, 0, regionSites, regionSites.length - toAppend.length,
toAppend.length);
}
}
else
{
allStatic = false;
break;
}
}
if (!allStatic)
continue;
}
else if (region.sites() == null)
{
continue;
}
else
{
regionSites = region.sites();
}
distances[i] = new int[numVertices];
final boolean[] startingPoint = new boolean[numVertices];
for (int j = 0; j < regionSites.length; ++j)
{
final int regionSite = regionSites[j];
// System.out.println("regionSite=" + regionSite + ", vertices.size()=" + vertices.size() + ".");
final Vertex regionVertex = vertices.get(regionSite);
// Start flood-fill from this region Vertex
final boolean[] visited = new boolean[numVertices];
int currDist = 0;
distances[i][regionSite] = currDist;
visited[regionSite] = true;
startingPoint[regionSite] = true;
final List<Vertex> currNeighbourList = new ArrayList<Vertex>();
currNeighbourList.addAll(regionVertex.adjacent());
final List<Vertex> nextNeighbourList = new ArrayList<Vertex>();
while (!currNeighbourList.isEmpty())
{
++currDist;
for (final Vertex neighbour : currNeighbourList)
{
final int idx = neighbour.index();
if (visited[idx] || startingPoint[idx])
continue;
if (distances[i][idx] > 0 && distances[i][idx] <= currDist)
continue;
distances[i][idx] = currDist;
nextNeighbourList.addAll(neighbour.adjacent());
}
currNeighbourList.clear();
currNeighbourList.addAll(nextNeighbourList);
nextNeighbourList.clear();
}
}
}
this.distanceToRegions.put(SiteType.Vertex, distances);
}
/**
* Pre-generates tables of distances to precomputed regions such as centre, corners, sides, ...
* @param type Site type for which we want to generate distances
*/
public void preGenerateDistanceTables(final SiteType type)
{
preGenerateDistanceToPrecomputed(type, centre, distanceToCentre);
preGenerateDistanceToPrecomputed(type, corners, distanceToCorners);
preGenerateDistanceToPrecomputed(type, perimeter, distanceToSides);
}
/**
* Pre-generates tables of distances to corners.
* @param type Site type for which we want to generate distances
* @param precomputed Map of precomputed regions to which we want to generate distances
* @param distancesMap Map in which we want to store computed distances
*/
private void preGenerateDistanceToPrecomputed
(
final SiteType type,
final Map<SiteType, List<TopologyElement>> precomputed,
final Map<SiteType, int[]> distancesMap
)
{
final List<? extends TopologyElement> elements = getGraphElements(type);
final int numElements = elements.size();
if (numElements == 0)
return;
final int[] distances = new int[numElements];
Arrays.fill(distances, -1);
int maxDistance = -1;
final boolean[] startingPoint = new boolean[numElements];
for (final TopologyElement corner : precomputed.get(type))
{
// Start flood-fill from this corner
final boolean[] visited = new boolean[numElements];
final int cornerIdx = corner.index();
int currDist = 0;
distances[cornerIdx] = currDist;
visited[cornerIdx] = true;
startingPoint[cornerIdx] = true;
final List<TopologyElement> currNeighbourList = new ArrayList<TopologyElement>();
currNeighbourList.addAll(corner.adjacent());
final List<TopologyElement> nextNeighbourList = new ArrayList<TopologyElement>();
while (!currNeighbourList.isEmpty())
{
++currDist;
for (final TopologyElement neighbour : currNeighbourList)
{
final int idx = neighbour.index();
if (visited[idx] || startingPoint[idx])
continue;
if (distances[idx] > 0 && distances[idx] <= currDist)
continue;
maxDistance = Math.max(maxDistance, currDist);
distances[idx] = currDist;
nextNeighbourList.addAll(neighbour.adjacent());
}
currNeighbourList.clear();
currNeighbourList.addAll(nextNeighbourList);
nextNeighbourList.clear();
}
}
// Any remaining values of -1 are disconnected; give them max distance + 1
ArrayUtils.replaceAll(distances, -1, maxDistance + 1);
distancesMap.put(type, distances);
}
//-------------------------------------------------------------------------
/**
* Optimises memory usage of the graph
*/
public void optimiseMemory()
{
((ArrayList<Cell>) cells).trimToSize();
((ArrayList<Edge>) edges).trimToSize();
((ArrayList<Vertex>) vertices).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : corners.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : cornersConcave.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : cornersConvex.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : major.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : minor.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : outer.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : perimeter.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : inner.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : interlayer.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : top.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : bottom.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : left.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : right.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : centre.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<List<TopologyElement>>> list : phases.entrySet())
((ArrayList<List<TopologyElement>>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<List<TopologyElement>>> list : rows.entrySet())
((ArrayList<List<TopologyElement>>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<List<TopologyElement>>> list : columns.entrySet())
((ArrayList<List<TopologyElement>>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<List<TopologyElement>>> list : layers.entrySet())
((ArrayList<List<TopologyElement>>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<List<TopologyElement>>> list : diagonals.entrySet())
((ArrayList<List<TopologyElement>>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : axials.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : horizontal.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : vertical.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : angled.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : slash.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
for (final Entry<SiteType, List<TopologyElement>> list : slosh.entrySet())
((ArrayList<TopologyElement>) list.getValue()).trimToSize();
// Also tell every vertex, edge, and face, to optimise their memory use
for (final Cell vertex : cells)
{
vertex.optimiseMemory();
}
for (final Edge edge : edges)
{
edge.optimiseMemory();
}
for (final Vertex face : vertices)
{
face.optimiseMemory();
}
}
/**
* @param type
* @return Different numbers of true-ortho-connectivity that different elements of given type in our graph have
*/
public TIntArrayList connectivities(final SiteType type)
{
return connectivities.get(type);
}
/**
* @param game
* @return Different numbers of true-ortho-connectivity among elements
* we play on in given game
*/
public TIntArrayList trueOrthoConnectivities(final Game game)
{
if (game.board().defaultSite() == SiteType.Vertex)
return connectivities.get(SiteType.Vertex);
else
return connectivities.get(SiteType.Cell);
}
/**
* Pregenerates connectivity data for features (for vertices as well
* as cells).
*
* @param game
* @param container
*/
public void pregenerateFeaturesData(final Game game, final Container container)
{
pregenerateFeaturesData(container, SiteType.Cell);
pregenerateFeaturesData(container, SiteType.Vertex);
if (game.board().defaultSite() == SiteType.Edge)
pregenerateFeaturesData(container, SiteType.Edge);
}
/**
* 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.
*
* @return The list of perimeters.
*/
public List<Perimeter> perimeters()
{
return this.perimeters;
}
/**
* Set the perimeters.
*
* @param perimeters The list of perimeters.
*/
public void setPerimeter(List<Perimeter> perimeters)
{
this.perimeters = perimeters;
}
/**
* For every site of given type in this topology, computes a sorted array
* of orthogonal neighbours, with null entries for off-board connections.
*
* While we're going through this, we also find what the maximum
* number of orthogonal connections is across all cells.
*
* This is used for features.
*
* @param container
* @param type
*/
public void pregenerateFeaturesData(final Container container, final SiteType type)
{
final double ANGLES_TOLERANCE = 0.001;
final List<? extends TopologyElement> elements = getGraphElements(type);
connectivities.put(type, new TIntArrayList());
for (final TopologyElement element : elements)
{
final int elementIdx = element.index;
final List<TopologyElement> sortedOrthos = new ArrayList<TopologyElement>();
// Create copy of radials list since we may have to insert extra placeholders
final List<Radial> radials = new ArrayList<Radial>(trajectories().radials(type, elementIdx).inDirection(AbsoluteDirection.Orthogonal));
final int numRealRadials = radials.size();
// if (radials == null)
// continue;
// Our radials may be missing off-board continuations; we'll have to patch these up first
// See if adding one more equal-angle radial completes 360 degrees (primarily for triangular tilings)
if (numRealRadials == 2)
{
final Radial r1 = radials.get(0);
final Radial r2 = radials.get(1);
final double angle = Radials.angle(r1, r2);
if (MathRoutines.approxEquals(angle, (2.0 * Math.PI) / 3.0, ANGLES_TOLERANCE))
{
// The two existing radials have a 120 degrees angle, so if we put one more fake radial
// at another 120 degrees angle we complete the circle
final Point2D newRadEndpoint = MathRoutines.rotate(angle, r2.steps()[1].pt2D(), r2.steps()[0].pt2D());
// Add a tiny error towards right such that, if we get a new radial pointing northwards,
// it gets correctly sorted as first instead of last (due to numeric errors)
final double x = newRadEndpoint.getX() + 0.00001;
final double y = newRadEndpoint.getY();
final double z = r2.steps()[1].pt().z();
final Radial placeholder =
new Radial
(
new GraphElement[]
{
r2.steps()[0],
new game.util.graph.Vertex(Constants.UNDEFINED, x, y, z)
},
AbsoluteDirection.Orthogonal
);
radials.add(placeholder);
//System.out.println("added placeholder: " + placeholder);
// Inserted placeholder, so re-sort
Radials.sort(radials);
}
}
// Only try other changes if we didn't already insert placeholder above
if (numRealRadials == radials.size())
{
// See if any of our real radials need complementary straight-angle continuations
for (int i = 0; i < numRealRadials; ++i)
{
final Radial realRadial = radials.get(i);
final TopologyElement neighbour = elements.get(realRadial.steps()[1].id());
// Search ALL radials of our neighbour for any that lead back to our current element
// (not just orthogonals, because those sometimes get truncated -- see Kensington)
final List<Radial> neighbourRadials = trajectories().radials(type, neighbour.index).inDirection(AbsoluteDirection.All);
for (final Radial neighbourRadial : neighbourRadials)
{
final GraphElement[] path = neighbourRadial.steps();
if (path.length == 2 && path[1].id() == elementIdx)
{
// This neighbour radial leads back to us, AND it does not continue afterwards
// TODO may want to keep a set of directions we already handled here, and skip if no new directions
// Create a placeholder radial to insert, starting at our element
//
// We need to add a step to a non-existing "off-board" element
// We'll always make the placeholder element a vertex, since that's the least
// complex constructor
final double x = 2.0 * path[1].pt().x() - path[0].pt().x();
final double y = 2.0 * path[1].pt().y() - path[0].pt().y();
final double z = 2.0 * path[1].pt().z() - path[0].pt().z();
final Radial placeholder =
new Radial
(
new GraphElement[]
{
path[1],
new game.util.graph.Vertex(Constants.UNDEFINED, x, y, z)
},
AbsoluteDirection.Orthogonal
);
radials.add(placeholder);
//System.out.println("added placeholder: " + placeholder);
}
}
}
// If we added any new radials, we'll have to re-sort our list of radials
Radials.sort(radials);
if (radials.size() > numRealRadials)
{
// We've added fake radials; let's see if we need to add even more to get nice uniform angles
// between consecutive radials
double realRadsAngleReference = Double.NaN;
double fakeRadsAngleReference = Double.NaN;
boolean realAnglesAllSame = true;
boolean fakeAnglesAllSame = true;
for (int i = 0; i < radials.size(); ++i)
{
final Radial r1 = radials.get(i);
final Radial r2 = radials.get((i + 1) % radials.size());
final double angle = Radials.angle(r1, r2);
if (r1.steps()[1].id() == Constants.UNDEFINED || r2.steps()[1].id() == Constants.UNDEFINED)
{
// At least one radial is fake, so this is a fake angle
if (Double.isNaN(fakeRadsAngleReference))
fakeRadsAngleReference = angle;
else if (Math.abs(angle - fakeRadsAngleReference) > ANGLES_TOLERANCE)
fakeAnglesAllSame = false; // Too big a difference
}
else
{
// This is an angle between two real radials
if (Double.isNaN(realRadsAngleReference))
realRadsAngleReference = angle;
else if (Math.abs(angle - realRadsAngleReference) > ANGLES_TOLERANCE)
realAnglesAllSame = false; // Too big a difference
}
}
if (realAnglesAllSame && !Double.isNaN(realRadsAngleReference))
{
// All angles between real radials are nicely the same; see if we can make
// sure that this also happens for angles involving at least one fake radial
if (!fakeAnglesAllSame || Math.abs(realRadsAngleReference - fakeRadsAngleReference) > ANGLES_TOLERANCE)
{
// We actually have work to do
boolean failedFix = false;
final List<Radial> newPlaceholders = new ArrayList<Radial>();
for (int i = 0; i < radials.size(); ++i)
{
final Radial r1 = radials.get(i);
final Radial r2 = radials.get((i + 1) % radials.size());
final double angle = Radials.angle(r1, r2);
// For now we just cover one case: where we simply divide the angle by 2 to make
// it right. This covers the problem of the corners in the Hex rhombus
if (Math.abs((angle / 2.0) - realRadsAngleReference) <= ANGLES_TOLERANCE)
{
// Dividing by 2 solves our problem!
final Point2D newRadEndpoint = MathRoutines.rotate(angle / 2.0, r2.steps()[1].pt2D(), r2.steps()[0].pt2D());
// Add a tiny error towards right such that, if we get a new radial pointing northwards,
// it gets correctly sorted as first instead of last (due to numeric errors)
final double x = newRadEndpoint.getX() + 0.00001;
final double y = newRadEndpoint.getY();
final double z = r2.steps()[1].pt().z();
final Radial placeholder =
new Radial
(
new GraphElement[]
{
r2.steps()[0],
new game.util.graph.Vertex(Constants.UNDEFINED, x, y, z)
},
AbsoluteDirection.Orthogonal
);
newPlaceholders.add(placeholder);
}
else if (!MathRoutines.approxEquals(angle, realRadsAngleReference, ANGLES_TOLERANCE))
{
failedFix = true;
}
}
if (failedFix)
{
// All real radials nicely had uniform angles between them, but fake
// radials messed this up in a way we couldn't fix; better to revert
// to the original radials
radials.clear();
radials.addAll(trajectories().radials(type, elementIdx).inDirection(AbsoluteDirection.Orthogonal));
}
else
{
radials.addAll(newPlaceholders);
}
// Re-sort again, with again more fake radials inserted (maybe)
Radials.sort(radials);
}
}
}
}
// Compute our sorted array of orthogonal connectivities (with null placeholders)
for (final Radial radial : radials)
{
final GraphElement[] path = radial.steps();
if (path[1].id() == Constants.UNDEFINED) // This is a placeholder
{
sortedOrthos.add(null);
}
else
{
sortedOrthos.add(elements.get(path[1].id()));
}
}
if (!connectivities.get(type).contains(sortedOrthos.size()))
connectivities.get(type).add(sortedOrthos.size());
element.setSortedOrthos(sortedOrthos.toArray(new TopologyElement[sortedOrthos.size()]));
//System.out.println(element + " has " + element.sortedOrthos().length + " orthos: " + Arrays.toString(element.sortedOrthos()));
}
connectivities.get(type).sort();
connectivities.get(type).trimToSize();
}
/**
* Checks if we should ignore an array of radials when pre-generating data for features. We ignore
* an array of radials if we've already previously processed an array of radials that is
* (maybe after "rotation") equal.
*
* @param radials
* @param otherRadials
* @return
*/
// private static boolean shouldIgnoreRadials(final int[][] radials, final List<int[][]> otherRadials)
// {
// final int numRadials = radials.length;
// for (final int[][] other : otherRadials)
// {
// final int numRotations = other.length;
//
// for (int rot = 0; rot < numRotations; ++rot)
// {
// boolean allEqual = true;
// for (int i = 0; i < radials.length; ++i)
// {
// if (!Arrays.equals(radials[i], other[((i + rot) % numRadials + numRadials) % numRadials]))
// {
// allEqual = false;
// break;
// }
// }
//
// if (allEqual)
// return true;
// }
// }
//
// return false;
// }
//-------------------------------------------------------------------------
/**
* @return The centre point of the board.
*/
public Point2D.Double centrePoint()
{
if (centre.get(SiteType.Cell).size() == 0)
return new Point2D.Double(0.5, 0.5); // assume world coords in range [0..1]
double avgX = 0;
double avgY = 0;
for (final TopologyElement element : centre.get(SiteType.Cell))
{
avgX += element.centroid().getX();
avgY += element.centroid().getY();
}
avgX /= centre.get(SiteType.Cell).size();
avgY /= centre.get(SiteType.Cell).size();
return new Point2D.Double(avgX, avgY);
}
//-------------------------------------------------------------------------
/**
* To store in the correct list the different properties of a graph element.
*
* @param type
* @param element
*/
public void convertPropertiesToList(final SiteType type, final TopologyElement element)
{
final Properties properties = element.properties();
if (properties.get(Properties.INNER))
inner(type).add(element);
if (properties.get(Properties.OUTER))
outer(type).add(element);
if (properties.get(Properties.INTERLAYER))
interlayer(type).add(element);
if (properties.get(Properties.PERIMETER))
perimeter(type).add(element);
if (properties.get(Properties.CORNER))
corners(type).add(element);
if (properties.get(Properties.CORNER_CONCAVE))
cornersConcave(type).add(element);
if (properties.get(Properties.CORNER_CONVEX))
cornersConvex(type).add(element);
if (properties.get(Properties.MAJOR))
major(type).add(element);
if (properties.get(Properties.MINOR))
minor(type).add(element);
if (properties.get(Properties.CENTRE))
centre(type).add(element);
if (properties.get(Properties.LEFT))
left(type).add(element);
if (properties.get(Properties.TOP))
top(type).add(element);
if (properties.get(Properties.RIGHT))
right(type).add(element);
if (properties.get(Properties.BOTTOM))
bottom(type).add(element);
if (properties.get(Properties.AXIAL))
axial(type).add(element);
if (properties.get(Properties.SLASH))
slash(type).add(element);
if (properties.get(Properties.SLOSH))
slosh(type).add(element);
if (properties.get(Properties.VERTICAL))
vertical(type).add(element);
if (properties.get(Properties.HORIZONTAL))
horizontal(type).add(element);
if (properties.get(Properties.ANGLED))
angled(type).add(element);
if (properties.get(Properties.PHASE_0))
{
phases(type).get(0).add(element);
element.setPhase(0);
}
if (properties.get(Properties.PHASE_1))
{
phases(type).get(1).add(element);
element.setPhase(1);
}
if (properties.get(Properties.PHASE_2))
{
phases(type).get(2).add(element);
element.setPhase(2);
}
if (properties.get(Properties.PHASE_3))
{
phases(type).get(3).add(element);
element.setPhase(3);
}
if (properties.get(Properties.PHASE_4))
{
phases(type).get(4).add(element);
element.setPhase(4);
}
if (properties.get(Properties.PHASE_5))
{
phases(type).get(5).add(element);
element.setPhase(5);
}
if (properties.get(Properties.SIDE_E))
sides.get(type).get(CompassDirection.E).add(element);
if (properties.get(Properties.SIDE_W))
sides.get(type).get(CompassDirection.W).add(element);
if (properties.get(Properties.SIDE_N))
sides.get(type).get(CompassDirection.N).add(element);
if (properties.get(Properties.SIDE_S))
sides.get(type).get(CompassDirection.S).add(element);
if (properties.get(Properties.SIDE_NE))
sides.get(type).get(CompassDirection.NE).add(element);
if (properties.get(Properties.SIDE_NW))
sides.get(type).get(CompassDirection.NW).add(element);
if (properties.get(Properties.SIDE_SW))
sides.get(type).get(CompassDirection.SW).add(element);
if (properties.get(Properties.SIDE_SE))
sides.get(type).get(CompassDirection.SE).add(element);
}
//-------------------------------------------------------------------------
/**
* @param type Graph element type.
* @param index Element index.
* @return Phase (colouring) of the specified element, in range 0..3.
*/
public int elementPhase(final SiteType type, final int index)
{
final List<? extends TopologyElement> elements = getGraphElements(type);
for (int c = 0; c < Constants.MAX_CELL_COLOURS; c++)
if (phases(type).get(c).contains(elements.get(index)))
return c;
return -1;
}
/**
* @param type Graph element type.
*/
public void crossReferencePhases(final SiteType type)
{
final List<? extends TopologyElement> elements = getGraphElements(type);
final int[] values = new int[elements.size()];
for (int e = 0; e < elements.size(); e++)
values[e] = elementPhase(type, e);
this.phaseByElementIndex.put(type, values);
}
//-------------------------------------------------------------------------
/**
* Compute the relations and steps between each graph element of the same type.
*
* @param type The graph element type.
*/
public void computeRelation(final SiteType type)
{
if (trajectories == null)
return;
final List<? extends TopologyElement> elements = getGraphElements(type);
for (final TopologyElement element : elements)
{
final List<Step> stepsNeighbours = trajectories.steps(type, element.index(), type, AbsoluteDirection.All);
for (final Step step : stepsNeighbours)
{
GraphUtilities.addNeighbour(type, element, elements.get(step.to().id()));
}
final List<Step> stepsAdjacent = trajectories.steps(type, element.index(), type, AbsoluteDirection.Adjacent);
for (final Step step : stepsAdjacent)
{
GraphUtilities.addAdjacent(type, element, elements.get(step.to().id()));
}
final List<Step> stepsOrthogonal = trajectories.steps(type, element.index(), type, AbsoluteDirection.Orthogonal);
for (final Step step : stepsOrthogonal)
{
GraphUtilities.addOrthogonal(type, element, elements.get(step.to().id()));
}
final List<Step> stepsDiagonal = trajectories.steps(type, element.index(), type, AbsoluteDirection.Diagonal);
for (final Step step : stepsDiagonal)
{
GraphUtilities.addDiagonal(type, element, elements.get(step.to().id()));
}
final List<Step> stepsOff = trajectories.steps(type, element.index(), type, AbsoluteDirection.OffDiagonal);
for (final Step step : stepsOff)
{
GraphUtilities.addOff(type, element, elements.get(step.to().id()));
}
}
}
//-------------------------------------------------------------------------
/**
* Pre-generate the rows for a graph element.
*
* @param type The graph element type.
* @param threeDimensions True if this is a 3D game.
*/
public void computeRows(final SiteType type, final boolean threeDimensions)
{
rows(type).clear();
if (graph() == null || graph().duplicateCoordinates(type) || threeDimensions) // If duplicate
{
final TDoubleArrayList rowCentroids = new TDoubleArrayList();
for (final TopologyElement element : getGraphElements(type))
{
// We count the rows only on the ground.
if (element.centroid3D().z() != 0)
continue;
final double yElement = element.centroid3D().y();
boolean found = false;
for (int i = 0; i < rowCentroids.size(); i++)
if (Math.abs(yElement - rowCentroids.get(i)) < 0.001)
{
found = true;
break;
}
if (!found)
rowCentroids.add(yElement);
}
rowCentroids.sort();
for (int i = 0; i < rowCentroids.size(); i++)
{
rows(type).add(new ArrayList<TopologyElement>());
for (final TopologyElement element : getGraphElements(type))
if (Math.abs(element.centroid3D().y() - rowCentroids.get(i)) < 0.001)
{
rows(type).get(i).add(element);
element.setRow(i);
}
}
}
else // If not we take that from the graph.
{
for (final TopologyElement element : getGraphElements(type))
{
final int rowId = element.row();
if (rows(type).size() > rowId)
rows(type).get(rowId).add(element);
else
{
while (rows(type).size() <= rowId)
rows(type).add(new ArrayList<TopologyElement>());
rows(type).get(rowId).add(element);
}
}
}
}
/**
* Pre-generate the columns for a graph element.
*
* @param type The graph element type.
* @param threeDimensions True if this is a 3D game.
*/
public void computeColumns(final SiteType type, final boolean threeDimensions)
{
columns(type).clear();
if (graph() == null || graph().duplicateCoordinates(type) || threeDimensions) // If duplicate
{
final TDoubleArrayList colCentroids = new TDoubleArrayList();
for (final TopologyElement element : getGraphElements(type))
{
// We count the columns only on the ground.
if (element.centroid3D().z() != 0)
continue;
final double xElement = element.centroid3D().x();
boolean found = false;
for (int i = 0; i < colCentroids.size(); i++)
if (Math.abs(xElement - colCentroids.get(i)) < 0.001)
{
found = true;
break;
}
if (!found)
colCentroids.add(xElement);
}
colCentroids.sort();
for (int i = 0; i < colCentroids.size(); i++)
{
columns(type).add(new ArrayList<TopologyElement>());
for (final TopologyElement element : getGraphElements(type))
if (Math.abs(element.centroid3D().x() - colCentroids.get(i)) < 0.001)
{
columns(type).get(i).add(element);
element.setColumn(i);
}
}
}
else // If not we take that from the graph.
{
for (final TopologyElement element : getGraphElements(type))
{
final int columnId = element.col();
if (columns(type).size() > columnId)
columns(type).get(columnId).add(element);
else
{
while (columns(type).size() <= columnId)
columns(type).add(new ArrayList<TopologyElement>());
columns(type).get(columnId).add(element);
}
}
}
}
/**
* Pre-generate the columns for a graph element.
*
* @param type The graph element type.
*/
public void computeLayers(final SiteType type)
{
layers(type).clear();
if (graph() == null || graph().duplicateCoordinates(type)) // If duplicate
{
final TDoubleArrayList layerCentroids = new TDoubleArrayList();
for (final TopologyElement element : getGraphElements(type))
{
final double z = element.centroid3D().z();
if (layerCentroids.isEmpty())
{
layerCentroids.add(z);
}
else
{
final int insertIdx = layerCentroids.binarySearch(z);
if (insertIdx < 0)
{
// Only insert if it's not already there
layerCentroids.insert(-insertIdx, z);
}
}
}
//layerCentroids.sort(); Already sorted
for (int i = 0; i < layerCentroids.size(); i++)
{
layers(type).add(new ArrayList<TopologyElement>());
for (final TopologyElement element : getGraphElements(type))
if (element.centroid3D().z() == layerCentroids.getQuick(i))
{
layers(type).get(i).add(element);
element.setLayer(i);
}
}
}
else // If not we take that from the graph.
{
for (final TopologyElement element : getGraphElements(type))
{
final int layerId = element.layer();
// System.out.println(type + " " + element.index() + " layer is " + layerId);
if (layers(type).size() > layerId)
layers(type).get(layerId).add(element);
else
{
while (layers(type).size() <= layerId)
layers(type).add(new ArrayList<TopologyElement>());
layers(type).get(layerId).add(element);
}
}
}
}
/**
* @param type The graph element type.
*/
public void computeCoordinates(final SiteType type)
{
if (graph() == null || graph().duplicateCoordinates(type)) // If duplicate
{
for (final TopologyElement element : getGraphElements(type))
{
String columnString = "";
// To handle case with column coordinate at more than Z.
if (element.col() >= 26)
columnString = String.valueOf((char) ('A' + (element.col() / 26) - 1));
columnString += String.valueOf((char) ('A' + element.col() % 26));
final String rowString = String.valueOf(element.row() + 1);
final String label = columnString + rowString;
element.setLabel(label);
}
}
}
/**
* @return the trajectories.
*/
public Trajectories trajectories()
{
return trajectories;
}
/**
* Set the trajectories.
*
* @param trajectories
*/
public void setTrajectories(final Trajectories trajectories)
{
this.trajectories = trajectories;
}
/**
* Compute the supported directions.
*
* @param type The graph element type.
*/
public void computeSupportedDirection(final SiteType type)
{
if (trajectories == null)
return;
final List<? extends TopologyElement> elements = getGraphElements(type);
final List<DirectionFacing> supportedDirection = supportedDirections.get(type);
final List<DirectionFacing> supportedOrthogonalDirection = supportedOrthogonalDirections.get(type);
final List<DirectionFacing> supportedDiagonalDirection = supportedDiagonalDirections.get(type);
final List<DirectionFacing> supportedAdjacentDirection = supportedAdjacentDirections.get(type);
final List<DirectionFacing> supportedOffDirection = supportedOffDirections.get(type);
supportedDirection.clear();
supportedOrthogonalDirection.clear();
supportedDiagonalDirection.clear();
supportedAdjacentDirection.clear();
supportedOffDirection.clear();
for (final TopologyElement element : elements)
{
final List<Step> steps = trajectories.steps(type, element.index(), type, AbsoluteDirection.All);
final List<Step> stepsOrtho = trajectories.steps(type, element.index(), type, AbsoluteDirection.Orthogonal);
final List<Step> stepsDiago = trajectories.steps(type, element.index(), type, AbsoluteDirection.Diagonal);
final List<Step> stepsAdjacent = trajectories.steps(type, element.index(), type,
AbsoluteDirection.Adjacent);
final List<Step> stepsOff = trajectories.steps(type, element.index(), type, AbsoluteDirection.OffDiagonal);
for (final Step step : steps)
{
for (int a = step.directions().nextSetBit(0); a >= 0; a = step.directions().nextSetBit(a + 1))
{
final AbsoluteDirection abs = AbsoluteDirection.values()[a];
final DirectionFacing direction = AbsoluteDirection.convert(abs);
if (direction != null)
{
if (!supportedDirection.contains(direction))
supportedDirection.add(direction);
if (!element.supportedDirections().contains(direction))
element.supportedDirections().add(direction);
}
}
}
for (final Step step : stepsOrtho)
{
for (int a = step.directions().nextSetBit(0); a >= 0; a = step.directions().nextSetBit(a + 1))
{
final AbsoluteDirection abs = AbsoluteDirection.values()[a];
final DirectionFacing direction = AbsoluteDirection.convert(abs);
if (direction != null)
{
if (!supportedOrthogonalDirection.contains(direction))
supportedOrthogonalDirection.add(direction);
if (!element.supportedOrthogonalDirections().contains(direction))
element.supportedOrthogonalDirections().add(direction);
}
}
}
for (final Step step : stepsDiago)
{
for (int a = step.directions().nextSetBit(0); a >= 0; a = step.directions().nextSetBit(a + 1))
{
final AbsoluteDirection abs = AbsoluteDirection.values()[a];
final DirectionFacing direction = AbsoluteDirection.convert(abs);
if (direction != null)
{
if (!supportedDiagonalDirection.contains(direction))
supportedDiagonalDirection.add(direction);
if (!element.supportedDiagonalDirections().contains(direction))
element.supportedDiagonalDirections().add(direction);
}
}
}
for (final Step step : stepsAdjacent)
{
for (int a = step.directions().nextSetBit(0); a >= 0; a = step.directions().nextSetBit(a + 1))
{
final AbsoluteDirection abs = AbsoluteDirection.values()[a];
final DirectionFacing direction = AbsoluteDirection.convert(abs);
if (direction != null)
{
if (!supportedAdjacentDirection.contains(direction))
supportedAdjacentDirection.add(direction);
if (!element.supportedAdjacentDirections().contains(direction))
element.supportedAdjacentDirections().add(direction);
}
}
}
for (final Step step : stepsOff)
{
for (int a = step.directions().nextSetBit(0); a >= 0; a = step.directions().nextSetBit(a + 1))
{
final AbsoluteDirection abs = AbsoluteDirection.values()[a];
final DirectionFacing direction = AbsoluteDirection.convert(abs);
if (direction != null)
{
if (!supportedOffDirection.contains(direction))
supportedOffDirection.add(direction);
if (!element.supportedOffDirections().contains(direction))
element.supportedOffDirections().add(direction);
}
}
}
}
// To sort the directions in compass direction.
final Comparator<DirectionFacing> dirComparator = new Comparator<DirectionFacing>()
{
@Override
public int compare(final DirectionFacing d1, final DirectionFacing d2)
{
return (d1.index() - d2.index());
}
};
Collections.sort(supportedDirection, dirComparator);
Collections.sort(supportedOrthogonalDirection, dirComparator);
Collections.sort(supportedDiagonalDirection, dirComparator);
Collections.sort(supportedAdjacentDirection, dirComparator);
Collections.sort(supportedOffDirection, dirComparator);
// System.out.println("SupportedDirections are " + supportedDirection);
// System.out.println("SupportedOrthoDirections are " + supportedOrthogonalDirection);
// System.out.println("SupportedDiagoDirections are " + supportedDiagonalDirection);
// System.out.println("SupportedAdjacentDirections are " + supportedAdjacentDirection);
// System.out.println("SupportedOffDirections are " + supportedOffDirection);
}
//-------------------------------------------------------------------------
/**
* Compute all the edges crossing another.
*/
public void computeDoesCross()
{
for (final Edge edge: edges())
edge.setDoesCross(new BitSet(edges.size()));
for (int i = 0; i < edges.size(); i++)
{
final Edge edge = edges.get(i);
final double tolerance = 0.001;
final Point2D ptA = edge.vA().centroid();
final Point2D ptB = edge.vB().centroid();
for (int j = i + 1; j < edges.size(); j++)
{
final Edge otherEdge = edges.get(j);
final Point2D ptEA = otherEdge.vA().centroid();
final Point2D ptEB = otherEdge.vB().centroid();
if (ptA.distance(ptEA) < tolerance || ptA.distance(ptEB) < tolerance || ptB.distance(ptEA) < tolerance
|| ptB.distance(ptEB) < tolerance)
continue;
if (MathRoutines.lineSegmentsIntersect(ptA.getX(), ptA.getY(), ptB.getX(), ptB.getY(), ptEA.getX(),
ptEA.getY(), ptEB.getX(), ptEB.getY()))
{
otherEdge.setDoesCross(edge.index());
edge.setDoesCross(otherEdge.index());
}
}
}
}
/**
* @return To know if the graph uses a regular tiling.
*/
public boolean isRegular()
{
return graph.isRegular();
}
/**
* Compute the number of edges of each tiling if the graph uses a regular
* tiling.
*/
public void computeNumEdgeIfRegular()
{
if (isRegular() && cells.size() > 0)
this.numEdges = cells.get(0).edges().size();
}
//-------------------------------------------------------------------------
/**
* @param type The SiteType of the sites.
* @param origin The index of the origin site.
* @param target The index of the target site.
* @return One of the minimum walk between two sites in the graph (with the
* minimum of Forward step).
*/
public StepType[] shortestWalk(final SiteType type, final int origin, final int target)
{
final List<? extends TopologyElement> elements = getGraphElements(type);
final List<DirectionFacing> orthogonalSupported = supportedOrthogonalDirections.get(type);
// No walk if the sites are the same or if the sites are incorrect.
if (origin == target || origin < 0 || target < 0 || origin >= elements.size() || target >= elements.size())
{
return new StepType[0];
}
else
{
// The min walk to return.
final List<StepType> returnedWalk = new ArrayList<StepType>();
// The first direction of the origin site (North for square tiling).
final DirectionFacing initialDirection = supportedOrthogonalDirections.get(type).get(0);
// All the sites reached in stepping.
final TIntArrayList reachedSites = new TIntArrayList();
reachedSites.add(origin);
// All the sites to explore or currently in exploration in stepping..
final TIntArrayList toExplore = new TIntArrayList();
// The current facing direction of the walk in each site currently in
// exploration.
final List<DirectionFacing> facingDirectionSitesToExplore = new ArrayList<DirectionFacing>();
// The current steps used to reach the sites currently in exploration.
final List<List<StepType>> stepUsed = new ArrayList<List<StepType>>();
// We init the structures used to get the minwalk.
toExplore.add(origin);
facingDirectionSitesToExplore.add(initialDirection);
stepUsed.add(new ArrayList<StepType>());
// We check all the sites to explore in the order we found them.
while (!toExplore.isEmpty())
{
// We get the site and direction.
final int fromSite = toExplore.get(0);
final DirectionFacing fromSiteDirection = facingDirectionSitesToExplore.get(0);
// Get the site in the forward direction.
final List<Step> stepsDirection = graph.trajectories().steps(type, fromSite,
fromSiteDirection.toAbsolute());
int toForward = Constants.UNDEFINED;
for (final Step stepDirection : stepsDirection)
{
if (stepDirection.from().siteType() != stepDirection.to().siteType())
continue;
toForward = stepDirection.to().id();
}
// If that site exists and not reached until now.
if (toForward != Constants.UNDEFINED && !reachedSites.contains(toForward))
{
toExplore.add(toForward);
facingDirectionSitesToExplore.add(fromSiteDirection);
stepUsed.add(new ArrayList<StepType>());
final List<StepType> previousWalk = stepUsed.get(0);
stepUsed.get(stepUsed.size() - 1).addAll(previousWalk);
stepUsed.get(stepUsed.size() - 1).add(StepType.F);
reachedSites.add(toForward);
// If that's the target site we stop.
if (toForward == target)
{
returnedWalk.addAll(stepUsed.get(stepUsed.size() - 1));
break;
}
}
// We try all the right and left directions.
for (int i = 1; i < orthogonalSupported.size() / 2 + 1; i++)
{
// We get the right direction on that site.
DirectionFacing currentRightDirection = fromSiteDirection;
for (int j = 0; j < i; j++)
{
currentRightDirection = currentRightDirection.right();
while (!orthogonalSupported.contains(currentRightDirection))
currentRightDirection = currentRightDirection.right();
}
// We get the site in that direction.
final List<Step> stepsRightDirection = graph.trajectories().steps(type, fromSite,
currentRightDirection.toAbsolute());
int toRight = Constants.UNDEFINED;
for (final Step stepDirection : stepsRightDirection)
{
if (stepDirection.from().siteType() != stepDirection.to().siteType())
continue;
toRight = stepDirection.to().id();
}
// If that site exists in that direction and did not reached yet.
if (toRight != Constants.UNDEFINED && !reachedSites.contains(toRight))
{
toExplore.add(toRight);
facingDirectionSitesToExplore.add(currentRightDirection);
final List<StepType> previousWalk = stepUsed.get(0);
stepUsed.add(new ArrayList<StepType>());
stepUsed.get(stepUsed.size() - 1).addAll(previousWalk);
for (int j = 0; j < i; j++)
stepUsed.get(stepUsed.size() - 1).add(StepType.R);
stepUsed.get(stepUsed.size() - 1).add(StepType.F);
reachedSites.add(toRight);
// If that's the target site we stop.
if (toRight == target)
{
returnedWalk.addAll(stepUsed.get(stepUsed.size() - 1));
break;
}
}
// We get the left direction on that site.
DirectionFacing currentLeftDirection = fromSiteDirection;
for (int j = 0; j < i; j++)
{
currentLeftDirection = currentLeftDirection.left();
while (!orthogonalSupported.contains(currentLeftDirection))
currentLeftDirection = currentLeftDirection.left();
}
// We get the site in that direction.
final List<Step> stepsLeftDirection = graph.trajectories().steps(type, fromSite,
currentLeftDirection.toAbsolute());
int toLeft = Constants.UNDEFINED;
for (final Step stepDirection : stepsLeftDirection)
{
if (stepDirection.from().siteType() != stepDirection.to().siteType())
continue;
toLeft = stepDirection.to().id();
}
// If that site exists in that direction and did not reached yet.
if (toLeft != Constants.UNDEFINED && !reachedSites.contains(toLeft))
{
toExplore.add(toLeft);
facingDirectionSitesToExplore.add(currentLeftDirection);
final List<StepType> previousWalk = stepUsed.get(0);
stepUsed.add(new ArrayList<StepType>());
stepUsed.get(stepUsed.size() - 1).addAll(previousWalk);
for (int j = 0; j < i; j++)
stepUsed.get(stepUsed.size() - 1).add(StepType.L);
stepUsed.get(stepUsed.size() - 1).add(StepType.F);
reachedSites.add(toLeft);
// If that's the target site we stop.
if (toLeft == target)
{
returnedWalk.addAll(stepUsed.get(stepUsed.size() - 1));
break;
}
}
}
// We remove the explored one.
toExplore.removeAt(0);
stepUsed.remove(0);
facingDirectionSitesToExplore.remove(0);
// To print the current exploration
// System.out.println("\nNew Explo:");
// for (int i = 0; i < exploration.size(); i++)
// {
// System.out.println("Explore " + exploration.get(i) + " current Direction Is "
// + explorationDirection.get(i) + " current Steps are " + stepTypeUsed.get(i));
// }
// System.out.println();
}
// We convert to an array and we return.
final StepType[] returnedWalkArray = new StepType[returnedWalk.size()];
for (int i = 0; i < returnedWalk.size(); i++)
returnedWalkArray[i] = returnedWalk.get(i);
return returnedWalkArray;
}
}
// /**
// * Compute one minimum walk between each pair of sites.
// *
// * @param type The graph element type.
// * @return An array with one minimum walk between each pair of sites.
// * [site1][site2][minWalk].
// */
// public StepType[][][] oneMinWalkBetweanEachPairSites(final SiteType type)
// {
// final List<? extends TopologyElement> elements = getGraphElements(type);
// final StepType[][][] minWalks = new StepType[elements.size()][elements.size()][];
//
// for (int iElem = 0; iElem < elements.size(); iElem++)
// for (int jElem = 0; jElem < elements.size(); jElem++)
// minWalks[iElem][jElem] = oneMinWalkBetweenTwoSites(type, iElem, jElem);
//
// return minWalks;
// }
}
| 85,221 | 29.933575 | 165 | java |
Ludii | Ludii-master/Core/src/other/topology/TopologyElement.java | package other.topology;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.util.directions.DirectionFacing;
import game.util.graph.Properties;
import main.math.Point3D;
import main.math.RCL;
/**
* Common graph element that is extended by vertex, edge and cell.
*
* @author Matthew.stephenson and Eric.Piette
*/
public abstract class TopologyElement
{
/** Index into list of the graph element. */
protected int index;
/** Centroid of the graph element. */
protected Point3D centroid;
/** [row,col,layer] coordinate on the board. */
protected RCL coord = new RCL();
/** Cell label. */
protected String label = "?";
/** The cost of the graph element. */
private int cost;
/** The phase of the element. */
private int phase;
/** Supported directions. */
private final List<DirectionFacing> supportedDirections = new ArrayList<DirectionFacing>();
/** Supported Orthogonal directions. */
private final List<DirectionFacing> supportedOrthogonalDirections = new ArrayList<DirectionFacing>();
/** Supported Diagonal directions. */
private final List<DirectionFacing> supportedDiagonalDirections = new ArrayList<DirectionFacing>();
/** Supported Adjacent directions. */
private final List<DirectionFacing> supportedAdjacentDirections = new ArrayList<DirectionFacing>();
/** Supported Off directions. */
private final List<DirectionFacing> supportedOffDirections = new ArrayList<DirectionFacing>();
// --------------------Pre-Generation----------------------------------------------
/**
* Properties of the graph element (Inner, Centre, Corner, ect..).
*/
protected Properties properties = new Properties();
/** A list of all the sites at a specific distance from that site. */
private final List<List<TopologyElement>> sitesAtDistance = new ArrayList<List<TopologyElement>>();
//-----------------Pregenerated for features-------------------------------
/**
* Array of orthogonally connected vertices, sorted for indexing by features.
* Also contains null entries for off-board!
*/
protected TopologyElement[] sortedOrthos = null;
//----------------------------Methods----------------------------------------
/**
* @return The graph element type.
*/
public abstract SiteType elementType();
/**
* @return The centroid of the graph element.
*/
public Point2D centroid()
{
return new Point2D.Double(centroid.x(), centroid.y());
}
/**
* @return The centroid in 3D of the graph element.
*/
public Point3D centroid3D()
{
return centroid;
}
/**
* To set the centroid of the vertex (useful for DrawnState methods)
*
* @param centroidX The new centroid X.
* @param centroidY The new centroid Y.
* @param centroidZ The new centroid Z.
*/
public void setCentroid(final double centroidX, final double centroidY, final double centroidZ)
{
centroid = new Point3D(centroidX, centroidY, centroidZ);
}
/**
* @return Index into list in Graph.
*/
public int index()
{
return index;
}
/**
* @return Phase, i.e. colour, if relevant.
*/
public int phase()
{
return phase;
}
/**
* To set the phase of the vertex.
*
* @param phase
*/
public void setPhase(final int phase)
{
this.phase = phase;
}
/**
* To set the index.
*
* @param index The new index.
*/
public void setIndex(final int index)
{
this.index = index;
}
/**
* @return element label.
*/
public String label()
{
return label;
}
/**
* @return the row coordinate.
*/
public int row()
{
return coord.row();
}
/**
* Set the row.
*
* @param r The new row.
*/
public void setRow(final int r)
{
coord.setRow(r);
}
/**
* Set the column.
*
* @param c The new column.
*/
public void setColumn(final int c)
{
coord.setColumn(c);
}
/**
* Set the layer.
*
* @param l The new layer.
*/
public void setLayer(final int l)
{
coord.setLayer(l);
}
/**
* @return the col coordinate.
*/
public int col()
{
return coord.column();
}
/**
* @return the layer coordinate.
*/
public int layer()
{
return coord.layer();
}
/**
* To set the label of the element.
*
* @param label
*/
public void setLabel(final String label)
{
this.label = label;
}
/**
* @return Cost of the element.
*/
public int cost()
{
return cost;
}
/**
* To set the cost of an element.
*
* @param cost The new cost.
*/
public void setCost(final int cost)
{
this.cost = cost;
}
/**
* To set the coordinates.
*
* @param row
* @param col
* @param level
*/
public void setCoord(final int row, final int col, final int level)
{
coord.set(row, col, level);
}
// /**
// * To set the row coordinate.
// *
// * @param row
// */
// public void setRow(final int row)
// {
// coord.row = row;
// }
//
// /**
// * To set the col coordinate.
// *
// * @param col
// */
// public void setColumn(final int col)
// {
// coord.column = col;
// }
//
// /**
// * To set the layer coordinate.
// *
// * @param layer
// */
// public void setLayer(final int layer)
// {
// coord.layer = layer;
// }
/**
* @return The vertices of this element.
*/
public abstract List<Vertex> vertices();
/**
* @return The edges of this element.
*/
public abstract List<Edge> edges();
/**
* @return The cells of this element.
*/
public abstract List<Cell> cells();
/**
* @return The vertices enclosed by this element.
*/
public abstract List<Vertex> regionVertices();
/**
* @return The edges enclosed by this element.
*/
public abstract List<Edge> regionEdges();
/**
* @return The cells enclosed by this element.
*/
public abstract List<Cell> regionCells();
//--------------------Pre-Generation methods----------------------------------
/**
* @return The properties of the graph element (INNER, CENTRE, CORNER, ect...).
*/
public Properties properties()
{
return properties;
}
/**
* Sets the array of sorted orthos
*
* @param sortedOrthos
*/
public void setSortedOrthos(final TopologyElement[] sortedOrthos)
{
this.sortedOrthos = sortedOrthos;
}
/**
* @return Sorted array of sorted orthogonal
*/
public TopologyElement[] sortedOrthos()
{
return sortedOrthos;
}
/**
* Set the the properties of the graph element (INNER, CENTRE, CORNER, ect...).
*
* @param properties The properties.
*/
public void setProperties(final Properties properties)
{
this.properties = properties;
}
/**
* @return The orthogonal elements of that element.
*/
public abstract List<? extends TopologyElement> orthogonal();
/**
* @return The diagonal elements of that element.
*/
public abstract List<? extends TopologyElement> diagonal();
/**
* @return The off elements of that element.
*/
public abstract List<? extends TopologyElement> off();
/**
* @return The neighbours elements of that element.
*/
public abstract List<? extends TopologyElement> neighbours();
/**
* @return The adjacent elements of that element.
*/
public abstract List<? extends TopologyElement> adjacent();
/**
* @param relationType The relation type.
*
* @return The list of supported directions according to a type of relation.
*/
public List<DirectionFacing> supportedDirections(final RelationType relationType)
{
switch (relationType)
{
case Adjacent:
return supportedAdjacentDirections;
case Diagonal:
return supportedDiagonalDirections;
case All:
return supportedDirections;
case OffDiagonal:
return supportedOffDirections;
case Orthogonal:
return supportedOrthogonalDirections;
default:
break;
}
return supportedDirections;
}
/**
* @return The list of sites at a specific distance.
*/
public List<List<TopologyElement>> sitesAtDistance()
{
return sitesAtDistance;
}
/**
* @return The list of supported directions.
*/
public List<DirectionFacing> supportedDirections()
{
return supportedDirections;
}
/**
* @return The list of orthogonal supported directions.
*/
public List<DirectionFacing> supportedOrthogonalDirections()
{
return supportedOrthogonalDirections;
}
/**
* @return The list of off supported directions.
*/
public List<DirectionFacing> supportedOffDirections()
{
return supportedOffDirections;
}
/**
* @return The list of diagonal supported directions.
*/
public List<DirectionFacing> supportedDiagonalDirections()
{
return supportedDiagonalDirections;
}
/**
* @return The list of adjacent supported directions.
*/
public List<DirectionFacing> supportedAdjacentDirections()
{
return supportedAdjacentDirections;
}
}
| 8,732 | 18.713318 | 102 | java |
Ludii | Ludii-master/Core/src/other/topology/Vertex.java | package other.topology;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import game.types.board.SiteType;
import main.math.Point3D;
/**
* Vertex of the graph (equivalent to any intersection of a board).
*
* @author Eric.Piette
*/
public final class Vertex extends TopologyElement implements Serializable
{
private static final long serialVersionUID = 1L;
//-----------------------------------------------------------------------------
/** List of cells. */
private final List<Cell> cells = new ArrayList<Cell>();
/** List of edge. */
private final List<Edge> edges = new ArrayList<Edge>();
private Vertex pivot = null;
//----------------------------------------------------------------------------
/** Orthogonally connected vertices. */
private final List<Vertex> orthogonal = new ArrayList<Vertex>();
/** Diagonally connected vertices. */
private final List<Vertex> diagonal = new ArrayList<Vertex>();
/** Off connected vertices. */
private final List<Vertex> off = new ArrayList<Vertex>();
/** Adjacent neighbours. */
private final List<Vertex> adjacent = new ArrayList<Vertex>();
/** Neighbours. */
private final List<Vertex> neighbours = new ArrayList<Vertex>();
//-------------------------------------------------------------------------
/**
* Definition of a vertex.
*
* @param index
* @param x
* @param y
* @param z
*/
public Vertex(final int index, final double x, final double y, final double z)
{
this.index = index;
centroid = new Point3D(x, y, z);
}
//-------------------------------------------------------------------------
/**
* @return cells using that vertex.
*/
@Override
public List<Cell> cells()
{
return cells;
}
/**
* @return Edges using that vertex.
*/
@Override
public List<Edge> edges()
{
return edges;
}
@Override
public List<Vertex> vertices()
{
final ArrayList<Vertex> vertices = new ArrayList<>();
vertices.add(this);
return vertices;
}
/**
* @return The pivot vertex.
*/
public Vertex pivot()
{
return pivot;
}
/**
* Set the pivot vertex.
*
* @param vertex The pivot vertex.
*/
public void setPivot(final Vertex vertex)
{
pivot = vertex;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "Vertex: " + index;
}
//-------------------------------------------------------------------------
/**
* Optimises memory usage by this vertex.
*/
public void optimiseMemory()
{
((ArrayList<Cell>) cells).trimToSize();
((ArrayList<Edge>) edges).trimToSize();
}
//-------------------------------------------------------------------------
@Override
public SiteType elementType()
{
return SiteType.Vertex;
}
//-------------------------------------------------------------------------
/**
* @return Orthogonally connected vertices.
*/
@Override
public List<Vertex> orthogonal()
{
return orthogonal;
}
/**
* @return Diagonally connected vertices.
*/
@Override
public List<Vertex> diagonal()
{
return diagonal;
}
/**
* @return Off connected vertices.
*/
@Override
public List<Vertex> off()
{
return off;
}
/**
* @return All the adjacent neighbours.
*/
@Override
public List<Vertex> adjacent()
{
return adjacent;
}
/**
* @return All the neighbours.
*/
@Override
public List<Vertex> neighbours()
{
return neighbours;
}
/**
*
* @param vid
* @return True if the vertex vid is a neighbor of the current vertex.
*/
public boolean neighbour(final int vid)
{
for (final Vertex v : diagonal)
{
if (v.index() == vid)
return true;
}
for (final Vertex v : orthogonal)
{
if (v.index() == vid)
return true;
}
return false;
}
/**
* @return The number of orthogonally connected vertices.
*/
public int orthogonalOutDegree()
{
return orthogonal.size();
}
//-------------------------------------------------------------------------
@Override
public List<Vertex> regionVertices()
{
return vertices();
}
@Override
public List<Edge> regionEdges()
{
return new ArrayList<>();
}
@Override
public List<Cell> regionCells()
{
return new ArrayList<>();
}
}
| 4,256 | 17.428571 | 80 | java |
Ludii | Ludii-master/Core/src/other/translation/LanguageUtils.java | package other.translation;
import java.util.ArrayList;
import java.util.List;
import game.types.board.SiteType;
import game.types.play.RoleType;
import main.Constants;
/**
* @author Matthew.Stephenson
*
*/
public class LanguageUtils
{
//-------------------------------------------------------------------------
/**
* Splits an item string into its piece name and owner.
* @param itemName
* @return "Pawn3" -> ["Pawn","3"]
*/
public static String[] SplitPieceName(final String itemName)
{
int index = itemName.length() - 1;
while (index >= 0)
{
if (itemName.charAt(index) < '0' || itemName.charAt(index) > '9')
{
index++;
break;
}
index--;
}
final String pieceName = itemName.substring(0,index);
String pieceOwner = String.valueOf(Constants.UNDEFINED);
if (index < itemName.length())
pieceOwner = itemName.substring(index);
return new String[] {pieceName, pieceOwner};
}
//-------------------------------------------------------------------------
/**
* @param siteText
* @param type
* @return A location in text form.
*/
public static String getLocationName(final String siteText, final SiteType type)
{
return type.name() + " " + siteText;
}
//-------------------------------------------------------------------------
/**
* @param role
* @param isNewSentence
* @return RoleType in text form.
*/
public static String RoleTypeAsText(final RoleType role, final boolean isNewSentence)
{
switch(role) {
case P1:
case P2:
case P3:
case P4:
case P5:
case P6:
case P7:
case P8:
case P9:
case P10:
case P11:
case P12:
case P13:
case P14:
case P15:
case P16:
return (isNewSentence ? "Player" : "player") + " " + NumberAsText(role.owner());
case Mover:
return (isNewSentence ? "The" : "the") + " moving player";
case Next:
return (isNewSentence ? "The" : "the") + " next player";
case Neutral:
return (isNewSentence ? "No" : "no") + " player";
default:
return role.name();
}
}
//-------------------------------------------------------------------------
/**
* @param number
* @return Integer in text form.
*/
public static String NumberAsText(final int number)
{
return NumberAsText(number, null, null);
}
/**
* @param originalNumber
* @param suffixSingular
* @param suffixPlural
* @return Integer in text form.
*/
public static String NumberAsText(final int originalNumber, final String suffixSingular, final String suffixPlural)
{
int number = originalNumber;
if(number < -999 || number > 999)
throw new IllegalArgumentException("This function is not implemented for numbers at this range yet! [" + number + "]");
String text = "";
if(number < 0) {
text += "minus ";
number *= -1;
}
if(number == 0) {
text += "zero";
} else if(number == 1) {
text += "one";
} else if(number == 2) {
text += "two";
} else if(number == 3) {
text += "three";
} else if(number == 4) {
text += "four";
} else if(number == 5) {
text += "five";
} else if(number == 6) {
text += "six";
} else if(number == 7) {
text += "seven";
} else if(number == 8) {
text += "eight";
} else if(number == 9) {
text += "nine";
} else if(number == 10) {
text += "ten";
} else if(number == 11) {
text += "eleven";
} else if(number == 12) {
text += "twelve";
} else if(number == 13) {
text += "thirteen";
} else if(number == 15) {
text += "fifteen";
} else if(number == 18) {
text += "eighteen";
} else if(number > 10 && number < 20) {
text += NumberAsText(number % 10) + "teen";
} else if(number == 20) {
text += "twenty";
} else if(number == 30) {
text += "thirty";
} else if(number == 40) {
text += "forty";
} else if(number == 50) {
text += "fifty";
} else if(number == 60) {
text += "sixty";
} else if(number == 70) {
text += "seventy";
} else if(number == 80) {
text += "eighty";
} else if(number == 90) {
text += "ninety";
} else if(number >= 100) {
text += NumberAsText(number / 100) + " hundred";
if(number % 100 > 0)
text += " and " + NumberAsText(number % 100);
} else if(number > 20 && number < 100) {
text += NumberAsText(number / 10 * 10) + "-" + NumberAsText(number % 10);
} else {
throw new IllegalArgumentException("Unknown number recognized! [" + number + "]");
}
if(number == 1) {
if(suffixSingular != null)
text += " " + suffixSingular;
} else {
if(suffixPlural != null)
text += " " + suffixPlural;
}
return text;
}
//-------------------------------------------------------------------------
/**
* @param index
* @return Index in text form.
*/
public static String IndexAsText(final int index)
{
if(index < 0 || index > 999)
throw new IllegalArgumentException("This function is not implemented for indices at this range yet! [" + index + "]");
String text = "";
if(index == 0) {
text += "zeroth";
} if(index == 1) {
text += "first";
} else if(index == 2) {
text += "second";
} else if(index == 3) {
text += "third";
} else if(index == 4) {
text += "fourth";
} else if(index == 5) {
text += "fifth";
} else if(index == 6) {
text += "sixth";
} else if(index == 7) {
text += "seventh";
} else if(index == 8) {
text += "eighth";
} else if(index == 9) {
text += "ninth";
} else if(index == 10) {
text += "tenth";
} else if(index == 11) {
text += "eleventh";
} else if(index == 12) {
text += "twelfth";
} else if(index >= 13 && index <= 19) {
text += NumberAsText(index) + "th";
} else if(index == 20) {
text += "twentieth";
} else if(index == 30) {
text += "thirtieth";
} else if(index == 40) {
text += "fortieth";
} else if(index == 50) {
text += "fiftieth";
} else if(index == 60) {
text += "sixtieth";
} else if(index == 70) {
text += "seventieth";
} else if(index == 80) {
text += "eightieth";
} else if(index == 90) {
text += "ninetieth";
} else if(index >= 100) {
final int h = index / 100;
final int d = index - h * 100;
if(h > 1)
text += NumberAsText(h);
text += " hundred" + (d == 0 ? "th" : "");
if(d > 0)
text += " and " + IndexAsText(d);
} else if(index > 20 && index < 100) {
text += NumberAsText(index / 10 * 10) + "-" + IndexAsText(index % 10);
} else {
throw new IllegalArgumentException("Unknown index recognized! [" + index + "]");
}
return text;
}
//-------------------------------------------------------------------------
// /**
// * @param basisType
// * @return Board's BasisType in text form.
// */
// public static String ConvertBoardNameToText(final BasisType basisType)
// {
// if (basisType == null)
// return "";
//
// switch (basisType) {
// case NoBasis:
// return "";
// case Square:
// return "square";
// case T33336:
// return "semi-regular tiling made up of hexagons surrounded by triangles";
// case T33344:
// return "semi-regular tiling made up of alternating rows of squares and triangles";
// case T33434:
// return "semi-regular tiling made up of squares and pairs of triangles";
// case T3464:
// return "rhombitrihexahedral";
// case T3636:
// return "semi-regular tiling 3.6.3.6 made up of hexagons with interstitial triangles";
// case T4612:
// return "semi-regular tiling made up of squares, hexagons and dodecagons";
// case T488:
// return "semi-regular tiling 4.8.8. made up of octagons with interstitial squares";
// case T31212:
// return "semi-regular tiling made up of triangles and dodecagons";
// case T333333_33434:
// return "tiling 3.3.3.3.3.3,3.3.4.3.4";
// default:
// return basisType.name().toLowerCase();
// }
// }
//-------------------------------------------------------------------------
/**
* @param direction
* @return Direction in text form.
*/
public static String GetDirection(final String direction)
{
switch (direction) {
case "N":
return "north";
case "S":
return "south";
case "E":
return "east";
case "W":
return "west";
case "FL":
return "forward-left";
case "FLL":
return "forward-left-left";
case "FLLL":
return "forward-left-left-left";
case "BL":
return "backward-left";
case "BLL":
return "backward-left-left";
case "BLLL":
return "backward-left-left-left";
case "FR":
return "forward-right";
case "FRR":
return "forward-right-right";
case "FRRR":
return "forward-right-right-right";
case "BR":
return "backward-right";
case "BRR":
return "backward-right-right";
case "BRRR":
return "backward-right-right-right";
default:
return LanguageUtils.splitCamelCase(direction);
}
}
//-------------------------------------------------------------------------
/**
* @param string
* @return the camel case string split into separate words
*/
public final static String splitCamelCase(final String string)
{
final List<String> splitClassName = new ArrayList<String>();
for (final String w : string.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"))
splitClassName.add(w);
return String.join(" ", splitClassName).toLowerCase();
}
//-------------------------------------------------------------------------
} | 9,307 | 24.088949 | 122 | java |
Ludii | Ludii-master/Core/src/other/trial/AuxilTrialData.java | package other.trial;
import java.util.ArrayList;
import java.util.List;
import game.rules.play.moves.Moves;
import gnu.trove.list.array.TIntArrayList;
import other.context.Context;
import other.move.Move;
import other.state.State;
/**
* Wrapper class for auxiliary data for Trials, which we usually do not want to keep track of
* but sometimes do (usually for unit testing purposes).
*
* @author Dennis Soemers
*/
public class AuxilTrialData
{
//-------------------------------------------------------------------------
/**
* If true, we'll also store a history of states (in addition to actions).
*
* NOTE: Currently we do not copy this flag when copying Trials using the copy
* constructor. We assume this flag is only used when we want to store logs of
* played games into files. If, in the future, we ever get any game rules that
* depend on this flag, we'll also want to make sure to copy it in the copy
* constructor (because it will become important for copied Trials in MCTS
* simulations for example)
*/
protected transient boolean storeStates = false;
/**
* If true, we'll also store a history of the legal moves in every encountered
* game state.
*
* NOTE: same note as above.
*/
protected transient boolean storeLegalMovesHistory = false;
/**
* If true, we'll also store a history of sizes of legal moves lists in every
* encountered game state.
*
* NOTE: same note as above.
*/
protected transient boolean storeLegalMovesHistorySizes = false;
/** History of states */
protected List<State> states = null;
/** History of legal moves per game state */
protected List<List<Move>> legalMovesHistory = null;
/** History of sizes of legal moves lists per game state */
protected TIntArrayList legalMovesHistorySizes = null;
//-------------------------------------------------------------------------
/**
* @return History of all states. Will often be null (only not null if we
* explicitly require Trial to store states).
*/
public List<State> stateHistory()
{
return states;
}
/**
* Tells this Trial that it can save the current state (if it wants to).
*
* @param state
*/
public void saveState(final State state)
{
if (storeStates)
{
states.add(new State(state));
}
}
/**
* Tells this trial that it should store a history of all states.
*/
public void storeStates()
{
if (!storeStates)
{
storeStates = true;
states = new ArrayList<>();
}
}
/**
* Tells this trial that it should store the list of legal moves
* for every game state encountered.
*/
public void storeLegalMovesHistory()
{
if (!storeLegalMovesHistory)
{
storeLegalMovesHistory = true;
legalMovesHistory = new ArrayList<>();
}
}
/**
* Tells this trial that it should store the sizes of lists
* of legal moves for every game state encountered.
*/
public void storeLegalMovesHistorySizes()
{
if (!storeLegalMovesHistorySizes)
{
storeLegalMovesHistorySizes = true;
legalMovesHistorySizes = new TIntArrayList();
}
}
/**
* Set the legal moves history (used when deserializing a trial)
* @param legalMovesHistory
*/
public void setLegalMovesHistory(final List<List<Move>> legalMovesHistory)
{
this.legalMovesHistory = legalMovesHistory;
}
/**
* Sets the history of legal moves list sizes (used when deserializing a trial)
* @param legalMovesHistorySizes
*/
public void setLegalMovesHistorySizes(final TIntArrayList legalMovesHistorySizes)
{
this.legalMovesHistorySizes = legalMovesHistorySizes;
}
/**
* @return History of legal moves in all traversed states
*/
public List<List<Move>> legalMovesHistory()
{
return legalMovesHistory;
}
/**
* @return History of sizes of legal moves lists in all traversed states
*/
public TIntArrayList legalMovesHistorySizes()
{
return legalMovesHistorySizes;
}
//-------------------------------------------------------------------------
/**
* Clears all stored data
*/
public void clear()
{
if (states != null)
states.clear();
if (legalMovesHistory != null)
legalMovesHistory.clear();
if (legalMovesHistorySizes != null)
legalMovesHistorySizes.clear();
}
/**
* Update this auxiliary data based on a newly-computed list of legal moves
* @param legalMoves New list of legal moves
* @param context
*/
public void updateNewLegalMoves(final Moves legalMoves, final Context context)
{
final Trial trial = context.trial();
if (storeLegalMovesHistory)
{
if (legalMovesHistory.size() == (trial.numMoves() - trial.numInitialPlacementMoves()) + 1)
{
// We probably previous called this from a (stalemated Next) End rule,
// need to correct for that
legalMovesHistory.remove(legalMovesHistory.size() - 1);
}
if (legalMovesHistory.size() == trial.numMoves() - trial.numInitialPlacementMoves())
{
final List<Move> historyList = new ArrayList<>();
for (final Move move : legalMoves.moves())
{
final Move moveToAdd = new Move(move.getActionsWithConsequences(context));
moveToAdd.setFromNonDecision(move.fromNonDecision());
moveToAdd.setToNonDecision(move.toNonDecision());
moveToAdd.setMover(move.mover());
historyList.add(moveToAdd);
}
legalMovesHistory.add(historyList);
}
}
if (storeLegalMovesHistorySizes)
{
if (legalMovesHistorySizes.size() == (trial.numMoves() - trial.numInitialPlacementMoves()) + 1)
{
// We probably previous called this from a (stalemated Next) End rule,
// need to correct for that
legalMovesHistorySizes.removeAt(legalMovesHistorySizes.size() - 1);
}
if (legalMovesHistorySizes.size() == trial.numMoves() - trial.numInitialPlacementMoves())
{
legalMovesHistorySizes.add(legalMoves.moves().size());
}
}
}
/**
* Update auxiliary data based on a given subtrial
* @param subtrial
*/
public void updateFromSubtrial(final Trial subtrial)
{
if (storeLegalMovesHistory)
{
for (final List<Move> movesList : subtrial.auxilTrialData().legalMovesHistory())
{
legalMovesHistory.add(new ArrayList<Move>(movesList));
}
}
if (storeLegalMovesHistorySizes)
legalMovesHistorySizes.addAll(subtrial.auxilTrialData().legalMovesHistorySizes());
}
//-------------------------------------------------------------------------
}
| 6,379 | 25.255144 | 98 | java |
Ludii | Ludii-master/Core/src/other/trial/MatchTrial.java | package other.trial;
import java.util.ArrayList;
import java.util.List;
//-----------------------------------------------------------------------------
/**
* Record of a complete match.
*
* @author cambolbro
*/
public final class MatchTrial
{
/** List of instances making up this match. */
protected final List<Trial> trials = new ArrayList<Trial>();
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param trial
*/
public MatchTrial(final Trial trial)
{
trials.add(trial);
}
//-------------------------------------------------------------------------
/**
* @return List of instances.
*/
public List<Trial> trials()
{
return trials;
}
//-------------------------------------------------------------------------
/**
* Clear this match.
*/
public void clear()
{
trials.clear();
}
//-------------------------------------------------------------------------
/**
* @return Current episode being played.
*/
public Trial currentTrial()
{
return trials.isEmpty() ? null : trials.get(trials.size() - 1);
}
//-------------------------------------------------------------------------
}
| 1,195 | 17.984127 | 79 | java |
Ludii | Ludii-master/Core/src/other/trial/TempTrial.java | package other.trial;
import other.move.MoveSequence;
/**
* A temporary version of a Trial. Can only be constructed by "copying" another
* trial. Contains optimisations that may make it invalid for long-term use,
* only intended to be used shortly and temporarily after creation. Changes to
* the source-Trial may also seep through into this temp Trial, making it
* potentially invalid.
*
* @author Dennis Soemers
*/
public final class TempTrial extends Trial
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
/**
*
* @param other
*/
public TempTrial(final Trial other)
{
super(other);
}
//-------------------------------------------------------------------------
@Override
protected MoveSequence copyMoveSequence(final MoveSequence otherSequence)
{
return new MoveSequence(otherSequence, true);
}
//-------------------------------------------------------------------------
}
| 1,006 | 22.97619 | 79 | java |
Ludii | Ludii-master/Core/src/other/trial/Trial.java | package other.trial;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.rng.RandomProviderState;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import game.Game;
import game.rules.meta.no.repeat.NoRepeat;
import game.rules.meta.no.simple.NoSuicide;
import game.rules.play.moves.BaseMoves;
import game.rules.play.moves.Moves;
import game.util.equipment.Region;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.list.array.TLongArrayList;
import main.Constants;
import main.Status;
import main.collections.FastArrayList;
import main.collections.FastTLongArrayList;
import other.UndoData;
import other.context.Context;
import other.context.TempContext;
import other.move.Move;
import other.move.MoveSequence;
import other.state.State;
/**
* Instance of a played game, consisting of states and turns that led to them.
*
* @author cambolbro and Dennis Soemers and Eric Piette
*/
public class Trial implements Serializable
{
private static final long serialVersionUID = 1L;
//-----------------------------------------------------------------------------
/** Moves made during the Trial (one less than number of states encountered). */
private MoveSequence moves;
/** Number of initial placement moves before player decision moves. */
private int numInitialPlacementMoves = 0;
/** The starting positions of each component. */
private List<Region> startingPos;
/** Result of game (null if game is still in progress). */
protected Status status = null;
/** Legal moves for next player. Typically generated the move before and cached. */
protected Moves legalMoves;
/** All the previous states of the game. TODO make this a TLongHashSet? */
private FastTLongArrayList previousStates;
/** All the previous state within a turn. TODO make this a TLongHashSet? */
private FastTLongArrayList previousStatesWithinATurn;
/**
* Number of sub-moves played in this trial. Only valid for simultaneous-move
* games. Only Used by the networking
*/
private int numSubmovesPlayed = 0;
/** Ranking of the players. */
private double[] ranking;
//-------------------------------------------------------------------------
/**
* Auxiliary trial data
*
* NOTE: Currently we do not copy this flag when copying Trials using the copy
* constructor. We assume this flag is only used when we want to store logs of
* played games into files. If, in the future, we ever get any game rules that
* depend on this flag, we'll also want to make sure to copy it in the copy
* constructor (because it will become important for copied Trials in MCTS
* simulations for example)
*/
protected transient AuxilTrialData auxilTrialData = null;
//------------------------------Data used to undo--------------------------------
/**
* The list of all the end data in each previous state from the initial state.
*/
private List<UndoData> endData = null;
/**
* The list of all the RNG states at each state.
*/
private List<RandomProviderState> RNGStates = null;
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param game The game.
*/
public Trial(final Game game)
{
if (game.hasSubgames())
{
// This is a Trial for a Match; we need almost no data here
startingPos = null;
legalMoves = null;
previousStates = null;
previousStatesWithinATurn = null;
}
else
{
// This is a Trial for just a single Game
startingPos = new ArrayList<Region>();
legalMoves = new BaseMoves(null);
previousStates = new FastTLongArrayList();
previousStatesWithinATurn = new FastTLongArrayList();
}
moves = new MoveSequence(null);
ranking = new double[game.players().count() + 1];
endData = new ArrayList<UndoData>();
RNGStates = new ArrayList<RandomProviderState>();
}
/**
* Copy constructor.
*
* @param other The trial to copy.
*/
public Trial(final Trial other)
{
moves = copyMoveSequence(other.moves);
numInitialPlacementMoves = other.numInitialPlacementMoves;
startingPos = other.startingPos == null ? null : new ArrayList<Region>(other.startingPos);
// NOTE: multiple Trials sharing same Status here. Usually fine
// because null if not terminal
status = other.status();
// Just copying reference here intentional!
legalMoves = other.legalMoves;
if (other.previousStates != null)
previousStates = new FastTLongArrayList(other.previousStates);
if (other.previousStatesWithinATurn != null)
previousStatesWithinATurn = new FastTLongArrayList(other.previousStatesWithinATurn);
numSubmovesPlayed = other.numSubmovesPlayed;
ranking = Arrays.copyOf(other.ranking, other.ranking.length);
if (other.endData != null)
{
endData = new ArrayList<UndoData>(other.endData);
RNGStates = new ArrayList<RandomProviderState>(other.RNGStates);
}
}
/**
* Method used to set the trial to another trial.
* @param trial The trial to reset to.
*/
public void resetToTrial(final Trial trial)
{
moves = copyMoveSequence(trial.moves);
numInitialPlacementMoves = trial.numInitialPlacementMoves;
startingPos = trial.startingPos == null ? null : new ArrayList<Region>(trial.startingPos);
// NOTE: multiple Trials sharing same Status here. Usually fine
// because null if not terminal
status = trial.status();
// Just copying reference here intentional!
legalMoves = trial.legalMoves;
if (trial.previousStates != null)
previousStates = new FastTLongArrayList(trial.previousStates);
if (trial.previousStatesWithinATurn != null)
previousStatesWithinATurn = new FastTLongArrayList(trial.previousStatesWithinATurn);
numSubmovesPlayed = trial.numSubmovesPlayed;
ranking = Arrays.copyOf(trial.ranking, trial.ranking.length);
endData = new ArrayList<UndoData>(trial.endData);
RNGStates = new ArrayList<RandomProviderState>(trial.RNGStates);
}
//-------------------------------------------------------------------------
/**
* Method for copying MoveSequence. NOTE: we override this in TempTrial
* for copying MoveSequences that are allowed to be invalidated.
*
* @param otherState
* @return Copy of given game state.
*/
@SuppressWarnings("static-method")
protected MoveSequence copyMoveSequence(final MoveSequence otherSequence)
{
return new MoveSequence(otherSequence);
}
/**
* @return Auxiliary trial data. Will often be null (only not null if we
* explicitly require Trial to keep track of some auxiliary data).
*/
public AuxilTrialData auxilTrialData()
{
return auxilTrialData;
}
/**
* @param move Action to be added to the history of played actions.
*/
public void addMove(final Move move)
{
moves = moves.add(move);
}
/**
* To remove the last action from the history of played actions.
* @return The action removed.
*/
public Move removeLastMove()
{
return moves.removeLastMove();
}
/**
* @param idx
* @return Move at given index
*/
public Move getMove(final int idx)
{
return moves.getMove(idx);
}
/**
* Replaces the last move in the sequence with the given new move
* @param move
*/
public void replaceLastMove(final Move move)
{
moves.replaceLastMove(move);
}
/**
* @return Result of game (null if game is still in progress).
*/
public Status status()
{
return status;
}
/**
* @param res
*/
public void setStatus(final Status res)
{
status = res;
}
/**
* @return Cached legal moves
*/
public Moves cachedLegalMoves()
{
if (over())
return new BaseMoves(null);
return legalMoves;
}
/**
* Sets the cached legal moves
* @param legalMoves
* @param context
*/
public void setLegalMoves(final Moves legalMoves, final Context context)
{
// Remove moves that don't satisfy meta rules
for (int i = 0; i < legalMoves.moves().size(); i++)
{
final Move m = legalMoves.moves().get(i);
if (!NoRepeat.apply(context, m) || !NoSuicide.apply(context, m))
legalMoves.moves().removeSwap(i--);
}
if (!over())
{
// Ensure that we have at least one legal move
if (context.game().isAlternatingMoveGame())
{
if (legalMoves.moves().isEmpty())
legalMoves.moves().add(Game.createPassMove(context,true));
}
// NOTE: case for simultaneous-move games not handled here, but already
// prior to state repetition checks in Game.moves(). State repetitions
// in simultaneous-move games are a mess...
}
this.legalMoves = legalMoves;
if (auxilTrialData != null)
auxilTrialData.updateNewLegalMoves(legalMoves, context);
}
//-------------------------------------------------------------------------
/**
* @return Whether game is over.
*/
public boolean over()
{
return status != null;
}
/**
* @return Number of setup moves
*/
public int numInitialPlacementMoves()
{
return numInitialPlacementMoves;
}
/**
* To set the number of start place rules.
*
* @param numInitialPlacementMoves
*/
public void setNumInitialPlacementMoves(final int numInitialPlacementMoves)
{
this.numInitialPlacementMoves = numInitialPlacementMoves;
}
//-------------------------------------------------------------------------
/**
* Clears cached list of legal moves (NOTE: not really clearing, actually
* it instantiates a new empty list)
*/
public void clearLegalMoves()
{
legalMoves = new BaseMoves(null);
}
/**
* Generates a complete list of all the moves
* @return Complete list of moves
*/
public List<Move> generateCompleteMovesList()
{
return moves.generateCompleteMovesList();
}
/**
* Generates a complete list of all the real moves that were made
* @return Complete list of real moves
*/
public List<Move> generateRealMovesList()
{
final List<Move> realMoves = new ArrayList<>();
for (int i = numInitialPlacementMoves(); i < numMoves(); i++)
realMoves.add(moves.getMove(i));
return realMoves;
}
/**
* @return An iterator that iterates through all the moves in reverse order
*/
public Iterator<Move> reverseMoveIterator()
{
return moves.reverseMoveIterator();
}
/**
* Reset this trial ready to play again.
*
* @param game
*/
public void reset(final Game game)
{
moves = new MoveSequence(null);
numInitialPlacementMoves = 0;
if (startingPos != null)
startingPos.clear();
status = null;
if (legalMoves != null)
clearLegalMoves();
if (previousStates != null)
previousStates.clear();
if (previousStatesWithinATurn != null)
previousStatesWithinATurn.clear();
numSubmovesPlayed = 0;
if (auxilTrialData != null)
auxilTrialData.clear();
Arrays.fill(ranking, 0.0);
}
//-------------------------------------------------------------------------
/**
* @return Last move. Null if there is no last move.
*/
public Move lastMove()
{
return moves.lastMove();
}
/**
* @param pid The index of the player.
* @return Last move of a specific player.
*/
public Move lastMove(final int pid)
{
return moves.lastMove(pid);
}
/**
* @param moverId the id of the mover.
* @return The index of the mover in the last turn.
*/
public int lastTurnMover(final int moverId)
{
final Iterator<Move> movesIterated = moves.reverseMoveIterator();
while (movesIterated.hasNext())
{
final int idPlayer = movesIterated.next().mover();
if (idPlayer != moverId)
return idPlayer;
}
return Constants.UNDEFINED;
}
/**
* @return Number of move played so far.
*/
public int numMoves()
{
return moves.size();
}
/**
* @return Number of forced passes played so far.
*/
public int numForcedPasses()
{
int count = 0;
for(int index = numInitPlacement(); index < moves.size(); index++)
{
final Move m = moves.getMove(index);
if(m.isForced())
count++;
}
return count;
}
/**
* @param game The game to replay.
* @return Number of times throughout a trial that the mover must choose from two or more legal moves.
*/
public int numLogicalDecisions(final Game game)
{
final Context context = new Context(game,new Trial(game));
context.game().start(context);
int count = 0;
for(int index = context.trial().numInitialPlacementMoves(); index < moves.size(); index++)
{
final Move m = moves.getMove(index);
if(context.game().moves(context).moves().size() >= 2)
count++;
context.game().apply(context, m);
}
return count;
}
/**
* @param game The game to replay.
* @return Number of times throughout a trial that the mover must choose from two or more plausible moves (i.e. legal moves that do not immediately lose the game or give the next player a winning reply -- need two ply search to detect this).
*/
public int numPlausibleDecisions(final Game game)
{
final Context context = new Context(game,new Trial(game));
context.game().start(context);
int count = 0;
for(int index = context.trial().numInitialPlacementMoves(); index < moves.size(); index++)
{
final int mover = context.state().mover();
final int next = context.state().next();
final Move m = moves.getMove(index);
final FastArrayList<Move> newLegalMoves = context.game().moves(context).moves();
int counterPlausibleMove = 0;
for(final Move legalMove : newLegalMoves)
{
final Context newContext = new TempContext(context);
newContext.game().apply(newContext, legalMove);
final boolean moverLoss = !newContext.active(mover) && !newContext.winners().contains(mover);
final boolean nextPlayerWin = next != mover && !newContext.active(next) && newContext.winners().contains(next);
if(!moverLoss && !nextPlayerWin)
counterPlausibleMove++;
if(counterPlausibleMove >= 2)
{
count++;
break;
}
}
context.game().apply(context, m);
}
return count;
}
/**
* @return The number of the init placement.
*/
public int numInitPlacement()
{
return numInitialPlacementMoves;
}
/**
* To add another init Placement.
*/
public void addInitPlacement()
{
numInitialPlacementMoves++;
}
/**
* @return Array of ranks (one rank per player, indexing starts at 1). Best rank is 1.0,
* higher values are worse.
*/
public double[] ranking()
{
return ranking;
}
//-------------------------------------------------------------------------
/**
* Tells this Trial that it can save the current state (if it wants to).
*
* @param state
*/
public void saveState(final State state)
{
if (auxilTrialData != null)
auxilTrialData.saveState(state);
}
/**
* Tells this trial that it should store a history of all states.
*/
public void storeStates()
{
if (auxilTrialData == null)
auxilTrialData = new AuxilTrialData();
auxilTrialData.storeStates();
}
/**
* Tells this trial that it should store the list of legal moves
* for every game state encountered.
*/
public void storeLegalMovesHistory()
{
if (auxilTrialData == null)
auxilTrialData = new AuxilTrialData();
auxilTrialData.storeLegalMovesHistory();
}
/**
* Tells this trial that it should store the sizes of lists
* of legal moves for every game state encountered.
*/
public void storeLegalMovesHistorySizes()
{
if (auxilTrialData == null)
auxilTrialData = new AuxilTrialData();
auxilTrialData.storeLegalMovesHistorySizes();
}
/**
* Set the legal moves history (used when deserializing a trial)
* @param legalMovesHistory
*/
public void setLegalMovesHistory(final List<List<Move>> legalMovesHistory)
{
if (auxilTrialData == null)
auxilTrialData = new AuxilTrialData();
auxilTrialData.setLegalMovesHistory(legalMovesHistory);
}
/**
* Sets the history of legal moves list sizes (used when deserializing a trial)
* @param legalMovesHistorySizes
*/
public void setLegalMovesHistorySizes(final TIntArrayList legalMovesHistorySizes)
{
if (auxilTrialData == null)
auxilTrialData = new AuxilTrialData();
auxilTrialData.setLegalMovesHistorySizes(legalMovesHistorySizes);
}
/**
* @return Number of sub-moves played in this trial. Only valid for simultaneous-move games
*/
public int numSubmovesPlayed()
{
return numSubmovesPlayed;
}
/**
* Sets the number of sub-moves played in this trial (for simultaneous-move games)
* @param numSubmovesPlayed
*/
public void setNumSubmovesPlayed(final int numSubmovesPlayed)
{
this.numSubmovesPlayed = numSubmovesPlayed;
}
//-------------------------------------------------------------------------
/**
* @return The number of the move.
*/
public int moveNumber()
{
return numMoves() - numInitPlacement();
}
//-------------------------------------------------------------------------
/**
* Saves this trial to the given file (in binary format)
* @param file
* @param gameName
* @param gameStartRngState Internal state of Context's RNG before start of game
* @throws IOException
*/
public void saveTrialToFile
(
final File file,
final String gameName,
final RandomProviderDefaultState gameStartRngState
) throws IOException
{
if (file != null)
{
file.getParentFile().mkdirs();
if (!file.exists())
file.createNewFile();
try
(
final ObjectOutputStream out =
new ObjectOutputStream
(
new BufferedOutputStream
(
new FileOutputStream(file.getAbsoluteFile())
)
)
)
{
out.writeUTF(gameName);
out.writeInt(gameStartRngState.getState().length);
out.write(gameStartRngState.getState());
//System.out.println("wrote RNG state: " + Arrays.toString(currGameStartRngState.getState()));
out.writeObject(this);
out.reset();
out.flush();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
}
/**
* Just calls the method below
*
* @param file
* @param gameName
* @param gameOptions
* @param gameStartRngState
* @throws IOException
*/
public void saveTrialToTextFile
(
final File file,
final String gameName,
final List<String> gameOptions,
final RandomProviderDefaultState gameStartRngState
) throws IOException
{
saveTrialToTextFile(file, gameName, gameOptions, gameStartRngState, false);
}
/**
* Saves this trial to the given file (in text format)
* @param file
* @param gameName
* @param gameStartRngState
* @param gameOptions
* @param trialContainsSandbox
* @throws IOException
*/
public void saveTrialToTextFile
(
final File file,
final String gameName,
final List<String> gameOptions,
final RandomProviderDefaultState gameStartRngState,
final boolean trialContainsSandbox
) throws IOException
{
if (file != null)
{
file.getParentFile().mkdirs();
if (!file.exists())
file.createNewFile();
try (final PrintWriter writer = new PrintWriter(file))
{
writer.print(convertTrialToString(gameName, gameOptions, gameStartRngState));
writer.println("SANDBOX=" + trialContainsSandbox);
writer.println("LUDII_VERSION=" + Constants.LUDEME_VERSION);
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
}
/**
* Saves this trial to the given file (in text format)
* @param gameName
* @param gameOptions
* @param gameStartRngState
* @throws IOException
* @return String representation of Trial
*/
public String convertTrialToString
(
final String gameName,
final List<String> gameOptions,
final RandomProviderDefaultState gameStartRngState
) throws IOException
{
final StringBuilder sb = new StringBuilder();
// if (getTrials().size() > 0)
// {
// TODO saving all sub-trials of a match in a single file
// A match trial with multiple instance trials
// for (int i = 0; i < getTrials().size(); i++)
// {
// final String trialString = getTrial(i).convertTrialToString(gameName, gameOptions, gameStartRngState);
// final String[] splitTrialString = trialString.split("\n");
//
// if (i == 0)
// {
// for (final String s : splitTrialString)
// {
// if
// (
// s.substring(0, 4).equals("Move") ||
// s.substring(0, 4).equals("game") ||
// s.substring(0, 3).equals("RNG")
// )
// {
// sb.append(s + "\n");
// }
// }
// }
// else
// {
// for (final String s : splitTrialString)
// {
// if
// (
// s.substring(0, 4).equals("Move") ||
// (i == getTrials().size() - 1 && s.substring(0, 8).equals("rankings"))
// )
// {
// sb.append(s + "\n");
// }
// }
// }
// }
// }
// else
// {
// Just a normal trial
if (gameName != null)
sb.append("game=" + gameName + "\n");
if (gameOptions != null)
{
sb.append("START GAME OPTIONS\n");
for (final String option : gameOptions)
{
sb.append(option + "\n");
}
sb.append("END GAME OPTIONS\n");
}
if (gameStartRngState != null)
{
sb.append("RNG internal state=");
final byte[] bytes = gameStartRngState.getState();
for (int i = 0; i < bytes.length; ++i)
{
sb.append(bytes[i]);
if (i < bytes.length - 1)
sb.append(",");
}
sb.append("\n");
}
final List<Move> movesList = moves.generateCompleteMovesList();
for (int i = 0; i < movesList.size(); ++i)
{
sb.append("Move=" + movesList.get(i).toTrialFormat(null) + "\n");
}
if (auxilTrialData != null)
{
if (auxilTrialData.storeLegalMovesHistorySizes)
{
for (int i = 0; i < auxilTrialData.legalMovesHistorySizes.size(); ++i)
{
sb.append("LEGAL MOVES LIST SIZE = " + auxilTrialData.legalMovesHistorySizes.getQuick(i) + "\n");
}
}
if (auxilTrialData.storeLegalMovesHistory)
{
for (final List<Move> legal : auxilTrialData.legalMovesHistory)
{
sb.append("NEW LEGAL MOVES LIST" + "\n");
for (int i = 0; i < legal.size(); ++i)
sb.append(legal.get(i).toTrialFormat(null) + "\n");
sb.append("END LEGAL MOVES LIST" + "\n");
}
}
}
sb.append("numInitialPlacementMoves=" + numInitialPlacementMoves + "\n");
if (status != null)
{
sb.append("winner=" + status.winner() + "\n");
sb.append("endtype=" + status.endType() + "\n");
}
if (ranking != null)
{
sb.append("rankings=");
for (int i = 0; i < ranking.length; ++i)
{
if (i > 0)
sb.append(",");
sb.append(ranking[i]);
}
sb.append("\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
try
{
str = convertTrialToString(null, null, null);
}
catch (final IOException e)
{
e.printStackTrace();
}
return str;
}
//-------------------------------------------------------------------------
/**
* @return Number of turns, i.e. mover changes, in this trial.
*/
public int numTurns()
{
int currentPlayerNumber = 0;
int numTurns = 0;
for (final Move m : moves.generateCompleteMovesList())
{
if (m.mover() != currentPlayerNumber)
{
currentPlayerNumber = m.mover();
numTurns++;
}
}
return numTurns;
}
//-------------------------------------------------------------------------
/**
* @return The previous state in case of no repetition rule.
*/
public TLongArrayList previousState()
{
return previousStates;
}
/**
* @return The previous state in the same turn.
*/
public TLongArrayList previousStateWithinATurn()
{
return previousStatesWithinATurn;
}
/**
* @param idComponent
* @return The starting positions of a component.
*/
public Region startingPos(final int idComponent)
{
return startingPos.get(idComponent);
}
/**
* @return The starting positions of all the components.
*/
public List<Region> startingPos()
{
return startingPos;
}
//-------------------------------------------------------------------------
/**
* @return The number of non-initial placement moves made in this trial.
*/
public int numberRealMoves()
{
return numMoves() - numInitialPlacementMoves();
}
//-----------------------Undo Data------------------------------------
/**
* @return The list of End Data.
*/
public List<UndoData> endData()
{
return endData;
}
/**
* To add an endData to the list.
* @param endDatum The end Data to add.
*/
public void addUndoData(final UndoData endDatum)
{
endData.add(endDatum);
}
/**
* To remove the last end data from the list.
*/
public void removeLastEndData()
{
endData.remove(endData.size()-1);
}
/**
* @return The list of RNG States.
*/
public List<RandomProviderState> RNGStates()
{
return RNGStates;
}
/**
* To add an RNGState to the list.
* @param RNGState The RNG state to add.
*/
public void addRNGState(final RandomProviderState RNGState)
{
RNGStates.add(RNGState);
}
/**
* To remove the last RNG state from the list.
*/
public void removeLastRNGStates()
{
RNGStates.remove(RNGStates.size()-1);
}
/**
* Sets any data only required for undo() operations to null
*/
public void nullUndoData()
{
endData = null;
RNGStates = null;
}
} | 25,337 | 23.017062 | 242 | java |
Ludii | Ludii-master/Core/src/other/uf/UnionFind.java | package other.uf;
import java.io.Serializable;
//-----------------------------------------------------------------------------
/**
* Main file to create Union tree
* (with one by one move in each of the game state)
*
* @author tahmina
*/
public class UnionFind implements Serializable
{
private static final long serialVersionUID = 1L;
/**
* Constructor.
*/
private UnionFind()
{
// Do nothing
}
// /**
// * @param context Present Context of the game board.
// * @param activeIsLoop loop information is required or not?.
// * @param dirnChoice The direction.
// * @param site The site.
// * @return ???
// */
// public static boolean eval
// (
// final Context context,
// final boolean activeIsLoop,
// final AbsoluteDirection dirnChoice,
// final int site
// )
// {
// final SiteType type;
//
// if (context.game().isEdgeGame()) type = SiteType.Edge;
// else if (context.game().isCellGame()) type = SiteType.Cell;
// else type = SiteType.Vertex;
//
// final int siteId = (site == Constants.UNDEFINED) ? context.trial().lastMove().toNonDecision() : site;
// final ContainerState state = context.state().containerStates()[0];
// final int whoSiteId = state.who(siteId, type);
// final int numPlayers = context.game().players().count();
//
// if (whoSiteId < 1 || whoSiteId > numPlayers + 1)
// {
// //System.out.println("** Bad who in UnionFind.eval(): " + whoSiteId);
// return false;
// }
//
// boolean ringflag = false;
// final TIntArrayList neighbourList = new TIntArrayList();
//
// final Topology topology = context.topology();
// final List<game.util.graph.Step> steps = topology.trajectories().steps(type, site, type, dirnChoice); // TODO shouldn't we use siteId here?
//
// for (final game.util.graph.Step step : steps)
// neighbourList.add(step.to().id());
//
// if (activeIsLoop)
// ringflag = new IsLoopAux(dirnChoice).eval(context);
//
// context.setRingFlagCalled(ringflag);
//
// union(siteId, state, state.unionInfo()[whoSiteId], whoSiteId, numPlayers, neighbourList, type);
// union(siteId, state, state.unionInfo()[numPlayers + 1], numPlayers + 1, numPlayers, neighbourList, type);
//
// return ringflag;
// }
//
// //-------------------------------------------------------------------------
//
// /**
// * @param siteId The last move of the game.
// * @param state Each state information.
// * @param uf The object of the union-find.
// * @param whoSiteId Player type of last move.
// * @param numPlayers The number of players.
// * @param neighbourList The adjacent list of our last movement.
// *
// * Remarks This function will not return any things.
// * It able to connect the last movement with the existing union-tree.
// * Basically, the rank base union-find is chosen in this implementation.
// * So, that the height of the union tree will be minimum.
// */
// private static void union
// (
// final int siteId,
// final ContainerState state,
// final UnionInfo uf,
// final int whoSiteId,
// final int numPlayers,
// final TIntArrayList neighbourList,
// final SiteType type
// )
// {
// final int numNeighbours = neighbourList.size();
//
// uf.setItem(siteId, siteId);
// uf.setParent(siteId, siteId);
//
// for (int i = 0; i < numNeighbours; i++)
// {
// final int ni = neighbourList.getQuick(i);
// boolean connect = true;
//
// if
// (
// ((whoSiteId == numPlayers + 1) && (state.who (ni, type) != 0)) ||
// ((whoSiteId != numPlayers + 1) && (state.who (ni, type) == whoSiteId))
// )
// {
// for (int j = i + 1; j < numNeighbours; j++)
// {
// final int nj = neighbourList.getQuick(j);
//
// if (connected(ni, nj, uf))
// {
// connect = false;
// break;
// }
// }
//
// if (connect)
// {
// final int rootP = find(ni, uf);
// final int rootQ = find(siteId, uf);
//
// if(rootP == rootQ)
// return;
//
// if (uf.getGroupSize(rootP) < uf.getGroupSize(rootQ))
// {
// uf.setParent(rootP, rootQ);
// uf.mergeItemsLists(rootQ, rootP);
// }
// else
// {
// uf.setParent(rootQ, rootP);
// uf.mergeItemsLists(rootP, rootQ);
// }
// }
// }
// }
// }
//
// //-------------------------------------------------------------------------
//
// /**
// *
// * @param position1 Integer position.
// * @param position2 Integer position.
// * @param uf Object of union-find.
// * @param whoSiteId The current player type.
// *
// * @return check Are the position1 and position1 in the same union tree or not?
// */
// private static boolean connected(final int position1, final int position2, final UnionInfo uf)
// {
// final int root1 = find(position1, uf);
// return uf.isSameGroup(root1, position2);
// }
//
// /**
// *
// * @param position A cell number.
// * @param uf Object of union-find.
// * @param whoSiteId The current player type.
// *
// * @return The root of the position.
// */
// private static int find(final int position, final UnionInfo uf)
// {
// final int parent = uf.getParent(position);
//
// if (parent == position)
// return position;
// else
// return find(uf.getParent(parent), uf);
// }
}
| 5,416 | 27.81383 | 144 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.