repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
Ludii
Ludii-master/Core/src/game/match/Games.java
package game.match; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import annotations.Or; import other.BaseLudeme; /** * Defines the games used in a match. * * @author Eric.Piette */ public class Games extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * The games used in the match. */ final List<Subgame> games; //------------------------------------------------------------------------- /** * @param game The game that makes up the subgames of the match. * @param games The games that make up the subgames of the match. * * @example (games { (subgame "Tic-Tac-Toe" next:1) (subgame "Yavalath" next:2) * (subgame "Breakthrough" next:0) }) */ public Games ( @Or final Subgame game, @Or final Subgame[] games ) { int numNonNull = 0; if (game != null) numNonNull++; if (games != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException("Exactly one Or parameter must be non-null."); if (game != null) { this.games = new ArrayList<Subgame>(); this.games.add(game); } else { if (games.length < 1) throw new IllegalArgumentException("A match needs at least one game."); this.games = new ArrayList<Subgame>(); for (final Subgame subGame : games) this.games.add(subGame); } } //------------------------------------------------------------------------- /** * @return the games. */ public List<Subgame> games() { return this.games; } //------------------------------------------------------------------------- }
1,708
20.632911
84
java
Ludii
Ludii-master/Core/src/game/match/Match.java
package game.match; import java.text.DecimalFormat; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import annotations.Hide; import annotations.Opt; 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.other.Dice; import game.players.Players; import game.rules.end.End; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import main.grammar.Description; import metadata.Metadata; import other.AI; import other.GameLoader; import other.action.others.ActionNextInstance; import other.concept.Concept; import other.concept.ConceptDataType; import other.context.Context; import other.move.Move; import other.playout.PlayoutMoveSelector; import other.topology.TopologyElement; import other.trial.Trial; /** * Defines a match made up of a series of subgames. * * @author Eric.Piette */ public class Match extends Game { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The end condition for the match. */ private End end; /** The difference possible instance for a match. */ protected Subgame[] instances; //------------------------------------------------------------------------- /** * @param name The name of the match. * @param players The players of the match [(players 2)]. * @param games The different subgames that make up the match. * @param end The end rules of the match. * * @example (match "Match" (players 2) (games { (subgame "Tic-Tac-Toe" next:1) * (subgame "Yavalath" next:2) (subgame "Breakthrough" next:0) } ) (end * { (if (and (= (count Trials) 3) (> (matchScore P1) (matchScore P2))) * (result P1 Win)) (if (and (= (count Trials) 3) (< (matchScore P1) * (matchScore P2))) (result P2 Win)) (if (and (= (count Trials) 3) (= * (matchScore P1) (matchScore P2))) (result P1 Draw)) }) ) */ public Match ( final String name, @Opt final Players players, final Games games, final End end ) { super(name, players, null, null, null); final List<Subgame> subgames = games.games(); this.instances = new Subgame[subgames.size()]; for (int i = 0; i < subgames.size(); i++) this.instances[i] = subgames.get(i); if (instances.length == 0) throw new IllegalArgumentException("A match needs at least one game."); stateReference = null; this.end = end; this.end.setMatch(true); } //------------------------------------------------------------------------- /** * @param name The name of the game. * @param gameDescription The description of the game. */ @Hide public Match(final String name, final Description gameDescription) { super(name, gameDescription); } //------------------------------------------------------------------------- @Override public Move apply(final Context context, final Move move, final boolean skipEndRules) { context.getLock().lock(); try { if (move.containsNextInstance()) { // We need to move on to next instance, so apply on match context instead of subcontext assert (context.subcontext().trial().over()); assert (move.actions().size() == 1 && move.actions().get(0) instanceof ActionNextInstance); context.currentInstanceContext().trial().addMove(move); context.trial().addMove(move); context.advanceInstance(); return move; } final Context subcontext = context.subcontext(); final Trial subtrial = subcontext.trial(); final int numMovesBeforeApply = subtrial.numMoves(); // First just apply the move on the subcontext final Move appliedMove = subcontext.game().apply(subcontext, move, skipEndRules); if (!skipEndRules) { // Will likely have to append some extra moves to the match-wide trial final List<Move> subtrialMoves = subtrial.generateCompleteMovesList(); final int numMovesAfterApply = subtrialMoves.size(); final int numMovesToAppend = numMovesAfterApply - numMovesBeforeApply; for (int i = 0; i < numMovesToAppend; ++i) context.trial().addMove(subtrialMoves.get(subtrialMoves.size() - 1 - i)); } return appliedMove; } finally { context.getLock().unlock(); } } @Override public Moves moves(final Context context) { context.getLock().lock(); try { final Context subcontext = context.subcontext(); final Moves moves; if (subcontext.trial().over()) { // Our only action will be to move on to next instance moves = new BaseMoves(null); if (context.trial().over()) return moves; // Full match is over final ActionNextInstance action = new ActionNextInstance(); action.setDecision(true); final Move move = new Move(action); move.setDecision(true); move.setMover(subcontext.state().mover()); moves.moves().add(move); } else { // Normal moves generation moves = subcontext.game().moves(subcontext); } if (context.trial().auxilTrialData() != null) context.trial().auxilTrialData().updateNewLegalMoves(moves, context); return moves; } finally { context.getLock().unlock(); } } //------------------------------------------------------------------------- @Override public void setMetadata(final Object md) { metadata = (Metadata)md; // We add the concepts of the metadata to the game. if (metadata != null) { final BitSet metadataConcept = metadata.concepts(this); booleanConcepts.or(metadata.concepts(this)); final boolean stackTypeUsed = booleanConcepts.get(Concept.StackType.id()); if (stackTypeUsed && !metadataConcept.get(Concept.Stack.id()) && booleanConcepts.get(Concept.StackState.id())) booleanConcepts.set(Concept.Stack.id(), false); } else { metadata = new Metadata(null, null, null, null); } } //------------------------------------------------------------------------- @Override public End endRules() { return end; } @Override public Subgame[] instances() { return instances; } //------------------------------------------------------------------------- @Override public boolean hasSubgames() { return true; } @Override public boolean hasCustomPlayouts() { for (final Subgame instance : instances) { if (instance.getGame().hasCustomPlayouts()) return true; } return false; } @Override public void disableMemorylessPlayouts() { for (final Subgame instance : instances) { instance.disableMemorylessPlayouts(); } } @Override public boolean usesNoRepeatPositionalInGame() { return false; } @Override public boolean usesNoRepeatPositionalInTurn() { return false; } @Override public boolean requiresScore() { return true; // Matches always have scores } @Override public boolean automove() { return false; // this flag should never be true for a Match } //------------------------------------------------------------------------- @Override public Board board() { // StringRoutines.stackTrace(); System.err.println("Match.board() always returns null! Should probably call context.board() instead."); return null; } @Override public Equipment equipment() { //StringRoutines.stackTrace(); System.err.println("Match.equipment() always returns null! Should probably call context.equipment() instead."); return null; } @Override public boolean hasSharedPlayer() { //StringRoutines.stackTrace(); System.err.println("Match.hasSharedPlayer() always returns false! Should probably call context.hasSharedPlayer() instead."); return false; } @Override public List<Dice> handDice() { //StringRoutines.stackTrace(); System.err.println("Match.handDice() always returns null! Should probably call context.handDice() instead."); return null; } @Override public int numContainers() { //StringRoutines.stackTrace(); System.err.println("Match.numContainers() always returns -1! Should probably call context.numContainers() instead."); return Constants.UNDEFINED; } @Override public int numComponents() { //StringRoutines.stackTrace(); System.err.println("Match.numComponents() always returns -1! Should probably call context.numComponents() instead."); return Constants.UNDEFINED; } //------------------------------------------------------------------------- @Override public void create() { if (finishedPreprocessing) System.err.println("Warning! Match.create() has already previously been called on " + name()); GameLoader.compileInstance(instances()[0]); finishedPreprocessing = true; booleanConcepts = computeBooleanConcepts(); conceptsNonBoolean = computeNonBooleanConcepts(); hasMissingRequirement = computeRequirementReport(); willCrash = computeCrashReport(); } @Override public void start(final Context context) { context.getLock().lock(); try { final Context subcontext = context.subcontext(); final Trial subtrial = subcontext.trial(); final int numMovesBeforeStart = subtrial.numMoves(); // Start the first instance instances()[0].getGame().start(subcontext); // Will maybe have to append some extra moves to the match-wide trial final List<Move> subtrialMoves = subtrial.generateCompleteMovesList(); final int numMovesAfterStart = subtrialMoves.size(); final int numMovesToAppend = numMovesAfterStart - numMovesBeforeStart; for (int i = 0; i < numMovesToAppend; ++i) context.trial().addMove(subtrialMoves.get(subtrialMoves.size() - 1 - i)); // // Let the match-wide trial know how many initial moves there are // context.trial().setNumInitialPlacementMoves(subtrial.numInitialPlacementMoves()); // Make sure our "real" context's RNG actually gets used and progresses if (!context.trial().over() && context.game().isStochasticGame()) context.game().moves(context); } finally { context.getLock().unlock(); } } @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 ) { return context.model().playout ( context, ais, thinkingTime, playoutMoveSelector, maxNumBiasedActions, maxNumPlayoutActions, random ); } //------------------------------------------------------------------------- @Override public boolean isGraphGame() { //StringRoutines.stackTrace(); System.err.println("Match.isGraphGame() always returns false! Should probably call context.isGraphGame() instead."); return false; } @Override public boolean isVertexGame() { //StringRoutines.stackTrace(); System.err.println("Match.isVertexGame() always returns false! Should probably call context.isVertexGame() instead."); return false; } @Override public boolean isEdgeGame() { //StringRoutines.stackTrace(); System.err.println("Match.isEdgeGame() always returns false! Should probably call context.isEdgeGame() instead."); return false; } @Override public boolean isCellGame() { //StringRoutines.stackTrace(); System.err.println("Match.isCellGame() always returns false! Should probably call context.isCellGame() instead."); return false; } @Override public boolean equipmentWithStochastic() { final BitSet regionConcept = new BitSet(); if (instances != null) for (final Subgame subgame : instances) if (subgame.getGame() != null) for (int i = 0; i < subgame.getGame().equipment().regions().length; i++) regionConcept.or(subgame.getGame().equipment().regions()[i].concepts(this)); return regionConcept.get(Concept.Stochastic.id()); } //------------------------------------------------------------------------- @Override public BitSet computeBooleanConcepts() { final BitSet gameConcept = new BitSet(); if (end != null) gameConcept.or(end.concepts(this)); if (instances != null) for (final Subgame subgame : instances) gameConcept.or(subgame.concepts(this)); gameConcept.set(Concept.Match.id(), true); return gameConcept; } @Override public BitSet computeWritingEvalContextFlag() { final BitSet writingEvalContextFlags = new BitSet(); if (end != null) writingEvalContextFlags.or(end.writesEvalContextRecursive()); if (instances != null) for (final Subgame subgame : instances) writingEvalContextFlags.or(subgame.writesEvalContextRecursive()); return writingEvalContextFlags; } @Override public BitSet computeReadingEvalContextFlag() { final BitSet readingEvalContextFlags = new BitSet(); if (end != null) readingEvalContextFlags.or(end.readsEvalContextRecursive()); if (instances != null) for (final Subgame subgame : instances) readingEvalContextFlags.or(subgame.readsEvalContextRecursive()); return readingEvalContextFlags; } @Override public Map<Integer, String> computeNonBooleanConcepts() { final Map<Integer, String> nonBooleanConcepts = new HashMap<Integer, String>(); int countPlayableSites = 0; int countPlayableSitesOnBoard = 0; int numColumns = 0; int numRows = 0; int numCorners = 0; double avgNumDirection = 0.0; double avgNumOrthogonalDirection = 0.0; double avgNumDiagonalDirection = 0.0; double avgNumAdjacentlDirection = 0.0; double avgNumOffDiagonalDirection = 0.0; int numOuterSites = 0; int numInnerSites = 0; int numLayers = 0; int numEdges = 0; int numCells = 0; int numVertices = 0; int numPerimeterSites = 0; int numTopSites = 0; int numBottomSites = 0; int numRightSites = 0; int numLeftSites = 0; int numCentreSites = 0; int numConvexCorners = 0; int numConcaveCorners = 0; int numPhasesBoard = 0; int numComponentsType = 0; double numComponentsTypePerPlayer = 0.0; int numPlayPhase = 0; int numDice = 0; int numContainers = 0; int numStartComponents = 0; int numStartComponentsHands = 0; int numStartComponentsBoard = 0; int numPlayers = 0; int numGamesCompiled = 0; for (final Subgame subGame : instances) { final Game game = subGame.getGame(); if(game != null) { numGamesCompiled++; final SiteType defaultSiteType = game.board().defaultSite(); final List<? extends TopologyElement> elements = game.board().topology().getGraphElements(defaultSiteType); final int numDefaultElements = elements.size(); int totalNumDirections = 0; int totalNumOrthogonalDirections = 0; int totalNumDiagonalDirections = 0; int totalNumAdjacentDirections = 0; int totalNumOffDiagonalDirections = 0; for (final TopologyElement element : elements) { totalNumDirections += element.neighbours().size(); totalNumOrthogonalDirections += element.orthogonal().size(); totalNumDiagonalDirections += element.diagonal().size(); totalNumAdjacentDirections += element.adjacent().size(); totalNumOffDiagonalDirections += element.off().size(); } for (final Concept concept : Concept.values()) if (!concept.dataType().equals(ConceptDataType.BooleanData)) { switch (concept) { case NumPlayableSites: for (int cid = 0; cid < game.equipment().containers().length; cid++) { final Container container = game.equipment().containers()[cid]; if (cid != 0) countPlayableSites += container.numSites(); else { if (booleanConcepts.get(Concept.Cell.id())) countPlayableSites += container.topology().cells().size(); if (booleanConcepts.get(Concept.Vertex.id())) countPlayableSites += container.topology().vertices().size(); if (booleanConcepts.get(Concept.Edge.id())) countPlayableSites += container.topology().edges().size(); } } break; case NumPlayableSitesOnBoard: final Container container = game.equipment().containers()[0]; if (booleanConcepts.get(Concept.Cell.id())) countPlayableSitesOnBoard += container.topology().cells().size(); if (booleanConcepts.get(Concept.Vertex.id())) countPlayableSitesOnBoard += container.topology().vertices().size(); if (booleanConcepts.get(Concept.Edge.id())) countPlayableSitesOnBoard += container.topology().edges().size(); break; case NumColumns: numColumns += game.board().topology().columns(defaultSiteType).size(); break; case NumPlayers: numPlayers += game.players().count(); break; case NumRows: numRows += game.board().topology().rows(defaultSiteType).size(); break; case NumCorners: numCorners += game.board().topology().corners(defaultSiteType).size(); break; case NumDirections: avgNumDirection += (double) totalNumDirections / (double) numDefaultElements; break; case NumOrthogonalDirections: avgNumOrthogonalDirection += (double) totalNumOrthogonalDirections / (double) numDefaultElements; break; case NumDiagonalDirections: avgNumDiagonalDirection += (double) totalNumDiagonalDirections / (double) numDefaultElements; break; case NumAdjacentDirections: avgNumAdjacentlDirection += (double) totalNumAdjacentDirections / (double) numDefaultElements; break; case NumOffDiagonalDirections: avgNumOffDiagonalDirection += (double) totalNumOffDiagonalDirections / (double) numDefaultElements; break; case NumOuterSites: numOuterSites += game.board().topology().outer(defaultSiteType).size(); break; case NumInnerSites: numInnerSites += game.board().topology().inner(defaultSiteType).size(); break; case NumLayers: numLayers += game.board().topology().layers(defaultSiteType).size(); break; case NumEdges: numEdges += game.board().topology().edges().size(); break; case NumCells: numCells += game.board().topology().cells().size(); break; case NumVertices: numVertices += game.board().topology().vertices().size(); break; case NumPerimeterSites: numPerimeterSites += game.board().topology().perimeter(defaultSiteType).size(); break; case NumTopSites: numTopSites += game.board().topology().top(defaultSiteType).size(); break; case NumBottomSites: numBottomSites += game.board().topology().bottom(defaultSiteType).size(); break; case NumRightSites: numRightSites += game.board().topology().right(defaultSiteType).size(); break; case NumLeftSites: numLeftSites += game.board().topology().left(defaultSiteType).size(); break; case NumCentreSites: numCentreSites += game.board().topology().centre(defaultSiteType).size(); break; case NumConvexCorners: numConvexCorners += game.board().topology().cornersConvex(defaultSiteType).size(); break; case NumConcaveCorners: numConcaveCorners += game.board().topology().cornersConcave(defaultSiteType).size(); break; case NumPhasesBoard: final List<List<TopologyElement>> phaseElements = game.board().topology() .phases(defaultSiteType); for (final List<TopologyElement> topoElements : phaseElements) if (topoElements.size() != 0) numPhasesBoard++; break; case NumComponentsType: numComponentsType += game.equipment().components().length - 1; break; case NumComponentsTypePerPlayer: final int[] componentsPerPlayer = new int[game.players().size()]; for (int i = 1; i < game.equipment().components().length; i++) { final Component component = game.equipment().components()[i]; if (component.owner() > 0 && component.owner() < players().size()) componentsPerPlayer[component.owner()]++; } int numOwnerComponent = 0; for (int i = 1; i < componentsPerPlayer.length; i++) numOwnerComponent += componentsPerPlayer[i]; String avgNumComponentPerPlayer = players.count() <= 0 ? "0": new DecimalFormat("##.##") .format((double) numOwnerComponent / (double) players.count()) + ""; avgNumComponentPerPlayer = avgNumComponentPerPlayer.replaceAll(",", "."); numComponentsTypePerPlayer += ((double) numOwnerComponent / (double) players.count()); break; case NumPlayPhase: numPlayPhase += game.rules().phases().length; break; case NumDice: for (int i = 1; i < game.equipment().components().length; i++) if (game.equipment().components()[i].isDie()) numDice++; break; case NumContainers: numContainers += game.equipment().containers().length; break; case NumStartComponents: nonBooleanConcepts.put(Integer.valueOf(concept.id()), numStartComponents + ""); break; case NumStartComponentsHand: nonBooleanConcepts.put(Integer.valueOf(concept.id()), numStartComponentsHands + ""); break; case NumStartComponentsBoard: nonBooleanConcepts.put(Integer.valueOf(concept.id()), numStartComponentsBoard + ""); break; case NumStartComponentsPerPlayer: nonBooleanConcepts.put(Integer.valueOf(concept.id()), numStartComponents / (players().count() == 0 ? 1 : players().count()) + ""); break; case NumStartComponentsHandPerPlayer: nonBooleanConcepts.put(Integer.valueOf(concept.id()), numStartComponentsHands / (players().count() == 0 ? 1 : players().count()) + ""); break; case NumStartComponentsBoardPerPlayer: nonBooleanConcepts.put(Integer.valueOf(concept.id()), numStartComponentsBoard / (players().count() == 0 ? 1 : players().count()) + ""); break; default: break; } } } } nonBooleanConcepts.put(Integer.valueOf(Concept.NumPlayableSites.id()), ((double) countPlayableSites / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumPlayableSitesOnBoard.id()), ((double) countPlayableSitesOnBoard / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumColumns.id()), ((double) numColumns / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumRows.id()), ((double) numRows / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumCorners.id()), ((double) numCorners / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumDirections.id()), new DecimalFormat("##.##").format(avgNumDirection / numGamesCompiled).replaceAll(",", ".") + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumOrthogonalDirections.id()), new DecimalFormat("##.##").format(avgNumOrthogonalDirection / numGamesCompiled).replaceAll(",", ".") + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumDiagonalDirections.id()), new DecimalFormat("##.##").format(avgNumDiagonalDirection / numGamesCompiled).replaceAll(",", ".") + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumAdjacentDirections.id()), new DecimalFormat("##.##").format(avgNumAdjacentlDirection / numGamesCompiled).replaceAll(",", ".") + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumOffDiagonalDirections.id()), new DecimalFormat("##.##").format(avgNumOffDiagonalDirection / numGamesCompiled).replaceAll(",", ".") + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumOuterSites.id()), ((double) numOuterSites / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumInnerSites.id()), ((double) numInnerSites / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumLayers.id()), ((double) numLayers / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumEdges.id()), ((double) numEdges / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumCells.id()), ((double) numCells / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumVertices.id()), ((double) numVertices / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumPerimeterSites.id()), ((double) numPerimeterSites / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumTopSites.id()), ((double) numTopSites / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumBottomSites.id()), ((double) numBottomSites / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumRightSites.id()), ((double) numRightSites / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumLeftSites.id()), ((double) numLeftSites / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumCentreSites.id()), ((double) numCentreSites / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumConvexCorners.id()), ((double) numConvexCorners / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumConcaveCorners.id()), ((double) numConcaveCorners / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumPhasesBoard.id()), ((double) numPhasesBoard / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumComponentsType.id()), ((double) numComponentsType / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumComponentsTypePerPlayer.id()), (numComponentsTypePerPlayer / numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumPlayPhase.id()), ((double) numPlayPhase / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumDice.id()), ((double) numDice / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumContainers.id()), ((double) numContainers / (double) numGamesCompiled) + ""); nonBooleanConcepts.put(Integer.valueOf(Concept.NumPlayers.id()), ((double) numPlayers / (double) numGamesCompiled) + ""); return nonBooleanConcepts; } @Override public boolean computeRequirementReport() { boolean missingRequirement = false; if (end != null) missingRequirement |= end.missingRequirement(this); if (instances != null) for (final Subgame subgame : instances) missingRequirement |= subgame.missingRequirement(this); return missingRequirement; } @Override public boolean computeCrashReport() { boolean crash = false; if (end != null) crash |= end.willCrash(this); if (instances != null) for (final Subgame subgame : instances) crash |= subgame.willCrash(this); return crash; } @Override public boolean isStacking() { return false; } }
26,922
32.69587
189
java
Ludii
Ludii-master/Core/src/game/match/Subgame.java
package game.match; import java.io.Serializable; import java.util.BitSet; import annotations.Name; import annotations.Opt; import game.Game; import game.functions.ints.IntFunction; import other.BaseLudeme; /** * Defines an instance game of a match. * * @author Eric.Piette */ public final class Subgame extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The name of the game. */ private final String gameName; /** The name of the option. */ private final String optionName; /** The game compiled. */ private Game game = null; /** The next instance. */ private final IntFunction nextInstance; /** The result (for the match score) got by the winner. */ private final IntFunction result; /** If this is set to true, we should automatically disable memoryless playouts on any games we compile */ private boolean disableMemorylessPlayouts = false; //------------------------------------------------------------------------- /** * @param name The name of the game instance. * @param option The option of the game instance. * @param next The index of the next instance. * @param result The score result for the match when game instance is over. * * @example (subgame "Tic-Tac-Toe") */ public Subgame ( final String name, @Opt final String option, @Opt @Name final IntFunction next, @Opt @Name final IntFunction result ) { gameName = name; optionName = option; nextInstance = next; this.result = result; } //------------------------------------------------------------------------- /** * To set the game. * * @param game */ public void setGame(final Game game) { this.game = game; if (disableMemorylessPlayouts) game.disableMemorylessPlayouts(); } /** * @return The name of the game. */ public String gameName() { return gameName; } /** * @return The name of the option. */ public String optionName() { return optionName; } /** * @return the game compiled. */ public Game getGame() { return game; } /** * Disables memoryless playouts on the current game (if any), and any future * games that may get set. */ public void disableMemorylessPlayouts() { disableMemorylessPlayouts = true; if (game != null) game.disableMemorylessPlayouts(); } //------------------------------------------------------------------------- /** * @return next Instance. */ public IntFunction next() { return nextInstance; } /** * @return result for the winner. */ public IntFunction result() { return result; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Game g) { final BitSet concepts = new BitSet(); if (game != null) concepts.or(game.computeBooleanConcepts()); if (nextInstance != null) concepts.or(nextInstance.concepts(game)); if (result != null) concepts.or(result.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); if (game != null) writeEvalContext.or(game.computeWritingEvalContextFlag()); if (nextInstance != null) writeEvalContext.or(nextInstance.writesEvalContextRecursive()); if (result != null) writeEvalContext.or(result.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); if (game != null) readEvalContext.or(game.computeReadingEvalContextFlag()); if (nextInstance != null) readEvalContext.or(nextInstance.readsEvalContextRecursive()); if (result != null) readEvalContext.or(result.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game g) { boolean missingRequirement = false; if (g != null) missingRequirement |= g.missingRequirement(g); if (nextInstance != null) missingRequirement |= nextInstance.missingRequirement(g); if (result != null) missingRequirement |= result.missingRequirement(g); return missingRequirement; } @Override public boolean willCrash(final Game g) { boolean willCrash = false; if (g != null) willCrash |= g.willCrash(g); if (nextInstance != null) willCrash |= nextInstance.willCrash(g); if (result != null) willCrash |= result.willCrash(g); return willCrash; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("[Subgame: " + gameName); if (optionName != null) sb.append(" (" + optionName + ")"); sb.append("]"); return sb.toString(); } }
4,860
20.227074
107
java
Ludii
Ludii-master/Core/src/game/match/package-info.java
/** * {\it Matches} are composed of multiple {\it instances} of component games. * Each match maintains additional state information beyond that stored for each of its component games, * and is effectively a super-game whose result is determined by the results of its sub-games. */ package game.match;
309
43.285714
105
java
Ludii
Ludii-master/Core/src/game/mode/Mode.java
package game.mode; import java.io.Serializable; import java.util.BitSet; import game.Game; import game.types.play.ModeType; import other.BaseLudeme; import other.model.AlternatingMove; import other.model.Model; import other.model.SimulationMove; import other.model.SimultaneousMove; import other.playout.Playout; /** * Describes the mode of play. * * @author cambolbro and Eric.Piette */ public final class Mode extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; /** Control type. */ protected ModeType mode; // Custom playout for certain game types protected Playout playout; //------------------------------------------------------------------------- /** * @param mode The mode of the game. * * @example (mode Simultaneous) */ public Mode ( final ModeType mode ) { this.mode = mode; } //------------------------------------------------------------------------- /** * @return Control type. */ public ModeType mode() { return mode; } /** * To set the mode of the game. * @param modeType */ public void setMode(ModeType modeType) { this.mode = modeType; } /** * @return Playout implementation */ public Playout playout() { return playout; } /** * Set playout implementation to use * @param newPlayout */ public void setPlayout(final Playout newPlayout) { playout = newPlayout; } /** * @return A newly-created model for this mode */ public Model createModel() { final Model model; switch (mode) { case Alternating: model = new AlternatingMove(); break; case Simultaneous: model = new SimultaneousMove(); break; case Simulation: model = new SimulationMove(); break; default: model = null; break; } return model; } @Override public BitSet concepts(final Game game) { // switch (mode) // { // case Alternating: // return GameConcept.Alternating; // case Simultaneous: // return GameConcept.Simultaneous; // case Simulation: // return GameConcept.Simulation; // default: // return GameConcept.Alternating; // } return new BitSet(); } }
2,141
16.274194
76
java
Ludii
Ludii-master/Core/src/game/mode/package-info.java
/** * The {\it mode} of a game refers to the way it is played. * Ludii supports the following modes of play: * * \begin{itemize} * \item {\it Alternating}: Players take turns making discrete moves. * \item {\it Simultaneous}: Players move at the same time. * \end{itemize} */ package game.mode;
305
26.818182
69
java
Ludii
Ludii-master/Core/src/game/players/Player.java
package game.players; import java.awt.Color; import java.io.Serializable; import java.util.BitSet; import game.Game; import game.util.directions.DirectionFacing; import gnu.trove.list.array.TIntArrayList; import other.BaseLudeme; import other.concept.Concept; /** * A player of the game. * * @author cambolbro and Eric.Piette * * @remarks Defines a player with a specific name or direction. */ public final class Player extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Player index, starting at 1. */ private int index; /** Player name. */ private String name; /** Player colour for UI. */ private Color colour; /** Player colour for UI. */ private final DirectionFacing direction; /** List of enemies. */ private final TIntArrayList enemies = new TIntArrayList(); //------------------------------------------------------------------------- /** * For defining a player with a facing direction. * * @param dirn The direction of the pieces of the player. * * @example (player N) */ public Player(final DirectionFacing dirn) { this.direction = dirn; } //------------------------------------------------------------------------- /** * @return Player index, starting at 1. */ public int index() { return index; } /** * Set the index of the player. * * @param id The index. */ public void setIndex(final int id) { index = id; } /** * @return Player name. */ public String name() { return name; } /** * To set the name of the player. * * @param s */ public void setName(final String s) { name = s; } /** * @return Player colour. */ public Color colour() { return colour; } /** * @return Player direction. */ public DirectionFacing direction() { return direction; } /** * @return Enemies. */ public TIntArrayList enemies() { return enemies; } /** * To init the enemies of the player. * * @param numPlayers */ public void setEnemies(int numPlayers) { for (int id = 1; id <= numPlayers; id++) if (id != index) enemies.add(id); } /** * @return true of the function is immutable, allowing extra optimisations. */ public static boolean isStatic() { return false; } /** * Called once after a game object has been created. Allows for any game- * specific preprocessing (e.g. precomputing and caching of static results). * * @param game */ public void preprocess(final Game game) { // Nothing to do. } /** * @param game The game. * @return Accumulated flags for this state type. */ public static long gameFlags(final Game game) { return 0l; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); if (direction != null) { concepts.set(Concept.PieceDirection.id(), true); concepts.set(Concept.PlayersWithDirections.id(), true); } return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { final boolean missingRequirement = false; return missingRequirement; } @Override public boolean willCrash(final Game game) { final boolean willCrash = false; return willCrash; } //------------------------------------------------------------------------- /** * Set default colour. Can be overridden by user UI settings. */ public void setDefaultColour() { switch (index) { case 1: this.colour = new Color(255, 255, 255); break; case 2: this.colour = new Color(63, 63, 63); break; case 3: this.colour = new Color(191, 191, 191); break; case 4: this.colour = new Color(255, 0, 0); break; case 5: this.colour = new Color(0, 127, 255); break; case 6: this.colour = new Color(0, 200, 255); break; case 7: this.colour = new Color(230, 230, 0); break; case 8: this.colour = new Color(0, 230, 230); break; default: this.colour = null; } } //------------------------------------------------------------------------- @Override public String toString() { final String str = "Player(name: " + name + ", index: " + index + ", colour: " + colour + ")"; return str; } }
4,524
17.545082
96
java
Ludii
Ludii-master/Core/src/game/players/Players.java
package game.players; import java.io.Serializable; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import exception.LimitPlayerException; import game.Game; import main.Constants; import other.BaseLudeme; /** * Defines the players of the game. * * @author cambolbro and Eric.Piette */ public final class Players extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Player records: 0 is empty, then player indices are 1..P. */ protected final List<Player> players = new ArrayList<Player>(); //------------------------------------------------------------------------- /** * To define a set of many players with specific data for each. * * @param players The list of players. * @example (players {(player N) (player S)}) */ public Players ( final Player[] players ) { this.players.add(null); // pad slot 0 to null player if (players != null) for (int p = 0; p < players.length; p++) { final Player player = players[p]; if(player.name() == null) player.setName("Player " + (p+1)); player.setIndex(p+1); player.setDefaultColour(); player.setEnemies(players.length); this.players.add(player); } if (this.players.size() > Constants.MAX_PLAYERS + 1) throw new LimitPlayerException(this.players.size()); } /** * To define a set of many players with the same data for each. * * @param numPlayers The number of players. * * @example (players 2) */ public Players ( final Integer numPlayers ) { players.add(null); // pad slot 0 to null player if (players != null) for (int p = 0; p < numPlayers.intValue(); p++) { final Player player = new Player(null); if (player.name() == null) player.setName("Player " + (p+1)); player.setIndex(p+1); player.setDefaultColour(); player.setEnemies(numPlayers.intValue()); players.add(player); } if (players.size() > Constants.MAX_PLAYERS + 1) throw new LimitPlayerException(players.size()); if (numPlayers.intValue() < 0) throw new LimitPlayerException(numPlayers.intValue()); } //------------------------------------------------------------------------- /** * @return Number of players. */ public int count() { return players.size() - 1; } /** * @return Number of player slots including null player. */ public int size() { return players.size(); } /** * @return Player records: 0 is empty, then player indices are 1..P. */ public List<Player> players() { return Collections.unmodifiableList(players); } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); for (int i = 1; i < players.size(); i++) { final Player player = players.get(i); concepts.or(player.concepts(game)); } return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); for (int i = 1; i < players.size(); i++) { final Player player = players.get(i); writeEvalContext.or(player.writesEvalContextRecursive()); } return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); for (int i = 1; i < players.size(); i++) { final Player player = players.get(i); readEvalContext.or(player.readsEvalContextRecursive()); } return readEvalContext; } /** * Called once after a game object has been created. Allows for any game- * specific preprocessing (e.g. precomputing and caching of static results). * * @param game */ public void preprocess(final Game game) { for (int i = 1; i < players.size(); i++) { final Player player = players.get(i); player.preprocess(game); } } /** * @param game The game. * @return Accumulated flags for this state type. */ public long gameFlags(final Game game) { long gameFlags = 0l; for (int i = 1; i < players.size(); i++) { //final Player player = players.get(i); gameFlags |= Player.gameFlags(game); } return gameFlags; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; for (int i = 1; i < players.size(); i++) { final Player player = players.get(i); missingRequirement |= player.missingRequirement(game); } return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; for (int i = 1; i < players.size(); i++) { final Player player = players.get(i); willCrash |= player.willCrash(game); } return willCrash; } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { if(count() == 0) return ""; final Pattern p = Pattern.compile("Player \\d+"); Matcher m = null; String playerName = null; boolean allMatch = false; String text = ""; for(int i = 1; i < players.size(); i++) { playerName = players.get(i).name(); m = p.matcher(playerName); // Does the player have a specific name? final boolean match = m.matches(); if(i == 1) allMatch = match; else if(allMatch ^ match) throw new RuntimeException("We assume that every player has a unique name or no one has one!"); if(!match) { if(!text.isEmpty()) text += i == players.size() - 1 ? " and " : ", "; text += playerName; } } return text; } //------------------------------------------------------------------------- }
5,752
21.920319
99
java
Ludii
Ludii-master/Core/src/game/players/package-info.java
/** * The {\it players} of a game are the entities that compete within the game according to its rules. * Players can be: * * \begin{itemize} * \item {\it Human}: i.e. you! * \item {\it AI}: Artificial intelligence agents. * \item {\it Remote}: Remote players over a network, which may be Human or AI. * \end{itemize} * * Each player has a name and a number according to the default play order. * The {\tt Neutral} player (index 0) is used to denote equipment that belongs to no player, * and to make moves associated with the environment rather than any actual player. * The {\tt Shared} player (index $N+1$ where $N$ is the number of players) is used to denote equipment that belongs to all players. * The actual players are denoted {\tt P1}, {\tt P2}, {\tt P3}, ... in game descriptions. */ package game.players;
838
45.611111
133
java
Ludii
Ludii-master/Core/src/game/rules/Rule.java
package game.rules; import game.types.state.GameType; import other.Ludeme; import other.context.Context; /** * Defines a rule of the game. * * @author cambolbro */ public interface Rule extends GameType, Ludeme { /** * @param context */ public void eval(final Context context); }
293
14.473684
46
java
Ludii
Ludii-master/Core/src/game/rules/Rules.java
package game.rules; import java.io.Serializable; import annotations.Name; import annotations.Opt; import game.Game; import game.rules.end.End; import game.rules.meta.Meta; import game.rules.phase.Phase; import game.rules.play.Play; import game.rules.start.Start; import game.types.play.RoleType; import other.BaseLudeme; /** * Sets the game's rules. * * @author cambolbro and Eric.Piette */ public final class Rules extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Metarules defined before play that supersede all other rules. */ private final Meta metarules; /** Starting instructions. */ private final Start start; /** Phases of the game. */ private final Phase[] phases; /** Global game end (not coupled to phases, does not require any player to be active) */ private End end; //------------------------------------------------------------------------- /** * For defining the rules with start, play and end. * * @param meta Metarules defined before play that supersede all other rules. * @param start Rules defining the starting position. * @param play Rules of play. * @param end Ending rules. * * @example (rules (play (move Add (to (sites Empty)))) (end (if (is Line 3) * (result Mover Win))) ) */ public Rules ( @Opt final Meta meta, @Opt final Start start, final Play play, final End end ) { metarules = meta; this.start = start; phases = new Phase[] {new Phase("Default Phase", RoleType.Shared, null, play, null, null, null)}; this.end = end; } /** * For defining the rules with some phases. * * @param meta Metarules defined before play that supersede all other rules. * @param start The starting rules. * @param play The playing rules shared between each phase. * @param phases The phases of the game. * @param end The ending rules shared between each phase. * * @example (rules (start (place "Ball" "Hand" count:3)) * * phases:{ (phase "Placement" (play (fromTo (from (handSite Mover)) * (to (sites Empty))) ) (nextPhase ("HandEmpty" P2) "Movement") ) * * (phase "Movement" (play (forEach Piece)) ) } (end (if (is Line 3) * (result Mover Win))) ) */ public Rules ( @Opt final Meta meta, @Opt final Start start, @Opt final Play play, @Name final Phase[] phases, @Opt final End end ) { metarules = meta; this.start = start; this.phases = phases; for (final Phase phase : phases) { if (phase.play() == null) phase.setPlay(play); else if (play != null) phase.setPlay ( new Play ( new game.rules.play.moves.nonDecision.operators.logical.Or(phase.play().moves(), play.moves(), null) ) ); } this.end = end; } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String text = ""; if(start != null) { String startRules = ""; for(int i = 0; i < start.rules().length; i++) { final String rule = start.rules()[i].toEnglish(game); if(!rule.isEmpty()) startRules += "\n " + rule.substring(0, 1).toUpperCase() + rule.substring(1); } if(!startRules.isEmpty()) text += "Setup:" + startRules + "."; } String phaseRules = ""; for (final Phase phase : phases) { final String rule = phase.play().toEnglish(game); if(!rule.isEmpty()) phaseRules += (phaseRules.isEmpty() ? "" : " ") + rule; } if(!phaseRules.isEmpty()) text += (text.isEmpty() ? "" : "\n") + "Rules: \n " + phaseRules.substring(0, 1).toUpperCase() + phaseRules.substring(1) + "."; if(end != null) { String endRules = ""; for (int i = 0; i < end.endRules().length; i++) { final String rule = end.endRules()[i].toEnglish(game); if(!rule.isEmpty()) endRules += (endRules.isEmpty() ? "" : " ") + rule; } if(!endRules.isEmpty()) text += (text.isEmpty() ? "" : "\n") + "Aim: \n " + endRules.substring(0, 1).toUpperCase() + endRules.substring(1) + "."; } return text; } //------------------------------------------------------------------------- /** * @return Meta instructions. */ public Meta meta() { return metarules; } /** * @return Starting instructions. */ public Start start() { return start; } /** * @return Phases of the game. */ public Phase[] phases() { return phases; } /** * @return End rules of the game */ public End end() { return end; } /** * To set the ending rules. * * @param e */ public void setEnd(final End e) { end = e; } }
4,833
21.801887
134
java
Ludii
Ludii-master/Core/src/game/rules/package-info.java
/** * @chapter Rule ludemes describe {\it how} the game is played. * Games may be sub-divided into named {\it phases}, each with its own sub-rules, for clarity. * Each games will typically have ``start'', ``play'' and ``end'' rules. * * @section The {\it rules} ludeme describes the actual rules of play. * These typically consist of ``start'', ``play'' and ``end'' rules. */ package game.rules;
434
42.5
103
java
Ludii
Ludii-master/Core/src/game/rules/end/BaseEndRule.java
package game.rules.end; import java.util.BitSet; import annotations.Hide; import annotations.Opt; import game.Game; import other.context.Context; /** * Dual role object; links end rules in the grammar and contains result afterwards. * * @author cambolbro */ @Hide public class BaseEndRule extends EndRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * The base end rule. * * @param result The result. */ public BaseEndRule ( @Opt final Result result ) { super(result); } //------------------------------------------------------------------------- /** * @return Must return EndRule object! * If return Result, grammar can't chain it with an end rule. */ @Override public EndRule eval(final Context context) { return null; } @Override public long gameFlags(final Game game) { return 0; } @Override public void preprocess(final Game game) { // Nothing to do. } @Override public BitSet stateConcepts(final Context context) { final BitSet concepts = new BitSet(); return concepts; } @Override public String toEnglish(final Game game) { return ""; } }
1,224
15.780822
84
java
Ludii
Ludii-master/Core/src/game/rules/end/ByScore.java
package game.rules.end; import java.util.BitSet; import annotations.Name; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanConstant; import game.functions.booleans.BooleanFunction; import game.functions.ints.board.Id; import game.types.state.GameType; import game.util.end.Score; import main.Status; import other.concept.Concept; import other.context.Context; import other.trial.Trial; /** * Is used to end a game based on the score of each player. * * @author Eric.Piette and cambolbro */ public class ByScore extends Result { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** To compute the scores. */ final private Score[] finalScore; /** Misere version. */ private final BooleanFunction misereFn; //------------------------------------------------------------------------- /** * @param finalScore The final score of each player. * @param misere Misere version of the ludeme [False]. * @example (byScore) */ public ByScore ( @Opt final Score[] finalScore, @Opt @Name final BooleanFunction misere ) { super(null, null); this.finalScore = finalScore; this.misereFn = (misere == null) ? new BooleanConstant(false) : misere; } //------------------------------------------------------------------------- @Override public void eval(final Context context) { final Trial trial = context.trial(); final boolean misere = misereFn.eval(context); if (finalScore != null) { for (int i = 0; i < finalScore.length; i++) { final Score score = finalScore[i]; final int pid = new Id(null, score.role()).eval(context); final int scoreToSet = score.score().eval(context); context.setScore(pid, scoreToSet); } } final int numPlayers = context.game().players().count(); context.setAllInactive(); final int[] allScores = new int[numPlayers + 1]; for (int pid = 1; pid < allScores.length; pid++) { // System.out.println("Player " + pid + " has score " + context.score(pid) + "."); allScores[pid] = context.score(pid); } // Keep assigning ranks until everyone got a rank int numAssignedRanks = 0; if(!misere) { while (true) { int maxScore = Integer.MIN_VALUE; int numMax = 0; // Detection of the max score for (int p = 1; p < allScores.length; p++) { final int score = allScores[p]; if (score > maxScore) { maxScore = score; numMax = 1; } else if (score == maxScore) { ++numMax; } } if (maxScore == Integer.MIN_VALUE) // We've assigned players to every rank break; final double nextWinRank = ((numAssignedRanks + 1.0) * 2.0 + numMax - 1.0) / 2.0; assert(nextWinRank >= 1.0 && nextWinRank <= context.trial().ranking().length); for (int p = 1; p < allScores.length; p++) { if (maxScore == allScores[p]) { context.trial().ranking()[p] = nextWinRank; allScores[p] = Integer.MIN_VALUE; } } numAssignedRanks += numMax; } } else { while (true) { int minScore = Integer.MAX_VALUE; int numMin = 0; // Detection of the min score for (int p = 1; p < allScores.length; p++) { final int score = allScores[p]; if (score < minScore) { minScore = score; numMin = 1; } else if (score == minScore) { ++numMin; } } if (minScore == Integer.MAX_VALUE) // We've assigned players to every rank break; final double nextWinRank = ((numAssignedRanks + 1.0) * 2.0 + numMin - 1.0) / 2.0; assert(nextWinRank >= 1.0 && nextWinRank <= context.trial().ranking().length); for (int p = 1; p < allScores.length; p++) { if (minScore == allScores[p]) { context.trial().ranking()[p] = nextWinRank; allScores[p] = Integer.MAX_VALUE; } } numAssignedRanks += numMin; } } // Set status (with winner if someone has full rank 1.0) int winner = 0; int loser = 0; for (int p = 1; p < context.trial().ranking().length; ++p) { if (context.trial().ranking()[p] == 1.0) winner = p; else if (context.trial().ranking()[p] == context.trial().ranking().length) loser = p; } if (winner > 0) context.addWinner(winner); if (loser > 0) context.addLoser(loser); trial.setStatus(new Status(winner)); } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = 0L; gameFlags |= GameType.Score; if (finalScore != null) for (final Score fScore : finalScore) gameFlags |= fScore.gameFlags(game); gameFlags |= misereFn.gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.set(Concept.Scoring.id(), true); concepts.set(Concept.ScoringEnd.id(), true); concepts.set(Concept.ScoringWin.id(), true); if (finalScore != null) for (final Score fScore : finalScore) concepts.or(fScore.concepts(game)); if (concepts.get(Concept.Territory.id())) { concepts.set(Concept.TerritoryEnd.id(), true); concepts.set(Concept.TerritoryWin.id(), true); } concepts.or(misereFn.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (finalScore != null) for (final Score fScore : finalScore) writeEvalContext.or(fScore.writesEvalContextRecursive()); writeEvalContext.or(misereFn.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (finalScore != null) for (final Score fScore : finalScore) readEvalContext.or(fScore.readsEvalContextRecursive()); readEvalContext.or(misereFn.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; if (finalScore != null) for (final Score fScore : finalScore) missingRequirement |= fScore.missingRequirement(game); missingRequirement |= misereFn.missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; if (finalScore != null) for (final Score fScore : finalScore) willCrash |= fScore.willCrash(game); willCrash |= misereFn.willCrash(game); return willCrash; } @Override public void preprocess(final Game game) { if (finalScore != null) for (final Score fScore : finalScore) fScore.preprocess(game); misereFn.preprocess(game); } @Override public String toEnglish(final Game game) { final boolean misere = misereFn.eval(new Context(game, new Trial(game))); if(misere) return "the game ends and the player with the lowest score wins"; else return "the game ends and the player with the highest score wins"; } }
7,273
23.166113
85
java
Ludii
Ludii-master/Core/src/game/rules/end/End.java
package game.rules.end; import java.util.Arrays; import java.util.BitSet; import annotations.Or; import game.Game; import game.functions.ints.board.Id; import game.rules.Rule; import game.types.play.ResultType; import game.types.play.RoleType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import main.Status; import other.BaseLudeme; import other.context.Context; import other.state.State; import other.trial.Trial; /** * Defines the rules for ending a game. * * @author Eric.Piette and cambolbro */ public class End extends BaseLudeme implements Rule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Condition that triggers end of game. */ private final EndRule[] endRules; /** True if this ludeme is used for a match. */ private boolean match = false; //------------------------------------------------------------------------- /** * @param endRule The ending rule. * @param endRules The ending rules. * * @example (end (if (no Moves Next) (result Mover Win) ) ) */ public End ( @Or final EndRule endRule, @Or final EndRule[] endRules ) { int numNonNull = 0; if (endRule != null) numNonNull++; if (endRules != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException("Exactly one Or parameter must be non-null."); if (endRule != null) this.endRules = new EndRule[] { endRule }; else { this.endRules = endRules; } } //------------------------------------------------------------------------- /** * @return Array of end rules. */ public EndRule[] endRules() { return endRules; } //------------------------------------------------------------------------- @Override public void eval(final Context context) { if (match) { evalMatch(context); } else { Result applyResult; for (final EndRule endingRule : endRules) { final EndRule endRuleResult = endingRule.eval(context); if (endRuleResult == null) continue; applyResult = endRuleResult.result(); if (applyResult == null) continue; final int whoResult = new Id(null, applyResult.who()).eval(context); if (!context.active(whoResult) && whoResult != context.game().players().size()) continue; applyResult(applyResult, context); // Do not break here. Sometimes we need to check all // end conditions, not just the first one that's true. // break; } if (!context.trial().over() && context.game().requiresAllPass() && context.allPass()) { // Nobody wins applyResult = new Result(RoleType.All, ResultType.Draw); applyResult(applyResult, context); } } // Reinit these numbers context.setNumLossesDecided(0); context.setNumWinsDecided(0); // To print the rank at the end // for (int id = 0; id < context.state().ranking().length; id++) // System.out.println("id = 0, rank is " + context.state().ranking()[id]); } /** * Apply the result of the game. * * @param applyResult The result to apply. * @param context The context. */ public static void applyResult(final Result applyResult, final Context context) { final RoleType whoRole = applyResult.who(); if (whoRole.toString().contains("Team")) { applyTeamResult(applyResult, context); } else { final Trial trial = context.trial(); final State state = context.state(); // Apply result final int who = new Id(null, whoRole).eval(context); // System.out.println("WHO: " + who); double rank = 1.0; int onlyOneActive = Constants.UNDEFINED; switch (applyResult.result()) { case Win: // "who" wins if (whoRole.equals(RoleType.All)) { if (context.game().players().count() > 1) { final double score = 1.0; for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 0.0) { context.addWinner(player); context.trial().ranking()[player] = score; } } } else { context.trial().ranking()[1] = 0.0; } context.setAllInactive(); trial.setStatus(new Status(0)); } else { context.setActive(who, false); rank = context.computeNextWinRank(); context.addWinner(who); assert(rank >= 1.0 && rank <= context.trial().ranking().length); context.trial().ranking()[who] = rank; onlyOneActive = context.onlyOneActive(); if (onlyOneActive != 0) { context.trial().ranking()[onlyOneActive] = rank + 1.0; context.addLoser(onlyOneActive); for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 1) { trial.setStatus(new Status(player)); break; } } context.setActive(onlyOneActive, false); } else if (!context.active()) { context.setAllInactive(); for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 1) { trial.setStatus(new Status(player)); break; } } } } // We increment that data in case of many results in the same turn. context.setNumWinsDecided(context.numWinsDecided() + 1); break; case Loss: // "opp" loses if (whoRole.equals(RoleType.All)) { if (context.game().players().count() > 1) { final double score = context.game().players().count(); for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 0.0) { context.trial().ranking()[player] = score; } } } else { context.trial().ranking()[1] = 0.0; } context.setAllInactive(); trial.setStatus(new Status(0)); break; } else { if (context.active(who)) // We apply the result only if that player was active before to lose. { context.setActive(who, false); if (state.next() == who && context.game().players().count() != 1) { int next = who; while (!context.active(next) && context.active()) { next++; if (next > context.game().players().count()) next = 1; } state.setNext(next); } // Don't do anything for one player game. if (context.trial().ranking().length > 2) { // Rank we would assign for a brand new singular loss rank = context.computeNextLossRank(); // Num losses already assigned in same eval() call final int numSimulLosses = context.numLossesDecided(); // Compute rank we may have temporarily assigned to any previous losses final double prevLossRank = rank + 1.0 + 0.5 * (numSimulLosses - 1.0); // Compute the correct rank that we want for this player and any other simultaneous losers rank = prevLossRank - 0.5; context.trial().ranking()[who] = rank; context.addLoser(who); assert(rank >= 1.0 && context.trial().ranking()[who] <= rank); for (int id = 0; id < context.trial().ranking().length; id++) { if (context.trial().ranking()[id] == prevLossRank) context.trial().ranking()[id] = rank; } if (!context.active()) { context.setAllInactive(); for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 1.0) { trial.setStatus(new Status(player)); break; } } } else { onlyOneActive = context.onlyOneActive(); if (onlyOneActive != 0) { rank = context.computeNextWinRank(); assert(rank >= 1.0 && rank <= context.trial().ranking().length); context.trial().ranking()[onlyOneActive] = rank; double minRank = Constants.DEFAULT_MOVES_LIMIT; // A high limit to be sure that will // be // never reach with 16 players. for (int player = 1; player < context.trial().ranking().length; player++) if (context.trial().ranking()[player] < minRank) minRank = context.trial().ranking()[player]; for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == minRank) { trial.setStatus(new Status(player)); context.addWinner(player); break; } } context.setActive(onlyOneActive, false); } } } else { context.setAllInactive(); trial.setStatus(new Status(0)); } } // We increment that data in case of many results in the same turn. context.setNumLossesDecided(context.numLossesDecided() + 1); break; } case Draw: // nobody wins if (context.game().players().count() > 1) { final double score = context.computeNextDrawRank(); assert(score >= 1.0 && score <= context.trial().ranking().length); for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 0.0) { context.trial().ranking()[player] = score; } } } else if (context.game().players().count() == 1) { context.trial().ranking()[1] = 0.0; } context.setAllInactive(); trial.setStatus(new Status(0)); for (int i = 0; i < context.trial().ranking().length; i++) { if (context.trial().ranking()[i] == 1.0) trial.setStatus(new Status(i)); } break; case Tie: // everybody wins context.setAllInactive(); trial.setStatus(new Status(state.numPlayers() + 1)); // 0)); break; case Abandon: case Crash: // nobody wins context.setAllInactive(); trial.setStatus(new Status(-1)); break; default: System.out.println("** End.apply(): Result type " + applyResult.result() + " not recognised."); } } } /** * Eval the end of a match * * @param context */ private void evalMatch(final Context context) { for (final EndRule endingRule : endRules) { final EndRule endRule = endingRule.eval(context); if (endRule == null) continue; final Result applyResult = endRule.result(); if (applyResult == null) continue; final int whoResult = new Id(null, applyResult.who()).eval(context); if (!context.active(whoResult) && whoResult != context.game().players().size()) continue; applyResultMatch(applyResult, context); //break; } } /** * Apply the result of the match. * * @param applyResult The result to apply. * @param context The context. */ public void applyResultMatch(final Result applyResult, final Context context) { final RoleType whoRole = applyResult.who(); if (whoRole.toString().contains("Team")) { applyTeamResult(applyResult, context); } else { final Trial trial = context.trial(); // Apply result final int who = new Id(null, whoRole).eval(context); // System.out.println("WHO: " + who); switch (applyResult.result()) { case Win: // "who" wins context.setActive(who, false); context.addWinner(who); // To get the rank of the player. double rank = 1.0; for (/**/; rank < context.trial().ranking().length; rank++) { boolean yourRank = true; for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == rank) { yourRank = false; break; } } if (yourRank) { context.trial().ranking()[who] = rank; assert(rank >= 1.0 && rank <= context.trial().ranking().length); break; } } // We set the same rank at all the other players winning in the same state. for (final EndRule endingRule : endRules) { final EndRule endRule = endingRule.eval(context); if (endRule == null) continue; final Result applySubResult = endRule.result(); if (applySubResult == null) continue; final int whoResult = new Id(null, applySubResult.who()).eval(context); if (!context.active(whoResult) && whoResult != context.game().players().size()) continue; final ResultType resultType = applySubResult.result(); if (resultType.equals(ResultType.Win)) { context.setActive(whoResult, false); context.addWinner(whoResult); context.trial().ranking()[whoResult] = rank; } } // We compute the rank for the losers. int gapRank = 0; for (int player = 1; player < context.trial().ranking().length; player++) if (context.active(player)) gapRank++; // We set all the losers. for (int player = 1; player < context.trial().ranking().length; player++) { if (context.active(player)) { context.setActive(player, false); context.trial().ranking()[player] = rank + gapRank; } } // We close the game. context.setAllInactive(); for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 1) { trial.setStatus(new Status(player)); break; } } // final int onlyOneActive = context.onlyOneActive(); // if (onlyOneActive != 0) // { // context.trial().ranking()[onlyOneActive] = rank + 1; // assert(context.trial().ranking()[onlyOneActive] >= 1.0 && context.trial().ranking()[onlyOneActive] <= context.trial().ranking().length); // for (int player = 1; player < context.trial().ranking().length; player++) // { // if (context.trial().ranking()[player] == 1) // { // trial.setStatus(new Status(player)); // break; // } // } // } // else if (!context.active()) // { // context.setAllInactive(); // for (int player = 1; player < context.trial().ranking().length; player++) // { // if (context.trial().ranking()[player] == 1) // { // trial.setStatus(new Status(player)); // break; // } // } // } break; case Loss: // "opp" loses // state.setActive(who, false); // if (state.next() == who && context.activeGame().players().count() != 1) // { // int next = who; // while (!state.active(next)) // { // next++; // if (next > context.activeGame().players().count()) // next = 1; // } // state.setNext(next); // } // // Don't do anything for one player game. // if (state.ranking().length > 2) // { // rank = state.ranking().length - 1; // for (; rank > 0; rank--) // { // boolean yourRank = true; // for (int player = 1; player < state.ranking().length; player++) // { // if (state.ranking()[player] == rank) // { // yourRank = false; // break; // } // } // if (yourRank) // { // state.ranking()[who] = rank; // break; // } // } // // if (!state.active()) // { // state.setAllInactive(); // for (int player = 1; player < state.ranking().length; player++) // { // if (state.ranking()[player] == 1) // { // trial.setStatus(new Status(player)); // break; // } // } // } // else // { // onlyOneActive = state.onlyOneActive(state.numPlayers()); // if (onlyOneActive != 0) // { // state.ranking()[onlyOneActive] = rank - 1; // for (int player = 1; player < state.ranking().length; player++) // { // if (state.ranking()[player] == 1) // { // trial.setStatus(new Status(player)); // state.setActive(onlyOneActive, false); // state.addWinner(player); // break; // } // } // } // } // } // else // { // state.setAllInactive(); // trial.setStatus(new Status(0)); // } break; case Draw: // nobody wins if (context.game().players().count() > 1) { final double score = (context.numActive() + 1) / 2.0 + (context.numWinners()); assert(score >= 1.0 && score <= context.trial().ranking().length); for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 0.0) { context.trial().ranking()[player] = score; } } } else { context.trial().ranking()[1] = 0.0; } trial.setStatus(new Status(0)); for (int i = 0; i < context.trial().ranking().length; i++) { if (context.trial().ranking()[i] == 1.0) trial.setStatus(new Status(i)); } break; case Tie: // everybody wins trial.setStatus(new Status(context.game().players().count() + 1)); // 0)); break; case Abandon: case Crash: // nobody wins trial.setStatus(new Status(-1)); break; default: System.out.println("** End.apply(): Result type " + applyResult.result() + " not recognised."); } } } //------------------------------------------------------------------------- /** * Apply the result of the game. * * @param applyResult * @param context */ public static void applyTeamResult(final Result applyResult, final Context context) { final Trial trial = context.trial(); final State state = context.state(); final RoleType whoRole = applyResult.who(); final int team = new Id(null, whoRole).eval(context); switch (applyResult.result()) { case Win: // "who" wins final TIntArrayList teamMembers = new TIntArrayList(); for (int pid = 1; pid <= context.game().players().count(); pid++) if (context.state().playerInTeam(pid, team)) teamMembers.add(pid); for (int i = 0; i < teamMembers.size(); i++) { final int pid = teamMembers.getQuick(i); context.setActive(pid, false); context.addWinner(pid); } // To get the rank of the player. int rank = 1; for (/**/; rank < context.trial().ranking().length; rank++) { boolean yourRank = true; for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == rank) { yourRank = false; break; } } if (yourRank) { for (int i = 0; i < teamMembers.size(); i++) { final int pid = teamMembers.getQuick(i); context.trial().ranking()[pid] = rank; } break; } } final int onlyOneActive = context.onlyOneTeamActive(); if (onlyOneActive != 0) { final TIntArrayList teamLossMembers = new TIntArrayList(); for (int pid = 1; pid <= context.game().players().count(); pid++) if (context.state().playerInTeam(pid, onlyOneActive)) teamLossMembers.add(pid); for (int i = 0; i < teamLossMembers.size(); i++) { final int pid = teamLossMembers.getQuick(i); context.trial().ranking()[pid] = rank + teamMembers.size(); for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 1) { trial.setStatus(new Status(player)); break; } } } } else if (!context.active()) { context.setAllInactive(); for (int player = 1; player < context.trial().ranking().length; player++) { if (context.trial().ranking()[player] == 1) { trial.setStatus(new Status(player)); break; } } } break; case Loss: // "opp" loses // TO DO ERIC // state.setActive(team, false); // if (state.next() == team && context.activeGame().players().count() != 1) // { // int next = team; // while (!state.active(next)) // { // next++; // if (next > context.activeGame().players().count()) // next = 1; // } // state.setNext(next); // } // state.setNumActive(state.numActive() - 1); // // Don't do anything for one player game. // if (state.ranking().length > 2) // { // rank = state.ranking().length - 1; // for (; rank > 0; rank--) // { // boolean yourRank = true; // for (int player = 1; player < state.ranking().length; player++) // { // if (state.ranking()[player] == rank) // { // yourRank = false; // break; // } // } // if (yourRank) // { // state.ranking()[team] = rank; // break; // } // } // // if (!state.active()) // { // state.setAllInactive(); // for (int player = 1; player < state.ranking().length; player++) // { // if (state.ranking()[player] == 1) // { // trial.setStatus(new Status(player)); // break; // } // } // } // else // { // onlyOneActive = state.onlyOneActive(state.numPlayers()); // if (onlyOneActive != 0) // { // state.setNumActive(state.numActive() - 1); // state.ranking()[onlyOneActive] = rank - 1; // for (int player = 1; player < state.ranking().length; player++) // { // if (state.ranking()[player] == 1) // { // trial.setStatus(new Status(player)); // state.setActive(onlyOneActive, false); // state.addWinner(player); // break; // } // } // } // } // } // else // { // state.setAllInactive(); // trial.setStatus(new Status(0)); // } break; case Draw: // nobody wins // TO DO ERIC // if (context.activeGame().players().count() > 1) // { // final double score = (state.numActive() + 1) / 2.0 + (state.numWinner()); // for (int player = 1; player < state.ranking().length; player++) // { // if (state.ranking()[player] == 0.0) // { // state.ranking()[player] = score; // } // } // } // else // { // state.ranking()[1] = 0.0; // } // // state.setAllInactive(); // // trial.setStatus(new Status(0)); // for (int i = 0; i < state.ranking().length; i++) // { // if (state.ranking()[i] == 1.0) // trial.setStatus(new Status(i)); // } break; case Tie: // everybody wins context.setAllInactive(); trial.setStatus(new Status(state.numPlayers() + 1)); // 0)); break; case Abandon: case Crash: // nobody wins context.setAllInactive(); trial.setStatus(new Status(-1)); break; default: System.out.println("** End.apply(): Result type " + applyResult.result() + " not recognised."); } } //------------------------------------------------------------------------- @Override public boolean isStatic() { return false; } @Override public long gameFlags(final Game game) { long gameFlags = 0; for (final EndRule endRule : endRules) gameFlags |= endRule.gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); for (final EndRule endRule : endRules) concepts.or(endRule.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); for (final EndRule endRule : endRules) writeEvalContext.or(endRule.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); for (final EndRule endRule : endRules) readEvalContext.or(endRule.readsEvalContextRecursive()); return readEvalContext; } @Override public void preprocess(final Game game) { for (final EndRule endRule : endRules) endRule.preprocess(game); } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; for (final EndRule endRule : endRules) missingRequirement |= endRule.missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; for (final EndRule endRule : endRules) willCrash |= endRule.willCrash(game); return willCrash; } //------------------------------------------------------------------------- /** * set this ending rules to a match. * * @param value */ public void setMatch(final boolean value) { match = value; } //------------------------------------------------------------------------- @Override public String toString() { return "[End: " + Arrays.toString(endRules) + "]"; } //------------------------------------------------------------------------- }
24,662
24.961053
143
java
Ludii
Ludii-master/Core/src/game/rules/end/EndRule.java
package game.rules.end; import java.io.Serializable; import java.util.BitSet; import annotations.Opt; import game.Game; import other.BaseLudeme; import other.context.Context; /** * Declares a generic end rule. * * @author cambolbro */ public abstract class EndRule extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The result of applying this end rule. */ private Result result = null; //------------------------------------------------------------------------- /** * @param result The result of the rule. */ public EndRule ( @Opt final Result result ) { this.result = result; } //------------------------------------------------------------------------- /** * @return The result of the end rule. */ public Result result() { return result; } /** * Set the result of the end rule. * * @param rslt */ public void setResult(final Result rslt) { result = rslt; } //------------------------------------------------------------------------- /** * @param context * @return Must return EndRule object! If return Result, grammar can't chain it * with an end rule. */ public abstract EndRule eval(final Context context); /** * @param game * @return The gameFlags of the end rule. */ public abstract long gameFlags(final Game game); /** * Preprocess the end rule. * * @param game */ public abstract void preprocess(final Game game); //------------------------------------------------------------------------- /** * @param context The context. * @return The concepts related to a specific ending state */ public abstract BitSet stateConcepts(final Context context); }
1,799
19.454545
80
java
Ludii
Ludii-master/Core/src/game/rules/end/ForEach.java
package game.rules.end; import java.util.BitSet; import annotations.Name; import annotations.Opt; import annotations.Or; import game.Game; import game.functions.booleans.BooleanConstant.FalseConstant; import game.functions.booleans.BooleanFunction; import game.types.board.TrackType; import game.types.play.RoleType; import other.concept.EndConcepts; import other.context.Context; import other.context.EvalContextData; /** * Applies the end condition to each player of a certain type. * * @author cambolbro and Eric.Piette */ public final class ForEach extends BaseEndRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The Roletype to iterate. */ final private RoleType type; /** To iterate on the tracks. */ final private TrackType trackType; /** The condition to check for each iteration. */ final private BooleanFunction cond; //------------------------------------------------------------------------- /** * @param type Role type to iterate through [Shared]. * @param trackType To iterate on each track. * @param If Condition to apply. * @param result Result to return. * * @example (forEach NonMover if:(is Blocked Player) (result Player Loss)) */ public ForEach ( @Opt @Or final RoleType type, @Opt @Or final TrackType trackType, @Name final BooleanFunction If, final Result result ) { super(result); int numNonNull = 0; if (type != null) numNonNull++; if (trackType != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException( "ForEach(): one of RoleType or trackType has to be null."); this.type = (type == null) ? RoleType.Shared : type; this.cond = If; this.trackType = trackType; } //------------------------------------------------------------------------- @Override public EndRule eval(final Context context) { final int numPlayers = context.game().players().count(); if (trackType != null) // If track is specified we iterate by track. { final int originalTrackIndex = context.track(); for(int trackIndex = 0; trackIndex < context.board().tracks().size(); trackIndex++) { // Stop the loop if the game is inactive if (!context.active()) break; context.setTrack(trackIndex); if (cond.eval(context)) End.applyResult(result(), context); } context.setTrack(originalTrackIndex); } else { final int originPlayer = context.player(); // Step through each player for (int pid = 1; pid <= numPlayers; pid++) { if (type == RoleType.NonMover) { final int mover = context.state().mover(); if (pid == mover) continue; } // Do nothing if the player is not active. if (!context.active(pid)) continue; // Check that player. context.setPlayer(pid); if (cond.eval(context)) End.applyResult(result(), context); } context.setPlayer(originPlayer); } return new BaseEndRule(null); } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = 0; if (cond != null) gameFlags |= cond.gameFlags(game); if (result() != null) gameFlags |= result().gameFlags(game); return gameFlags; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; if (cond instanceof FalseConstant) { game.addRequirementToReport("One of the ending condition is \"false\" which is wrong."); missingRequirement = true; } if (trackType != null && !game.hasTrack()) { game.addRequirementToReport( "The ludeme (forEach Track ...) is used in the ending rules but the board has no tracks."); missingRequirement = true; } // We check if the roletype is correct. if (type != null) { final int indexOwnerPhase = type.owner(); if (((indexOwnerPhase < 1 && !type.equals(RoleType.NonMover)) && !type.equals(RoleType.Mover) && !type.equals(RoleType.Player) && !type.equals(RoleType.All) && !type.equals(RoleType.Shared) && !type.equals(RoleType.Each)) || indexOwnerPhase > game.players().count()) { game.addRequirementToReport( "(forEach ...) is used in the ending conditions with an incorrect RoleType " + type + "."); missingRequirement = true; } } if (cond != null) missingRequirement |= cond.missingRequirement(game); if (result() != null) missingRequirement |= result().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; if (cond != null) willCrash |= cond.willCrash(game); if (result() != null) willCrash |= result().willCrash(game); return willCrash; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); if (cond != null) concepts.or(cond.concepts(game)); if (result() != null) concepts.or(result().concepts(game)); concepts.or(EndConcepts.get(cond, null, game, result())); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); if (cond != null) writeEvalContext.or(cond.writesEvalContextRecursive()); if (result() != null) writeEvalContext.or(result().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); if (trackType != null) writeEvalContext.set(EvalContextData.Track.id(), true); else writeEvalContext.set(EvalContextData.Player.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (cond != null) readEvalContext.or(cond.readsEvalContextRecursive()); if (result() != null) readEvalContext.or(result().readsEvalContextRecursive()); return readEvalContext; } @Override public void preprocess(final Game game) { if (cond != null) cond.preprocess(game); if (result() != null) result().preprocess(game); } //------------------------------------------------------------------------- @Override public BitSet stateConcepts(final Context context) { final int numPlayers = context.game().players().count(); final BitSet concepts = new BitSet(); if (trackType != null) // If track is specified we iterate by track. { final int originalTrackIndex = context.track(); for (int trackIndex = 0; trackIndex < context.board().tracks().size(); trackIndex++) { // Stop the loop if the game is inactive if (!context.active()) break; context.setTrack(trackIndex); if (cond.eval(context)) concepts.or(EndConcepts.get(cond, context, context.game(), result())); } context.setTrack(originalTrackIndex); } else { final int originPlayer = context.player(); // Step through each player for (int pid = 1; pid <= numPlayers; pid++) { if (type == RoleType.NonMover) { final int mover = context.state().mover(); if (pid == mover) continue; } // Do nothing if the player is not active. if (!context.active(pid)) continue; // Check that player. context.setPlayer(pid); if (cond.eval(context)) concepts.or(EndConcepts.get(cond, context, context.game(), result())); } context.setPlayer(originPlayer); } return concepts; } }
7,666
23.812298
100
java
Ludii
Ludii-master/Core/src/game/rules/end/If.java
package game.rules.end; import java.util.BitSet; import annotations.Opt; import annotations.Or; import game.Game; import game.functions.booleans.BooleanConstant.FalseConstant; import game.functions.booleans.BooleanFunction; import other.concept.EndConcepts; import other.context.Context; /** * Implements the condition(s) for ending the game, and deciding its result. * * @author cambolbro and Eric.Piette * * @remarks If the stopping condition is met then this rule will return a result, * whether any sub-conditions are defined or not. */ public class If extends BaseEndRule { private static final long serialVersionUID = 1L; /** Test for whether the game ends or not. */ private final BooleanFunction endCondition; /** Sub-conditions (one or many) to decide some more complex result. */ private final If[] subconditions; //------------------------------------------------------------------------- /** * @param test Condition to end the game. * @param sub Sub-condition to check. * @param subs Sub-conditions to check. * @param result Default result to return if no sub-condition is satisfied. * * @example (if (is Mover (next)) (result Mover Win)) */ public If ( final BooleanFunction test, @Opt @Or final If sub, @Opt @Or final If[] subs, @Opt final Result result ) { super(result); int numNonNull = 0; if (sub != null) numNonNull++; if (subs != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException("Can't have more than one non-null Or parameter."); endCondition = test; subconditions = (subs != null) ? subs : (sub != null) ? new If[]{ sub } : null; } //------------------------------------------------------------------------- /** * @param context * @return The result of the game. */ @Override public EndRule eval(final Context context) { // Multiple sub-conditions to test if (endCondition.eval(context)) { if (subconditions == null) { result().eval(context); return new BaseEndRule(result()); } else { for (final If sub : subconditions) { final EndRule subResult = sub.eval(context); if (subResult != null) return subResult; } } // No other result, so fall through to default result return new BaseEndRule(result()); } return null; } //------------------------------------------------------------------------- /** * @param game * @return The gameFlags of that ludeme. */ @Override public long gameFlags(final Game game) { long gameFlags = 0; if (endCondition != null) gameFlags |= endCondition.gameFlags(game); if (subconditions != null) for (final If sub : subconditions) gameFlags |= sub.gameFlags(game); if (result() != null) gameFlags |= result().gameFlags(game); return gameFlags; } /** * @param game * @return The gameFlags of that ludeme. */ @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); if (endCondition != null) concepts.or(endCondition.concepts(game)); if (subconditions != null) for (final If sub : subconditions) concepts.or(sub.concepts(game)); if (result() != null) concepts.or(result().concepts(game)); concepts.or(EndConcepts.get(endCondition, null, game, result())); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); if (endCondition != null) writeEvalContext.or(endCondition.writesEvalContextRecursive()); if (subconditions != null) for (final If sub : subconditions) writeEvalContext.or(sub.writesEvalContextRecursive()); if (result() != null) writeEvalContext.or(result().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); if (endCondition != null) readEvalContext.or(endCondition.readsEvalContextRecursive()); if (subconditions != null) for (final If sub : subconditions) readEvalContext.or(sub.readsEvalContextRecursive()); if (result() != null) readEvalContext.or(result().readsEvalContextRecursive()); return readEvalContext; } /** * To preprocess the condition of that ludeme. */ @Override public void preprocess(final Game game) { if (endCondition != null) endCondition.preprocess(game); if (subconditions != null) for (final If sub : subconditions) sub.preprocess(game); if (result() != null) result().preprocess(game); } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; if (endCondition instanceof FalseConstant) { game.addRequirementToReport("One of the ending condition is \"false\" which is wrong."); missingRequirement = true; } if (!hasAResult()) { game.addRequirementToReport("One of the ending rule has no result."); missingRequirement = true; } if (endCondition != null) missingRequirement |= endCondition.missingRequirement(game); if (subconditions != null) for (final If sub : subconditions) missingRequirement |= sub.missingRequirement(game); if (result() != null) missingRequirement |= result().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; if (endCondition != null) willCrash |= endCondition.willCrash(game); if (subconditions != null) for (final If sub : subconditions) willCrash |= sub.willCrash(game); if (result() != null) willCrash |= result().willCrash(game); return willCrash; } //------------------------------------------------------------------------- /** * @return endCondition. */ public BooleanFunction endCondition() { return endCondition; } /** * @return true if the condition has a result. */ public boolean hasAResult() { if (result() != null) return true; else if (subconditions != null) for (final If subcondition : subconditions) return subcondition.hasAResult(); return false; } //------------------------------------------------------------------------- @Override public BitSet stateConcepts(final Context context) { // Multiple sub-conditions to test if (endCondition.eval(context)) { if (subconditions == null) { return EndConcepts.get(endCondition, context, context.game(), result()); } else { for (final If sub : subconditions) { final EndRule subResult = sub.eval(context); if (subResult != null) return subResult.stateConcepts(context); } } } return new BitSet(); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String endConditionString = ""; if (result() != null) endConditionString = ", " + result().toEnglish(game); return "If " + endCondition.toEnglish(game) + endConditionString; } }
7,112
22.245098
91
java
Ludii
Ludii-master/Core/src/game/rules/end/Payoffs.java
package game.rules.end; import java.util.BitSet; import game.Game; import game.functions.ints.board.Id; import game.types.state.GameType; import game.util.end.Payoff; import main.Status; import other.context.Context; import other.trial.Trial; /** * Is used to end a game based on the payoff of each player. * * @author Eric.Piette */ public class Payoffs extends Result { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** To compute the scores. */ final private Payoff[] finalPayoff; //------------------------------------------------------------------------- /** * @param finalPayoffs The final score of each player. * @example (payoffs {(payoff P1 5.5) (payoff P2 1.2)}) */ public Payoffs ( final Payoff[] finalPayoffs ) { super(null, null); this.finalPayoff = finalPayoffs; } //------------------------------------------------------------------------- @Override public void eval(final Context context) { final Trial trial = context.trial(); if (finalPayoff != null) { for (int i = 0; i < finalPayoff.length; i++) { final Payoff payoff = finalPayoff[i]; final int pid = new Id(null, payoff.role()).eval(context); final double payoffToSet = payoff.payoff().eval(context); context.setPayoff(pid, payoffToSet); } } final int numPlayers = context.game().players().count(); context.setAllInactive(); final double[] allPayoffs = new double[numPlayers + 1]; for (int pid = 1; pid < allPayoffs.length; pid++) { // System.out.println("Player " + pid + " has score " + context.score(pid) + "."); allPayoffs[pid] = context.payoff(pid); } if (numPlayers == 1) { // Special case: "lose" if payoff <= 0, "win" otherwise context.trial().ranking()[1] = (allPayoffs[1] <= 0.0) ? 0.0 : 1.0; } else { // Keep assigning ranks until everyone got a rank int numAssignedRanks = 0; while (true) { double maxPayoff = Integer.MIN_VALUE; int numMax = 0; // Detection of the max score for (int p = 1; p < allPayoffs.length; p++) { final double payoff = allPayoffs[p]; if (payoff > maxPayoff) { maxPayoff = payoff; numMax = 1; } else if (payoff == maxPayoff) { ++numMax; } } if (maxPayoff == Integer.MIN_VALUE) // We've assigned players to every rank break; final double nextWinRank = ((numAssignedRanks + 1.0) * 2.0 + numMax - 1.0) / 2.0; assert(nextWinRank >= 1.0 && nextWinRank <= context.trial().ranking().length); for (int p = 1; p < allPayoffs.length; p++) { if (maxPayoff == allPayoffs[p]) { context.trial().ranking()[p] = nextWinRank; allPayoffs[p] = Integer.MIN_VALUE; } } numAssignedRanks += numMax; } } // Set status (with winner if someone has full rank 1.0) int winner = 0; int loser = 0; for (int p = 1; p < context.trial().ranking().length; ++p) { if (context.trial().ranking()[p] == 1.0) winner = p; else if (context.trial().ranking()[p] == context.trial().ranking().length) loser = p; } if (winner > 0) context.addWinner(winner); if (loser > 0) context.addLoser(loser); trial.setStatus(new Status(winner)); } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = 0L; gameFlags |= GameType.Payoff; if (finalPayoff != null) for (final Payoff fPayoff : finalPayoff) gameFlags |= fPayoff.gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); if (finalPayoff != null) for (final Payoff fPayoff : finalPayoff) concepts.or(fPayoff.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (finalPayoff != null) for (final Payoff fPayoff : finalPayoff) writeEvalContext.or(fPayoff.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (finalPayoff != null) for (final Payoff fPayoff : finalPayoff) readEvalContext.or(fPayoff.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; if (finalPayoff != null) for (final Payoff fPayoff : finalPayoff) missingRequirement |= fPayoff.missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; if (finalPayoff != null) for (final Payoff fPayoff : finalPayoff) willCrash |= fPayoff.willCrash(game); return willCrash; } @Override public void preprocess(final Game game) { if (finalPayoff != null) for (final Payoff fPayoff : finalPayoff) fPayoff.preprocess(game); } }
5,228
22.768182
85
java
Ludii
Ludii-master/Core/src/game/rules/end/Result.java
package game.rules.end; import java.io.Serializable; import java.util.BitSet; import game.Game; import game.types.play.ResultType; import game.types.play.RoleType; import other.BaseLudeme; import other.concept.Concept; import other.context.Context; import other.translation.LanguageUtils; /** * Gives the result when an ending rule is reached for a specific player/team. * * @author cambolbro and Eric.Piette */ public class Result extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The player or the team. */ private final RoleType who; /** The result type of the player or team. */ private final ResultType result; //------------------------------------------------------------------------- /** * @param who The player or the team. * @param result The result type of the player or team. * @example (result Mover Win) */ public Result ( final RoleType who, final ResultType result ) { this.who = who; this.result = result; } //------------------------------------------------------------------------- /** * @return role of player, else None or All. */ public RoleType who() { return who; } /** * @return Result type. */ public ResultType result() { return result; } /** * Allow eval for iterators. * * @param context */ public void eval(final Context context) { // Nothing to do. } //------------------------------------------------------------------------- @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); if (result != null) if (result.equals(ResultType.Draw)) concepts.set(Concept.Draw.id(), true); return concepts; } /** * @param game The game. * @return The long value corresponding of the state flags. */ @SuppressWarnings("static-method") public long gameFlags(final Game game) { return 0; } /** * @param game */ public void preprocess(final Game game) { // Placeholder for derived classes to implement. } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; // We check if the role is correct. final int indexOwnerPhase = who.owner(); if ((indexOwnerPhase < 1 && !who.equals(RoleType.All) && !who.equals(RoleType.Player) && !who.equals(RoleType.Mover) && !who.equals(RoleType.TeamMover) && !who.equals(RoleType.Next) && !who.equals(RoleType.Prev)) || indexOwnerPhase > game.players().count()) { game.addRequirementToReport( "A result is defined in the ending rules with an incorrect player: " + who + "."); missingRequirement = true; } if (result.equals(ResultType.Crash)) { game.addRequirementToReport("A crash result is used in an ending condition."); missingRequirement = true; } if (result.equals(ResultType.Abandon)) { game.addRequirementToReport("An abandon result is used in an ending condition."); missingRequirement = true; } return missingRequirement; } //------------------------------------------------------------------------- @Override public String toString() { return "[Result: " + who + " " + result + "]"; } @Override public String toEnglish(final Game game) { switch(result) { case Win: return LanguageUtils.RoleTypeAsText(who, false) + " wins"; case Loss: return LanguageUtils.RoleTypeAsText(who, false) + " loses"; case Draw: return "it's a draw"; default: throw new RuntimeException("Not implemented yet! [ResultType=" + result.name() + "]"); } } }
3,645
21.231707
89
java
Ludii
Ludii-master/Core/src/game/rules/end/package-info.java
/** * The {\tt end} rules describe the terminating conditions of the game and the result of the game. */ package game.rules.end;
131
25.4
98
java
Ludii
Ludii-master/Core/src/game/rules/meta/Automove.java
package game.rules.meta; import java.util.BitSet; import game.Game; import game.rules.phase.Phase; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import main.Constants; import other.MetaRules; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.move.MoveUtilities; /** * To apply automatically to the game all the legal moves only applicable to a * single site. * * @author Eric.Piette */ public class Automove extends MetaRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @example (automove) */ public Automove() { } //------------------------------------------------------------------------- @Override public void eval(final Context context) { context.game().metaRules().setAutomove(true); } /** * @param context The context. * @param move The original move. */ public static void apply(final Context context, final Move move) { final Game game = context.game(); final MetaRules metaRules = game.metaRules(); if (metaRules.automove()) { boolean repeatAutoMove = true; while (repeatAutoMove) { repeatAutoMove = false; if (context.state().isDecided() != Constants.UNDEFINED) context.state().setIsDecided(Constants.UNDEFINED); context.storeCurrentData(); // We need to save the data before to apply the move. final Move moveApplied = (Move) move.apply(context, true); final int mover = context.state().mover(); final int indexPhase = context.state().currentPhase(mover); final Phase phase = context.game().rules().phases()[indexPhase]; final Moves newLegalMoves = phase.play().moves().eval(context); for (int j = 0; j < newLegalMoves.moves().size() - 1; j++) { final Move newMove = newLegalMoves.get(j); final int site = newMove.toNonDecision(); int cpt = 1; for (int k = j + 1; k < newLegalMoves.moves().size(); k++) { if (site == newLegalMoves.moves().get(k).toNonDecision()) cpt++; } if (cpt != 1) { for (int k = 0; k < newLegalMoves.moves().size(); k++) { if (newLegalMoves.moves().get(k).toNonDecision() == site) { newLegalMoves.moves().remove(k); k--; } } j--; } } if (!newLegalMoves.moves().isEmpty()) { final Moves forcedMoves = new BaseMoves(null); for (int j = 0; j < newLegalMoves.moves().size(); j++) MoveUtilities.chainRuleCrossProduct(context, forcedMoves, null, newLegalMoves.moves().get(j), false); move.then().add(forcedMoves); repeatAutoMove = true; } moveApplied.undo(context, true); // We undo the move. } } } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { return 0; } @Override public boolean isStatic() { return true; } @Override public void preprocess(final Game game) { // Nothing to do. } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.set(Concept.AutoMove.id(), true); return concepts; } @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 Automove)) return false; return true; } @Override public String toEnglish(final Game game) { return "Metarule: apply automatically to the game all the legal moves only applicable to a single site"; } }
3,638
21.602484
107
java
Ludii
Ludii-master/Core/src/game/rules/meta/Gravity.java
package game.rules.meta; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import annotations.Opt; import game.Game; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.play.GravityType; import game.util.directions.AbsoluteDirection; import game.util.graph.Step; import main.Constants; import other.MetaRules; import other.action.Action; import other.action.move.move.ActionMove; import other.concept.Concept; import other.context.Context; import other.context.TempContext; import other.move.Move; import other.state.container.ContainerState; import other.topology.Topology; /** * To apply a certain type of gravity after making a move. * * @author Eric.Piette */ public class Gravity extends MetaRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * The gravity type. */ final GravityType type; /** * @param type The type of gravity [PyramidalDrop]. * * @example (gravity) */ public Gravity ( @Opt final GravityType type ) { this.type = (type == null) ? GravityType.PyramidalDrop : type; } //------------------------------------------------------------------------- @Override public void eval(final Context context) { context.game().metaRules().setGravityType(type); } /** * @param context The context. * @param move The original move. */ public static void apply(final Context context, final Move move) { final Game game = context.game(); final MetaRules metaRules = game.metaRules(); if (metaRules.gravityType() != null) { if (metaRules.gravityType().equals(GravityType.PyramidalDrop)) { final Topology topology = context.topology(); boolean pieceDropped = false; final Move droppedMove = new Move(new ArrayList<Action>()); final Context newContext = new TempContext(context); game.applyInternal(newContext, move, false); do { pieceDropped = false; for (int site = 0; site < topology.vertices().size(); site++) { final ContainerState cs = newContext.containerState(newContext.containerId()[site]); if (cs.what(site, SiteType.Vertex) != 0) { final List<game.util.graph.Step> steps = topology.trajectories().steps(SiteType.Vertex, site, SiteType.Vertex, AbsoluteDirection.Downward); for (final Step step : steps) { final int toSite = step.to().id(); if (cs.what(toSite, SiteType.Vertex) == 0) { final Action action = ActionMove.construct(SiteType.Vertex, site, 0, SiteType.Vertex, toSite, 0, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, false); final Move moveToApply = new Move(action); moveToApply.apply(newContext, false); droppedMove.actions().add(action); pieceDropped = true; break; } } } if (pieceDropped) break; } } while (pieceDropped); final Moves droppedMoves = new BaseMoves(null); droppedMoves.moves().add(droppedMove); move.then().add(droppedMoves); } } } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { return 0; } @Override public boolean isStatic() { return true; } @Override public void preprocess(final Game game) { // Nothing to do. } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.set(Concept.CopyContext.id(), true); return concepts; } @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 Gravity)) return false; return true; } }
3,873
22.621951
176
java
Ludii
Ludii-master/Core/src/game/rules/meta/Meta.java
package game.rules.meta; import java.io.Serializable; import annotations.Or; import other.BaseLudeme; import other.context.Context; /** * Defines a metarule defined before play that supersedes all other rules. * * @author cambolbro * */ public class Meta extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The metarules. */ private final MetaRule[] rules; //------------------------------------------------------------------------- /** * @param rules A collection of metarules. * @param rule A single metarule. * * @example (meta (swap)) */ public Meta ( @Or final MetaRule[] rules, @Or final MetaRule rule ) { int numNonNull = 0; if (rules != null) numNonNull++; if (rule != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException("Exactly one Or parameter must be non-null."); if (rules != null) this.rules = rules; else { this.rules = new MetaRule[1]; this.rules[0] = rule; } } //------------------------------------------------------------------------- /** * @return The metarules. */ public MetaRule[] rules() { return rules; } //------------------------------------------------------------------------- /** * Eval the meta rules. * * @param context The context. */ public void eval(final Context context) { for (final MetaRule rule : rules) rule.eval(context); } }
1,530
18.628205
84
java
Ludii
Ludii-master/Core/src/game/rules/meta/MetaRule.java
package game.rules.meta; import game.rules.Rule; import other.BaseLudeme; /** * Metarule defined before play that supersedes all other rules. * * @author cambolbro */ public abstract class MetaRule extends BaseLudeme implements Rule { private static final long serialVersionUID = 1L; }
295
17.5
65
java
Ludii
Ludii-master/Core/src/game/rules/meta/PassEnd.java
package game.rules.meta; import java.util.BitSet; import game.Game; import game.types.play.PassEndType; import game.types.state.GameType; import other.context.Context; /** * To apply a certain end result to all players if all players pass their turns. * * @author Eric.Piette */ public class PassEnd extends MetaRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * The passEnd type. */ final PassEndType type; /** * @param type The type of passEnd. * * @example (passEnd NoEnd) */ public PassEnd(final PassEndType type) { this.type = type; } //------------------------------------------------------------------------- @Override public void eval(final Context context) { // Nothing to do. } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { return type == PassEndType.NoEnd ? GameType.NotAllPass : 0l; } @Override public boolean isStatic() { return true; } @Override public void preprocess(final Game game) { // Nothing to do. } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); return concepts; } @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 PassEnd)) return false; return true; } }
1,518
16.067416
80
java
Ludii
Ludii-master/Core/src/game/rules/meta/Pin.java
package game.rules.meta; import java.util.BitSet; import java.util.List; import game.Game; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.play.PinType; import game.util.directions.AbsoluteDirection; import game.util.graph.Step; import other.MetaRules; import other.action.Action; import other.action.ActionType; import other.context.Context; import other.move.Move; import other.state.container.ContainerState; /** * To filter some remove moves in case some pieces can not be removed because of pieces on top of them. * * @author Eric.Piette */ public class Pin extends MetaRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * The pin type. */ final PinType type; /** * @param type The type of pin. * * @example (pin SupportMultiple) */ public Pin(final PinType type) { this.type = type; } //------------------------------------------------------------------------- @Override public void eval(final Context context) { context.game().metaRules().setPinType(type); } /** * @param context The context. * @param legalMoves The original legal moves. */ public static void apply(final Context context, final Moves legalMoves) { final Game game = context.game(); final MetaRules metaRules = game.metaRules(); final PinType pinType = metaRules.pinType(); if (pinType != null) { if (pinType.equals(PinType.SupportMultiple)) { for (int indexMove = legalMoves.moves().size() - 1; indexMove >= 0; indexMove--) { final Move move = legalMoves.moves().get(indexMove); boolean forbiddenMove = false; for(final Action action : move.actions()) if (action != null && action.actionType().equals(ActionType.Remove)) { final int siteToRemove = action.to(); final ContainerState cs = context.containerState(context.containerId()[siteToRemove]); if (cs.what(siteToRemove, SiteType.Vertex) != 0) { final List<game.util.graph.Step> steps = game.board().topology().trajectories() .steps(SiteType.Vertex, siteToRemove, SiteType.Vertex, AbsoluteDirection.Upward); int numOccupiedUpWardSites = 0; for (final Step step : steps) { final int toSite = step.to().id(); if (cs.what(toSite, SiteType.Vertex) != 0) numOccupiedUpWardSites++; } if (numOccupiedUpWardSites > 1) { forbiddenMove = true; break; } } } if (forbiddenMove) legalMoves.moves().remove(indexMove); } } } } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { return 0; } @Override public boolean isStatic() { return true; } @Override public void preprocess(final Game game) { // Nothing to do. } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); return concepts; } @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 Pin)) return false; return true; } }
3,299
21.44898
103
java
Ludii
Ludii-master/Core/src/game/rules/meta/Swap.java
package game.rules.meta; import java.util.BitSet; import game.Game; import game.functions.ints.IntConstant; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.effect.state.swap.players.SwapPlayers; import game.types.state.GameType; import main.Constants; import other.MetaRules; import other.concept.Concept; import other.context.Context; import other.trial.Trial; /** * To activate the swap rule. * * @author Eric.Piette */ public class Swap extends MetaRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @example (swap) */ public Swap() { } //------------------------------------------------------------------------- @Override public void eval(final Context context) { // Do nothing } /** * @param context The context. * @param legalMoves The original legal moves. */ public static void apply(final Context context, final Moves legalMoves) { final Game game = context.game(); final Trial trial = context.trial(); final int mover = context.state().mover(); final MetaRules metaRules = game.metaRules(); if (metaRules.usesSwapRule() && trial.moveNumber() == context.game().players().count() - 1) { final int moverLastTurn = context.trial().lastTurnMover(mover); if(mover != moverLastTurn && moverLastTurn != Constants.UNDEFINED) legalMoves.moves() .addAll(new SwapPlayers(new IntConstant(mover), null, new IntConstant(moverLastTurn), null, null) .eval(context).moves()); } } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { return GameType.UsesSwapRule; } @Override public boolean isStatic() { return true; } @Override public void preprocess(final Game game) { // Nothing to do } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.set(Concept.SwapPlayersDecision.id(), true); concepts.set(Concept.SwapOption.id(), true); return concepts; } @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 Swap)) return false; return true; } }
2,335
20.431193
103
java
Ludii
Ludii-master/Core/src/game/rules/meta/package-info.java
/** * The {\tt meta} rules describe higher-level rules applied across the entire game. */ package game.rules.meta;
117
22.6
83
java
Ludii
Ludii-master/Core/src/game/rules/meta/no/No.java
package game.rules.meta.no; import annotations.Opt; import game.Game; import game.rules.meta.MetaRule; import game.rules.meta.no.repeat.NoRepeat; import game.rules.meta.no.simple.NoSuicide; import game.types.play.RepetitionType; import other.context.Context; /** * Defines a no meta rules to forbid certain moves. * * @author Eric.Piette */ @SuppressWarnings("javadoc") public final class No extends MetaRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * For specifying a particular type of repetition that is forbidden in the game. * * @param type Type of repetition to forbid [Positional]. * @param repetitionType Type of repetition to forbid [Positional]. * * @example (no Repeat PositionalInTurn) */ public static MetaRule construct ( final NoRepeatType type, @Opt final RepetitionType repetitionType ) { switch (type) { case Repeat: return new NoRepeat(repetitionType); default: break; } // We should never reach that except if we forget some codes. throw new IllegalArgumentException("No(): A NoRepeatType is not implemented."); } /** * For specifying that a move leading to a direct loss is forbidden in the game. * * @param type Type of suicide. * * @example (no Suicide) */ public static MetaRule construct ( final NoSimpleType type ) { switch (type) { case Suicide: return new NoSuicide(); default: break; } // We should never reach that except if we forget some codes. throw new IllegalArgumentException("No(): A NoSimpleType is not implemented."); } private No() { // Make grammar pick up construct() and not default constructor } //------------------------------------------------------------------------- @Override public boolean isStatic() { // Should never be there return false; } @Override public long gameFlags(final Game game) { // Should never be there return 0L; } @Override public void preprocess(final Game game) { // Nothing to do. } @Override public void eval(Context context) { // Nothing to do. } //------------------------------------------------------------------------- }
2,263
19.770642
81
java
Ludii
Ludii-master/Core/src/game/rules/meta/no/NoRepeatType.java
package game.rules.meta.no; /** * Defines the types of no repeat meta rules. */ public enum NoRepeatType { /** Makes a particular type of repetition that is forbidden in the game. */ Repeat, }
198
17.090909
76
java
Ludii
Ludii-master/Core/src/game/rules/meta/no/NoSimpleType.java
package game.rules.meta.no; /** * Defines the types of meta rules with no parameters. */ public enum NoSimpleType { /** Makes all moves leading directly to lose forbidden. */ Suicide, }
191
16.454545
59
java
Ludii
Ludii-master/Core/src/game/rules/meta/no/package-info.java
/** * To specifies rules not allowed across the entire game. */ package game.rules.meta.no;
94
18
57
java
Ludii
Ludii-master/Core/src/game/rules/meta/no/repeat/NoRepeat.java
package game.rules.meta.no.repeat; import java.util.BitSet; import annotations.Hide; import annotations.Opt; import game.Game; import game.rules.meta.MetaRule; import game.types.play.RepetitionType; import game.types.state.GameType; import other.MetaRules; import other.concept.Concept; import other.context.Context; import other.move.Move; /** * Specifies a particular type of repetition that is forbidden in the game. * * @author Eric.Piette * * @remarks The Infinite option disallows players from making consecutive * sequences of moves that would lead to the same state twice, which * would indicate the start of an infinite cycle of moves. */ @Hide public class NoRepeat extends MetaRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- private final RepetitionType type; //------------------------------------------------------------------------- /** * @param type Type of repetition to forbid [Positional]. */ public NoRepeat ( @Opt final RepetitionType type ) { this.type = (type == null) ? RepetitionType.Positional : type; } //------------------------------------------------------------------------- @Override public void eval(final Context context) { context.game().metaRules().setRepetitionType(type); } /** * @param context The context. * @param move The move to check. * @return True if the given move does not reach a state previously reached. */ public static boolean apply(final Context context, final Move move) { final Game game = context.game(); final MetaRules metaRules = game.metaRules(); final RepetitionType type = metaRules.repetitionType(); if (type != null) { if (move.isPass()) return true; context.storeCurrentData(); // We need to save the data before to apply the move. // 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("Applying move: " + move); // } final Move moveApplied = (Move) move.apply(context, true); boolean noRepeat = true; switch (type) { case PositionalInTurn: { noRepeat = !context.trial().previousStateWithinATurn().contains(context.state().stateHash()); break; } case SituationalInTurn: { noRepeat = !context.trial().previousStateWithinATurn().contains(context.state().fullHash()); break; } case Positional: { noRepeat = !context.trial().previousState().contains(context.state().stateHash()); break; } case Situational: { noRepeat = !context.trial().previousState().contains(context.state().fullHash()); break; } default: break; } // 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("Undoing move: " + move); // } moveApplied.undo(context, true); // We undo the move. return noRepeat; } return true; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = 0l; if (type == RepetitionType.Positional) gameFlags |= GameType.RepeatPositionalInGame; if (type == RepetitionType.PositionalInTurn) gameFlags |= GameType.RepeatPositionalInTurn; if (type == RepetitionType.Situational) gameFlags |= GameType.RepeatSituationalInGame; if (type == RepetitionType.SituationalInTurn) gameFlags |= GameType.RepeatSituationalInTurn; return gameFlags; } @Override public boolean isStatic() { return true; } @Override public void preprocess(final Game game) { // Nothing to do. } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); if (type == RepetitionType.PositionalInTurn) concepts.set(Concept.TurnKo.id(), true); else if (type == RepetitionType.Positional) concepts.set(Concept.PositionalSuperko.id(), true); else if (type == RepetitionType.SituationalInTurn) concepts.set(Concept.SituationalTurnKo.id(), true); else if (type == RepetitionType.Situational) concepts.set(Concept.SituationalSuperko.id(), true); return concepts; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + type.hashCode(); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof NoRepeat)) return false; final NoRepeat other = (NoRepeat) obj; return type.equals(other.type); } }
5,047
24.24
102
java
Ludii
Ludii-master/Core/src/game/rules/meta/no/simple/NoSuicide.java
package game.rules.meta.no.simple; import java.util.BitSet; import annotations.Hide; import game.Game; import game.rules.meta.MetaRule; import other.MetaRules; import other.context.Context; import other.context.TempContext; import other.move.Move; /** * Specifies a particular type of repetition that is forbidden in the game. * * @author Eric.Piette * * @remarks The Infinite option disallows players from making consecutive * sequences of moves that would lead to the same state twice, which * would indicate the start of an infinite cycle of moves. */ @Hide public class NoSuicide extends MetaRule { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * Constructor. */ public NoSuicide() { } //------------------------------------------------------------------------- @Override public void eval(final Context context) { context.game().metaRules().setNoSuicide(true); } /** * @param context The context. * @param move The move to check. * @return True if the given move does not reach a state previously reached. */ public static boolean apply(final Context context, final Move move) { final Game game = context.game(); final MetaRules metaRules = game.metaRules(); if (metaRules.usesNoSuicide()) { final Context newContext = new TempContext(context); game.applyInternal(newContext, move, false); final boolean moverActive = newContext.active(context.state().mover()); if(moverActive) return true; else return !newContext.losers().contains(context.state().mover()); } return true; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = 0l; return gameFlags; } @Override public boolean isStatic() { return true; } @Override public void preprocess(final Game game) { // Nothing to do. } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); return concepts; } @Override public int hashCode() { int result = 1; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof NoSuicide)) return false; return true; } }
2,348
19.787611
77
java
Ludii
Ludii-master/Core/src/game/rules/phase/NextPhase.java
package game.rules.phase; import java.util.BitSet; import annotations.Opt; import annotations.Or; import game.Game; import game.functions.booleans.BooleanConstant; import game.functions.booleans.BooleanConstant.FalseConstant; import game.functions.booleans.BooleanFunction; import game.functions.ints.BaseIntFunction; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.board.Id; import game.types.play.RoleType; import main.Constants; import other.context.Context; /** * Enables a player or all the players to proceed to another phase of the game. * * @author Eric.Piette and cambolbro * * @remarks If no phase is specified, moves to the next phase in the list, * wrapping back to the first phase if needed. * The ludeme returns Undefined (-1) if the condition is false or if * the named phase does not exist. */ public final class NextPhase extends BaseIntFunction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Index of the player to go to another phase. N+1 if this is all. */ private final IntFunction who; /** Condition to reach a phase. */ private final BooleanFunction cond; /** Name of the phase to reach. */ private final String phaseName; //------------------------------------------------------------------------- /** * @param role The roleType of the player [Shared]. * @param indexPlayer The index of the player. * @param cond The condition to satisfy to go to another phase [True]. * @param phaseName The name of the phase. * * @example (nextPhase Mover (= (count Moves) 10) "Movement") */ public NextPhase ( @Opt @Or final RoleType role, @Opt @Or final game.util.moves.Player indexPlayer, @Opt final BooleanFunction cond, @Opt final String phaseName ) { int numNonNull = 0; if (role != null) numNonNull++; if (indexPlayer != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException("Zero or one Or parameter must be non-null."); this.cond = (cond == null) ? new BooleanConstant(true) : cond; this.phaseName = phaseName; if (indexPlayer != null) this.who = indexPlayer.index(); else if (role != null) this.who = RoleType.toIntFunction(role); else this.who = new Id(null, RoleType.Shared); } //------------------------------------------------------------------------- @Override public final int eval(final Context context) { if (context.game().rules().phases() == null) return Constants.UNDEFINED; final Phase[] phases = context.game().rules().phases(); if (cond.eval(context)) { // Return the next phase of the player if no specific name defined if (phaseName == null) { final int pid = who.eval(context); final int currentPhase = (pid == context.game().players().size()) ? context.state().currentPhase(context.state().mover()) : context.state().currentPhase(pid); return (currentPhase + 1) % phases.length; } else { for (int phaseId = 0; phaseId < phases.length; phaseId++) { final Phase phase = phases[phaseId]; if (phase.name().equals(phaseName)) return phaseId; } } throw new IllegalArgumentException("BUG: Phase " + phaseName + " unfounded."); } return Constants.UNDEFINED; } //------------------------------------------------------------------------- /** * @return The player concerned by that nextPhase ludeme. */ public IntFunction who() { return who; } /** * @return The name of the next phase. */ public String phaseName() { return phaseName; } //------------------------------------------------------------------------- @Override public boolean isStatic() { return cond.isStatic() && who.isStatic(); } @Override public long gameFlags(final Game game) { return cond.gameFlags(game) | who.gameFlags(game); } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(cond.concepts(game)); concepts.or(who.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(cond.writesEvalContextRecursive()); writeEvalContext.or(who.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(cond.readsEvalContextRecursive()); readEvalContext.or(who.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= cond.missingRequirement(game); missingRequirement |= who.missingRequirement(game); if (who instanceof IntConstant) { final int whoValue = ((IntConstant) who).eval(null); if (whoValue < 1 || whoValue > game.players().size()) { game.addRequirementToReport("A wrong player index is used in (nextPhase ...)."); missingRequirement = true; } } if (cond instanceof FalseConstant) { game.addRequirementToReport("The condition of a (nextPhase ...) ludeme is \"false\" which is wrong."); missingRequirement = true; } return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= cond.willCrash(game); willCrash |= who.willCrash(game); return willCrash; } @Override public void preprocess(final Game game) { cond.preprocess(game); who.preprocess(game); } //------------------------------------------------------------------------- }
5,786
25.18552
105
java
Ludii
Ludii-master/Core/src/game/rules/phase/Phase.java
package game.rules.phase; import java.io.Serializable; import java.util.BitSet; import annotations.Opt; import annotations.Or; import game.Game; import game.mode.Mode; import game.rules.end.End; import game.rules.play.Play; import game.types.play.RoleType; import other.BaseLudeme; import other.playout.Playout; /** * Defines the phase of a game. * * @author Eric.Piette and cambolbro * @remarks A phase can be defined for only one player. */ public class Phase extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; /** Move logic. */ private Play play; /** End logic. */ private End end; /** Owner of the phase. */ private final RoleType role; /** Mode for this phase */ private final Mode mode; /** Name of the phase. */ private final String name; /** Conditions to reach another phase. */ private final NextPhase[] nextPhase; /** Playout implementation to use inside this phase */ private Playout playout; //------------------------------------------------------------------------- /** * @param name The name of the phase. * @param role The roleType of the owner of the phase [Shared]. * @param mode The mode of this phase within the game [mode defined for * whole game)]. * @param play The playing rules of this phase. * @param end The ending rules of this phase. * @param nextPhase The next phase of this phase. * @param nextPhases The next phases of this phase. * * @example (phase "Movement" (play (forEach Piece))) */ public Phase ( final String name, @Opt final RoleType role, @Opt final Mode mode, final Play play, @Opt final End end, @Opt @Or final NextPhase nextPhase, @Opt @Or final NextPhase[] nextPhases ) { this.name = name; this.role = (role == null) ? RoleType.Shared : role; this.mode = mode; this.play = play; this.end = end; int numNonNull = 0; if (nextPhase != null) numNonNull++; if (nextPhases != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException("Zero or one Or parameter must be non-null."); if (nextPhase != null) { this.nextPhase = new NextPhase[1]; this.nextPhase[0] = nextPhase; } else if (nextPhases != null) { this.nextPhase = nextPhases; } else { this.nextPhase = new NextPhase[0]; } } //------------------------------------------------------------------------- /** * @return Mode for this phase */ public Mode mode() { return mode; } /** * @return Play logic. */ public Play play() { return play; } /** * @return End logic. */ public End end() { return end; } /** * @return Name of the phase. */ public String name() { return name; } /** * @return Owner of the phase */ public RoleType owner() { return role; } /** * @return Conditions to reach another phase. */ public NextPhase[] nextPhase() { return nextPhase; } /** * Set the Play object * @param play */ public void setPlay(final Play play) { this.play = play; } /** * Set the End object * @param end */ public void setEnd(final End end) { this.end = end; } /** * @return Playout implementation for this phase */ public Playout playout() { return playout; } /** * Sets the playout implementation for this phase * @param playout */ public void setPlayout(final Playout playout) { this.playout = playout; } //--------------------------------------------------- /** * To preprocess the phase. * * @param game The game. */ public void preprocess(final Game game) { play.moves().preprocess(game); for (final NextPhase next : nextPhase()) next.preprocess(game); if (end() != null) end().preprocess(game); } /** * @param game The game. * @return The gameFlags of the phase. */ public long gameFlags(final Game game) { long gameFlags = play.moves().gameFlags(game); for (final NextPhase next : nextPhase()) gameFlags |= next.gameFlags(game); if (end() != null) gameFlags |= end().gameFlags(game); return gameFlags; } /** * @param game The game. * @return The gameFlags of the phase. */ @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(play.moves().concepts(game)); for (final NextPhase next : nextPhase()) concepts.or(next.concepts(game)); if (end() != null) concepts.or(end().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(play.moves().writesEvalContextRecursive()); for (final NextPhase next : nextPhase()) writeEvalContext.or(next.writesEvalContextRecursive()); if (end() != null) writeEvalContext.or(end().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(play.moves().readsEvalContextRecursive()); for (final NextPhase next : nextPhase()) readEvalContext.or(next.readsEvalContextRecursive()); if (end() != null) readEvalContext.or(end().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; if (game.rules().phases().length > 1) { // We check if the owner is correct. final int indexOwnerPhase = role.owner(); if ((indexOwnerPhase < 1 && !role.equals(RoleType.Shared)) || indexOwnerPhase > game.players().size()) { game.addRequirementToReport( "The phase \"" + name + "\" has an incorrect owner which is " + owner() + "."); missingRequirement = true; } else { final boolean[] playersInitPhase = new boolean[game.players().size()]; boolean phaseUsed = false; boolean nextPhaseIsReached = false; // We check if the phase can be reached. for (int i = 0; i < game.rules().phases().length; i++) { final Phase phase = game.rules().phases()[i]; final String phaseName = phase.name(); if (nextPhaseIsReached) { if (phaseName.equals(name)) { phaseUsed = true; break; } nextPhaseIsReached = false; } final RoleType rolePhase = phase.owner(); // The phase belongs to all the players. if (rolePhase.equals(RoleType.Shared)) { for (int pid = 1; pid <= game.players().count(); pid++) { if (!playersInitPhase[pid]) { if (phaseName.equals(name)) phaseUsed = true; break; } } for (int pid = 1; pid < game.players().count(); pid++) playersInitPhase[pid] = true; } else // The phase is for a particular player. { if (rolePhase.owner() < 1 || rolePhase.owner() > game.players().size()) continue; if (playersInitPhase[rolePhase.owner()] == false) { if (phaseName.equals(name)) { phaseUsed = true; break; } playersInitPhase[rolePhase.owner()] = true; } } // Check next phases. for (int j = 0; j < phase.nextPhase.length; j++) { final String nameNextPhase = phase.nextPhase[j].phaseName(); if (nameNextPhase == null) { nextPhaseIsReached = true; } else if (nameNextPhase.equals(name)) { phaseUsed = true; break; } } if (phaseUsed) break; } if (!phaseUsed) { game.addRequirementToReport( "The phase \"" + name + "\" is described but the phase is never used in the game."); missingRequirement = true; } } } missingRequirement |= play.moves().missingRequirement(game); for (final NextPhase next : nextPhase()) missingRequirement |= next.missingRequirement(game); if (end() != null) missingRequirement |= end().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= play.moves().willCrash(game); for (final NextPhase next : nextPhase()) willCrash |= next.willCrash(game); if (end() != null) willCrash |= end().willCrash(game); return willCrash; } }
8,350
21.210106
105
java
Ludii
Ludii-master/Core/src/game/rules/phase/package-info.java
/** * Games may be sub-divided into named {\it phases} for clarity. * Each phase can contain its own sub-rules, which override the rules for the broader game while in that phase. * Each phase can nominate a ``next'' phase to which control is relinquished under specified conditions. */ package game.rules.phase;
317
44.428571
111
java
Ludii
Ludii-master/Core/src/game/rules/play/Play.java
package game.rules.play; import java.io.Serializable; import game.Game; import game.rules.play.moves.Moves; import other.BaseLudeme; /** * Checks the playing rules of the game. * * @author cambolbro and Eric.Piette */ public final class Play extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The playing moves. */ private final Moves moves; //------------------------------------------------------------------------- /** * The playing rules of the game. * * @param moves The legal moves of the playing rules. * @example (play (forEach Piece)) */ public Play ( final Moves moves ) { this.moves = moves; } //------------------------------------------------------------------------- /** * @return The moves. */ public Moves moves() { return moves; } //------------------------------------------------------------------------- // Ludeme overrides @Override public String toEnglish(final Game game) { return moves.toEnglish(game); } //------------------------------------------------------------------------- }
1,198
18.655738
76
java
Ludii
Ludii-master/Core/src/game/rules/play/package-info.java
/** * The {\tt play} rules describe the actual rules of play, from the start to the end of each trial. */ package game.rules.play;
133
25.8
99
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/BaseMoves.java
package game.rules.play.moves; import annotations.Hide; import annotations.Opt; import game.Game; import game.rules.play.moves.nonDecision.effect.Then; import other.context.Context; /** * Placeholder object for creating default Moves objects without initialisation. * * @author cambolbro */ @Hide public class BaseMoves extends Moves { /** */ private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * The base Moves. * * @param then The subsequents of the moves. */ public BaseMoves ( @Opt final Then then ) { super(then); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { return this; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { return 0L; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); } //------------------------------------------------------------------------- }
1,159
16.575758
80
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/Moves.java
package game.rules.play.moves; import java.util.Iterator; import java.util.function.BiPredicate; import annotations.Opt; import game.Game; import game.rules.meta.no.repeat.NoRepeat; import game.rules.meta.no.simple.NoSuicide; import game.rules.play.moves.nonDecision.effect.Then; import game.types.state.GameType; import main.collections.FastArrayList; import other.BaseLudeme; import other.context.Context; import other.move.Move; import other.move.MovesIterator; /** * Returns a moves collection. * * @author cambolbro and Eric.Piette */ public abstract class Moves extends BaseLudeme implements GameType { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** List of Moves. */ private final FastArrayList<Move> moves = new FastArrayList<Move>(10); /** Consequent actions of moves. */ private Then then; /** If the move is a decision. */ private boolean isDecision = false; /** * Use for the simultaneous games, to apply the consequence when all the moves * of all the players are applied. */ private boolean applyAfterAllMoves = false; //------------------------------------------------------------------------- /** * @param then The subsequents of the moves. */ public Moves ( @Opt final Then then ) { this.then = then; } //------------------------------------------------------------------------- /** * @return The moves generated by moves. */ public FastArrayList<Move> moves() { return moves; } /** * @return The subsequents of the moves. */ public Then then() { return then; } /** * To set the then moves of the moves. * * @param then */ public void setThen(final Then then) { this.then = then; } /** * @return The number of moves. */ public int count() { return moves.size(); } /** * @param n * @return To get the move n in the list of moves. */ public Move get(final int n) { return moves.get(n); } //------------------------------------------------------------------------- /** * @param context * @return The result of applying this function in this context. */ public abstract Moves eval(final Context context); //------------------------------------------------------------------------- /** * @param context * @param target * @return True if this generator can generate moves in the given context * that would move towards "target" */ public boolean canMoveTo(final Context context, final int target) { final Iterator<Move> it = movesIterator(context); while (it.hasNext()) { if (it.next().toNonDecision() == target) return true; } return false; } //------------------------------------------------------------------------- @Override public void preprocess(final Game game) { if (then != null) then.moves().preprocess(game); } @Override public long gameFlags(final Game game) { long result = 0L; if (then != null) result |= then.moves().gameFlags(game); return result; } @Override public boolean isStatic() { if (then != null) return then.moves().isStatic(); return false; // TODO this should return true? } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); for (final Move m : moves) { if (sb.length() > 0) sb.append(", "); sb.append(m.toString()); } if (then != null) { sb.append(then); } return sb.toString(); } //------------------------------------------------------------------------- // WARNING: the below hashCode() and equals() implementations are WRONG! // All other Moves ludemes do not provide correct (or any) implementations! // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((consequents == null) ? 0 : consequents.hashCode()); // result = prime * result + ((moves == null) ? 0 : moves.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) // { // if (this == obj) // return true; // // if (obj == null) // return false; // // if (getClass() != obj.getClass()) // return false; // // final Moves other = (Moves) obj; // if (consequents == null) // { // if (other.consequents != null) // return false; // } // else if (!consequents.equals(other.consequents)) // { // return false; // } // // if (moves == null) // { // if (other.moves != null) // return false; // } // else if (!moves.equals(other.moves)) // { // return false; // } // // return true; // } //------------------------------------------------------------------------- /** * @return True if the moves is a constraint move. */ @SuppressWarnings("static-method") public boolean isConstraintsMoves() { return false; } /** * @return True if the moves returned have to be a decision moves. */ public boolean isDecision() { return isDecision; } /** * Set the moves to be a decision. */ public void setDecision() { isDecision = true; } /** * @return The applyAfterAllMoves. */ public boolean applyAfterAllMoves() { return applyAfterAllMoves; } /** * Set the flag applyAfterAllMoves. * * @param value The new value. */ public void setApplyAfterAllMoves(final boolean value) { applyAfterAllMoves = value; } //------------------------------------------------------------------------- /** * @param context * @return Iterator for iterating through moves in given context. * Base class implementation just computes full list of legal moves, * and allows iterating through it afterwards. */ public MovesIterator movesIterator(final Context context) { final FastArrayList<Move> generatedMoves = eval(context).moves(); return new MovesIterator(){ private int cursor = 0; @Override public boolean hasNext() { return cursor < generatedMoves.size(); } @Override public Move next() { return generatedMoves.get(cursor++); } @Override public boolean canMoveConditionally(final BiPredicate<Context, Move> predicate) { for (final Move m : generatedMoves) if (predicate.test(context, m)) return true; return false; } }; } /** * @param context * @return True if there is at least one legal move in given context */ public boolean canMove(final Context context) { return movesIterator(context).canMoveConditionally( (final Context c, final Move m) -> { final boolean noRepeat = NoRepeat.apply(c, m); final boolean noSuicide = NoSuicide.apply(c, m); return noRepeat && noSuicide; }); } }
6,767
19.44713
83
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/package-info.java
/** * @chapter Move ludemes define the legal moves for a given game state. * We distinguish between: * \begin{itemize} * \item {\it decision moves} that involve a choice by the player, * \item {\it effect moves} that are applied as the result of a decision, and * \item {\it move generators} that iterate over the playable sites. * \end{itemize} */ package game.rules.play.moves;
443
39.363636
86
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/Decision.java
package game.rules.play.moves.decision; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.effect.Then; import other.context.Context; //----------------------------------------------------------------------------- /** * Defines moves that involve a decision by the player. * * @author Eric.Piette and cambolbro */ public abstract class Decision extends Moves { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @param then The subsequents of the moves. */ public Decision(final Then then) { super(then); } //------------------------------------------------------------------------- /** * Trick ludeme into joining the grammar. */ @Override public Moves eval(final Context context) { return null; } //------------------------------------------------------------------------- }
922
20.97619
79
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/Move.java
package game.rules.play.moves.decision; import annotations.And; import annotations.Name; import annotations.Opt; import annotations.Or; import annotations.Or2; import game.Game; import game.functions.booleans.BooleanFunction; import game.functions.intArray.IntArrayFunction; import game.functions.intArray.math.Difference; import game.functions.ints.IntFunction; import game.functions.range.RangeFunction; import game.functions.region.RegionFunction; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.effect.Add; import game.rules.play.moves.nonDecision.effect.Bet; import game.rules.play.moves.nonDecision.effect.Claim; import game.rules.play.moves.nonDecision.effect.FromTo; import game.rules.play.moves.nonDecision.effect.Hop; import game.rules.play.moves.nonDecision.effect.Leap; import game.rules.play.moves.nonDecision.effect.Pass; import game.rules.play.moves.nonDecision.effect.PlayCard; import game.rules.play.moves.nonDecision.effect.Promote; import game.rules.play.moves.nonDecision.effect.Propose; import game.rules.play.moves.nonDecision.effect.Remove; import game.rules.play.moves.nonDecision.effect.Select; import game.rules.play.moves.nonDecision.effect.Shoot; import game.rules.play.moves.nonDecision.effect.Slide; import game.rules.play.moves.nonDecision.effect.Step; import game.rules.play.moves.nonDecision.effect.Then; import game.rules.play.moves.nonDecision.effect.Vote; import game.rules.play.moves.nonDecision.effect.set.SetNextPlayerType; import game.rules.play.moves.nonDecision.effect.set.SetRotationType; import game.rules.play.moves.nonDecision.effect.set.SetTrumpType; import game.rules.play.moves.nonDecision.effect.set.direction.SetRotation; import game.rules.play.moves.nonDecision.effect.set.nextPlayer.SetNextPlayer; import game.rules.play.moves.nonDecision.effect.set.suit.SetTrumpSuit; import game.rules.play.moves.nonDecision.effect.state.swap.SwapPlayersType; import game.rules.play.moves.nonDecision.effect.state.swap.SwapSitesType; import game.rules.play.moves.nonDecision.effect.state.swap.players.SwapPlayers; import game.rules.play.moves.nonDecision.effect.state.swap.sites.SwapPieces; import game.types.board.SiteType; import game.types.board.StepType; import game.types.play.RoleType; import game.types.play.WhenType; import game.util.directions.AbsoluteDirection; import game.util.moves.From; import game.util.moves.Piece; import game.util.moves.Player; import game.util.moves.To; import other.context.Context; /** * Defines a decision move. * * @author Eric.Piette */ @SuppressWarnings("javadoc") public final class Move extends Decision { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * For deciding to swap two players. * * @param moveType The type of move. * @param swapType The type of property to take. * @param player1 The index of the first player. * @param role1 The role of the first player. * @param player2 The index of the second player. * @param role2 The role of the second player. * @param then The moves applied after that move is applied. * * @example (move Swap Players P1 P2) */ public static Moves construct ( final MoveSwapType moveType, final SwapPlayersType swapType, @And @Or final IntFunction player1, @And @Or final RoleType role1, @And @Or2 final IntFunction player2, @And @Or2 final RoleType role2, @Opt final Then then ) { int numNonNull = 0; if (player1 != null) numNonNull++; if (role1 != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException("Move(): With MoveSwapType and SwapPlayersType exactly one player1 or role1 parameter must be non-null."); int numNonNull2 = 0; if (player2 != null) numNonNull2++; if (role2 != null) numNonNull2++; if (numNonNull2 != 1) throw new IllegalArgumentException("Move(): With MoveSwapType and SwapPlayersType exactly one player2 or role2 parameter must be non-null."); Moves moves = null; switch (moveType) { case Swap: moves = new SwapPlayers(player1, role1, player2, role2, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveSwapType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to swap two pieces. * * @param moveType The type of move. * @param swapType The type of property to take. * @param locA The first location [(lastFrom)]. * @param locB The second location [(lastTo)]. * @param then The moves applied after that move is applied. * * @example (move Swap Pieces (last To) (last From)) */ public static Moves construct ( final MoveSwapType moveType, final SwapSitesType swapType, @Opt final IntFunction locA, @Opt final IntFunction locB, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Swap: moves = new SwapPieces(locA, locB,then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveSwapType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to remove components. * * @param moveType The type of move. * @param type The graph element type of the location [Cell (or * Vertex if the main board uses this)]. * @param locationFunction The location to remove a piece. * @param regionFunction The locations to remove a piece. * @param level The level to remove a piece [top level]. * @param at When to perform the removal [immediately]. * @param count The number of pieces to remove [1]. * @param then The moves applied after that move is applied. * * @example (move Remove (last To)) */ public static Moves construct ( final MoveRemoveType moveType, @Opt final SiteType type, @Or final IntFunction locationFunction, @Or final RegionFunction regionFunction, @Opt @Name final IntFunction level, @Opt @Name final WhenType at, @Opt @Name final IntFunction count, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Remove: moves = new Remove(type, locationFunction, regionFunction, level, at, count, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveRemoveType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding the trump suit of a card game. * * @param moveType The type of move. * @param setType The type of property to set. * @param suit The suit to choose. * @param suits The possible suits to choose. * @param then The moves applied after that move is applied. * * @example (move Set TrumpSuit (card Suit at:(handSite Shared))) * */ public static Moves construct ( final MoveSetType moveType, final SetTrumpType setType, @Or final IntFunction suit, @Or final Difference suits, @Opt final Then then ) { int numNonNull = 0; if (suit != null) numNonNull++; if (suits != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException( "Move(): With SetSuitType only one suit or suits parameter must be non-null."); Moves moves = null; switch (setType) { case TrumpSuit: moves = new SetTrumpSuit(suit, suits, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A SetSuitType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding the next player. * * @param moveType The type of move. * @param setType The type of property to set. * @param who The data of the next player. * @param nextPlayers The indices of the next players. * @param then The moves applied after that move is applied. * * @example (move Set NextPlayer (player (mover))) * */ public static Moves construct ( final MoveSetType moveType, final SetNextPlayerType setType, @Or final Player who, @Or final IntArrayFunction nextPlayers, @Opt final Then then ) { int numNonNull = 0; if (who != null) numNonNull++; if (nextPlayers != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException( "Move(): With SetPlayerType only one who or nextPlayers parameter can be non-null."); Moves moves = null; switch (setType) { case NextPlayer: moves = new SetNextPlayer(who, nextPlayers, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A SetPlayerType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to set the rotation. * * @param moveType The type of move. * @param setType The type of property to set. * @param to Description of the ``to'' location [(to (from))]. * @param directions The index of the possible new directions. * @param direction The index of the possible new direction. * @param previous True to allow movement to the left [True]. * @param next True to allow movement to the right [True]. * @param then The moves applied after that move is applied. * * @example (move Set Rotation) * * @example (move Set Rotation (to (last To)) next:False) */ public static Moves construct ( final MoveSetType moveType, final SetRotationType setType, @Opt final game.util.moves.To to, @Opt @Or final IntFunction[] directions, @Opt @Or final IntFunction direction, @Opt @Name final BooleanFunction previous, @Opt @Name final BooleanFunction next, @Opt final Then then ) { int numNonNull = 0; if (directions != null) numNonNull++; if (direction != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException( "Move(): With SetRotationType zero or one directions or direction parameter must be non-null."); Moves moves = null; switch (setType) { case Rotation: moves = new SetRotation(to, directions, direction, previous, next, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A SetRotationType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to step. * * @param moveType The type of move. * @param from Description of ``from'' location [(from)]. * @param directions The directions of the move [Adjacent]. * @param to Description of the ``to'' location. * @param stack True if the move is applied to a stack [False]. * @param then Moves to apply after this one. * * @example (move Step (to if:(is Empty (to))) ) * * @example (move Step Forward (to if:(is Empty (to))) ) * * @example (move Step (directions {FR FL}) (to if:(or (is Empty (to)) (is * Enemy (who at:(to)))) (apply (remove (to)))) ) */ public static Moves construct ( final MoveStepType moveType, @Opt final game.util.moves.From from, @Opt final game.util.directions.Direction directions, final game.util.moves.To to, @Opt @Name final Boolean stack, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Step: moves = new Step(from, directions, to, stack, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveStepType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to slide. * * @param moveType The type of move. * @param from Description of the ``from'' location [(from)]. * @param track The track on which to slide. * @param directions The directions of the move [Adjacent]. * @param between Description of the location(s) between ``from'' and ``to''. * @param to Description of the ``to'' location. * @param stack True if the move is applied to a stack [False]. * @param then Moves to apply after this one. * * @example (move Slide) * * @example (move Slide Orthogonal) * * @example (move Slide "AllTracks" (between if:(or (= (between) (from)) (is In * (between) (sites Empty)) ) ) (to if:(is Enemy (who at:(to))) (apply * (remove (to))) ) (then (set Counter)) ) * */ public static Moves construct ( final MoveSlideType moveType, @Opt final game.util.moves.From from, @Opt final String track, @Opt final game.util.directions.Direction directions, @Opt final game.util.moves.Between between, @Opt final To to, @Opt @Name final Boolean stack, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Slide: moves = new Slide(from, track, directions, between, to, stack, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveSlideType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to shoot. * * @param moveType The type of move. * @param what The data about the piece to shoot. * @param from The ``from'' location [(lastTo)]. * @param dirn The direction to follow [Adjacent]. * @param between The location(s) between ``from'' and ``to''. * @param to The condition on the ``to'' location to allow shooting [(to * if:(in (to) (sites Empty)))]. * @param then The moves applied after that move is applied. * * @example (move Shoot (piece "Dot0")) * */ public static Moves construct ( final MoveShootType moveType, final Piece what, @Opt final From from, @Opt final AbsoluteDirection dirn, @Opt final game.util.moves.Between between, @Opt final To to, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Shoot: moves = new Shoot(what, from, dirn, between, to, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveShootType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to select sites. * * @param moveType The type of move. * @param from Describes the ``from'' location to select [(from)]. * @param to Describes the ``to'' location to select. * @param mover The mover of the move. * @param then The moves applied after that move is applied. * * @example (move Select (from) (then (remove (last To)))) * * @example (move Select (from (sites Occupied by:Mover) if:(!= (state at:(to)) * 0) ) (to (sites Occupied by:Next) if:(!= (state at:(to)) 0) ) (then * (set State at:(last To) (% (+ (state at:(last From)) (state at:(last * To))) 5) ) ) ) * */ public static Moves construct ( final MoveSelectType moveType, final From from, @Opt final To to, @Opt final RoleType mover, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Select: moves = new Select(from, to, mover, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveSelectType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to vote or propose. * * @param moveType The type of move. * @param message The message. * @param messages The messages. * @param then The moves applied after that move is applied. * * @example (move Propose "End") * * @example (move Vote "End") * */ public static Moves construct ( final MoveMessageType moveType, @Or final String message, @Or final String[] messages, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Propose: moves = new Propose(message, messages, then); break; case Vote: moves = new Vote(message, messages, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveProposeType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to promote. * * @param moveType The type of move. * @param type The graph element type [default SiteType of the board]. * @param locationFn The location of the piece to promote [(to)]. * @param what The data about the promoted pieces. * @param who Data of the owner of the promoted piece. * @param role RoleType of the owner of the promoted piece. * @param then The moves applied after that move is applied. * * @example (move Promote (last To) (piece {"Queen" "Knight" "Bishop" "Rook"}) * Mover) * */ public static Moves construct ( final MovePromoteType moveType, @Opt final SiteType type, @Opt final IntFunction locationFn, final Piece what, @Opt @Or final Player who, @Opt @Or final RoleType role, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Promote: moves = new Promote(type, locationFn, what, who, role, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MovePromotionType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to pass or play a card. * * @param moveType The type of move. * @param then The moves applied after that move is applied. * * @example (move Pass) */ public static Moves construct ( final MoveSimpleType moveType, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Pass: moves = new Pass(then); break; case PlayCard: moves = new PlayCard(then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveSimpleType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to leap. * * @param moveType The type of move. * @param from The from location [(from)]. * @param walk The walk to follow. * @param forward True if the move can only move forward according to the * direction of the piece [False]. * @param rotations True if the move includes all the rotations of the walk * [True]. * @param to The data about the location to move. * @param then The moves applied after that move is applied. * * @example (move Leap { {F F R F} {F F L F} } (to if:(or (is Empty (to)) (is * Enemy (who at:(to)))) (apply (if (is Enemy (who at:(to))) (remove * (to) ) ) ) ) ) * */ public static Moves construct ( final MoveLeapType moveType, @Opt final game.util.moves.From from, final StepType[][] walk, @Opt @Name final BooleanFunction forward, @Opt @Name final BooleanFunction rotations, final To to, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Leap: moves = new Leap(from, walk, forward, rotations, to, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveLeapType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to hop. * * @param moveType The type of move. * @param from The data of the from location [(from)]. * @param directions The directions of the move [Adjacent]. * @param between The information about the locations between ``from'' and * ``to'' [(between if:True)]. * @param to The condition on the location to move. * @param stack True if the move has to be applied for stack [False]. * @param then The moves applied after that move is applied. * * @example (move Hop (between if:(is Enemy (who at:(between))) (apply (remove * (between))) ) (to if:(is Empty (to))) ) * * @example (move Hop Orthogonal (between if:(is Friend (who at:(between))) * (apply (remove (between))) ) (to if:(is Empty (to))) ) * */ public static Moves construct ( final MoveHopType moveType, @Opt final game.util.moves.From from, @Opt final game.util.directions.Direction directions, @Opt final game.util.moves.Between between, final To to, @Opt @Name final Boolean stack, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Hop: moves = new Hop(from, directions, between, to, stack, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveHopType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to move a piece. * * @param from The data of the ``from'' location [(from)]. * @param to The data of the ``to'' location. * @param count The number of pieces to move. * @param copy Whether to duplicate the piece rather than moving it [False]. * @param stack To move a complete stack [False]. * @param mover The mover of the move. * @param then The moves applied after that move is applied. * * @example (move (from (last To)) (to (last From))) * * @example (move (from (handSite Mover)) (to (sites Empty))) * * @example (move (from (to)) (to (sites Empty)) count:(count at:(to))) * * @example (move (from (handSite Shared)) (to (sites Empty)) copy:True ) * */ public static Moves construct ( final From from, final To to, @Opt @Name final IntFunction count, @Opt @Name final BooleanFunction copy, @Opt @Name final Boolean stack, @Opt final RoleType mover, @Opt final Then then ) { final Moves moves = new FromTo(from, to, count, copy, stack, mover, then); moves.setDecision(); return moves; } /** * For deciding to bet. * * @param moveType The type of move. * @param who The data about the player to bet. * @param role The RoleType of the player to bet. * @param range The range of the bet. * @param then The moves applied after that move is applied. * * @example (move Bet P1 (range 0 5)) * */ public static Moves construct ( final MoveBetType moveType, @Or final Player who, @Or final RoleType role, final RangeFunction range, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Bet: moves = new Bet(who, role, range, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveBetType is not implemented."); moves.setDecision(); return moves; } //------------------------------------------------------------------------- /** * For deciding to add a piece or claim a site. * * @param moveType The type of move. * @param what The data about the components to add. * @param to The data on the location to add. * @param count The number of components to add [1]. * @param stack True if the move has to be applied on a stack [False]. * @param then The moves applied after that move is applied. * * @example (move Add (to (sites Empty))) * * @example (move Claim (to Cell (site))) */ public static Moves construct ( final MoveSiteType moveType, @Opt final Piece what, final To to, @Opt @Name final IntFunction count, @Opt @Name final Boolean stack, @Opt final Then then ) { Moves moves = null; switch (moveType) { case Add: moves = new Add(what, to, count, stack, then); break; case Claim: moves = new Claim(what, to, then); break; default: break; } // We should never reach that except if we forget some codes. if (moves == null) throw new IllegalArgumentException("Move(): A MoveAddType is not implemented."); moves.setDecision(); return moves; } private Move() { super(null); // Ensure that compiler does pick up default constructor } @Override public Moves eval(final Context context) { // Should not be called, should only be called on subclasses throw new UnsupportedOperationException("Move.eval(): Should never be called directly."); } //------------------------------------------------------------------------- @Override public boolean isStatic() { // Should never be there return false; } @Override public long gameFlags(final Game game) { // Should never be there return 0L; } @Override public void preprocess(final Game game) { // Nothing to do. } @Override public boolean canMoveTo(Context context, int target) { // Should never be there throw new UnsupportedOperationException("Move.canMoveTo(): Should never be called directly."); } //------------------------------------------------------------------------- }
28,259
28.044193
144
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveBetType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to bet. */ public enum MoveBetType { /** Makes a bet move. */ Bet, }
169
14.454545
59
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveFromToType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to move a piece from a site * to another. */ public enum MoveFromToType { /** Makes a FromTo move. */ FromTo, }
213
16.833333
79
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveHopType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a hop move. */ public enum MoveHopType { /** Makes a Hop move. */ Hop, }
176
15.090909
66
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveLeapType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a leap move. */ public enum MoveLeapType { /** Makes a Leap move. */ Leap, }
180
15.454545
67
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveMessageType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move relative to a message. */ public enum MoveMessageType { /** Makes a propose move. */ Propose, /** Makes a vote move. */ Vote, }
217
14.571429
60
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MovePromoteType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a promotion move. */ public enum MovePromoteType { /** Makes a promotion move. */ Promote, }
196
16.909091
72
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveRemoveType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a remove move. */ public enum MoveRemoveType { /** Makes a remove move. */ Remove, }
188
16.181818
69
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveSelectType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a select move. */ public enum MoveSelectType { /** Makes a select move. */ Select, }
188
16.181818
69
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveSetType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a set move. */ public enum MoveSetType { /** Makes a set move. */ Set, }
176
15.090909
66
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveShootType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a shoot move. */ public enum MoveShootType { /** Makes a shoot move. */ Shoot, }
184
15.818182
68
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveSimpleType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to move with no parameters except the subsequents. */ public enum MoveSimpleType { /** Makes a pass move. */ Pass, /** Plays a card. */ PlayCard, }
251
17
102
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveSiteType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a single site. */ public enum MoveSiteType { /** Makes a add move. */ Add, /** Makes a claim move. */ Claim, }
217
14.571429
69
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveSlideType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a slide move. */ public enum MoveSlideType { /** Makes a slide move. */ Slide, }
184
15.818182
68
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveStepType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a step move. */ public enum MoveStepType { /** Makes a step move. */ Step, }
180
15.454545
67
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/MoveSwapType.java
package game.rules.play.moves.decision; /** * Defines the types of decision move corresponding to a swap move. */ public enum MoveSwapType { /** To Swap two pieces or two players. */ Swap, }
196
16.909091
67
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/decision/package-info.java
/** * To specify that a move is a decision move. */ package game.rules.play.moves.decision;
94
18
45
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/NonDecision.java
package game.rules.play.moves.nonDecision; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.effect.Then; import other.context.Context; /** * Defines moves that do not involve an immediate decision by the player. * * @author Eric.Piette and cambolbro * * @remarks Non-decision moves include move operators that might combine * further decision moves. */ public abstract class NonDecision extends Moves { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @param then The subsequents of the moves. */ public NonDecision(final Then then) { super(then); } //------------------------------------------------------------------------- /** * Trick ludeme into joining the grammar. */ @Override public Moves eval(final Context context) { return null; } //------------------------------------------------------------------------- }
981
21.837209
76
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Add.java
package game.rules.play.moves.nonDecision.effect; import java.util.Arrays; import java.util.BitSet; import annotations.Name; import annotations.Opt; import game.Game; import game.equipment.component.Component; import game.functions.booleans.BooleanFunction; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.state.Mover; import game.functions.region.RegionFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import game.util.equipment.Region; import game.util.moves.Piece; import game.util.moves.To; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.move.ActionAdd; import other.action.move.ActionInsert; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.Move; import other.move.MoveUtilities; import other.state.container.ContainerState; import other.trial.Trial; /** * Places one or more component(s) at a collection of sites or at one specific * site. * * @author cambolbro and Eric.Piette * * @remarks The ``to'' location is not updated until the move is made. */ public final class Add extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Which local state. */ private final IntFunction localState; /** Which components. */ private IntFunction[] components; /** Which region. */ private final RegionFunction region; /** Which site. */ private final IntFunction site; /** Which site. */ private final IntFunction level; /** Which site. */ private final BooleanFunction test; /** The number of pieces to add to each site. */ private final IntFunction countFn; /** The condition to apply the side effect. */ private final BooleanFunction sideEffectCondition; /** The side effect to apply. */ private final Moves sideEffect; /** Which site. */ private final boolean onStack; /** Add on Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** Action cache (indexed by mover first, component second, state+1 third, site fourth) */ private Move[][][][] actionCache = null; /** * Set to false if use of action cache is not allowed * This being true causes the bug reported here (https://ludii.games/forums/showthread.php?tid=589) */ private boolean allowCacheUse = false; //------------------------------------------------------------------------- /** * @param what The data about the components to add. * @param to The data on the location to add. * @param count The number of components to add [1]. * @param stack True if the move has to be applied on a stack [False]. * @param then The moves applied after that move is applied. * * @example (add (to (sites Empty))) * * @example (add (to Cell (sites Empty Cell))) * * @example (add (piece "Disc0") (to (last From))) * * @example (add (piece "Disc0") (to (sites Empty)) (then (attract)) ) */ public Add ( @Opt final Piece what, final To to, @Opt @Name final IntFunction count, @Opt @Name final Boolean stack, @Opt final Then then ) { super(then); if (what != null && what.components() == null) { if (what.component() == null) components = new IntFunction[] {new Mover()}; else components = new IntFunction[] { what.component() }; } else { components = (what == null) ? new IntFunction[] { new Mover() } : what.components(); } localState = (what == null) ? null : (what.state() == null) ? null : what.state(); site = to.loc(); region = to.region(); test = to.cond(); onStack = (stack == null) ? false : stack.booleanValue(); type = to.type(); level = to.level(); sideEffectCondition = (to.effect() == null) ? null : to.effect().condition(); sideEffect = to.effect(); countFn = (count == null) ? new IntConstant(1) : count; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { // Return list of legal "to" moves final BaseMoves moves = new BaseMoves(super.then()); final int origFrom = context.from(); final int origTo = context.to(); final int mover = context.state().mover(); final int count = countFn.eval(context); if (count < 1) return moves; for (final IntFunction componentFn : components) { final int componentId = componentFn.eval(context); if (componentId == Constants.UNDEFINED) continue; // We check if we try to add a large piece. final Component component = context.components()[componentId]; if (component != null && component.isLargePiece()) { final Moves movesLargePiece = evalLargePiece(context, component); moves.moves().addAll(movesLargePiece.moves()); continue; } if (site != null) { // TODO we're not making use of cache inside this block? final int siteEval = site.eval(context); context.setTo(siteEval); if (test == null || test.eval(context)) { Move move; final int state = (localState == null) ? Constants.UNDEFINED : localState.eval(context); final Action actionToAdd = (level == null) ? new ActionAdd(type, siteEval, componentId, 1, state, Constants.UNDEFINED, Constants.UNDEFINED, null) : new ActionInsert(type, siteEval, level.eval(context), componentId, state); final int cid = siteEval >= context.containerId().length ? 0 : context.containerId()[siteEval]; final ContainerState cs = context.containerState(cid); if(context.game().isStacking()) actionToAdd.setLevelTo(cs.sizeStack(siteEval, type)); if (isDecision()) actionToAdd.setDecision(true); move = new Move(actionToAdd); int remainingCount = count - 1; while (remainingCount > 0) { final Action actionToAddAgain = (level == null) ? new ActionAdd(type, siteEval, componentId, 1, state, Constants.UNDEFINED, Constants.UNDEFINED, null) : new ActionInsert(type, siteEval, level.eval(context), componentId, state); move.actions().add(actionToAddAgain); remainingCount--; } if (sideEffect != null && (sideEffectCondition == null || (sideEffectCondition != null && (sideEffectCondition.eval(context))))) { context.setFrom(siteEval); context.setTo(siteEval); move = MoveUtilities.chainRuleWithAction(context, sideEffect, move, true, false); } if (type.equals(SiteType.Edge)) { move.setFromNonDecision(siteEval); move.setToNonDecision(siteEval); move.setEdgeMove(siteEval); move.setOrientedMove(false); } else { move.setFromNonDecision(siteEval); move.setToNonDecision(siteEval); } moves.moves().add(move); context.setFrom(origFrom); context.setTo(origTo); for (int j = 0; j < moves.moves().size(); j++) { final Move m = moves.moves().get(j); m.setMover(mover); if (then() != null) m.then().add(then().moves()); } // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } } final Move[][] compActionCache = actionCache[mover][componentId]; if (region == null) return moves; final Region sites = region.eval(context); for (int toSite = sites.bitSet().nextSetBit(0); toSite >= 0; toSite = sites.bitSet().nextSetBit(toSite + 1)) { Move move; context.setTo(toSite); if (test == null || test.eval(context)) { final int state = (localState == null) ? -1 : localState.eval(context); if (compActionCache[state + 1][toSite] == null) { final Action actionToAdd = (level == null) ? new ActionAdd(type, toSite, componentId, 1, state, Constants.UNDEFINED, Constants.UNDEFINED, null) : new ActionInsert(type, toSite, level.eval(context), componentId, state); final int cid = toSite >= context.containerId().length ? 0 : context.containerId()[toSite]; final ContainerState cs = context.containerState(cid); if(context.game().isStacking()) actionToAdd.setLevelTo(cs.sizeStack(toSite, type)); actionToAdd.setDecision(isDecision()); move = new Move(actionToAdd); int remainingCount = count - 1; while (remainingCount > 0) { final Action actionToAddAgain = (level == null) ? new ActionAdd(type, toSite, componentId, 1, state, Constants.UNDEFINED, Constants.UNDEFINED, null) : new ActionInsert(type, toSite, level.eval(context), componentId, state); move.actions().add(actionToAddAgain); remainingCount--; } if (sideEffect != null && (sideEffectCondition == null || (sideEffectCondition != null && (sideEffectCondition.eval(context))))) { context.setFrom(toSite); context.setTo(toSite); move = MoveUtilities.chainRuleWithAction(context, sideEffect, move, true, false); MoveUtilities.chainRuleCrossProduct(context, moves, null, move, false); } if (type.equals(SiteType.Edge)) { move.setFromNonDecision(toSite); move.setToNonDecision(toSite); move.setEdgeMove(toSite); move.setOrientedMove(false); } else { move.setFromNonDecision(toSite); move.setToNonDecision(toSite); } if (then() != null) move.then().add(then().moves()); move.setMover(mover); if (allowCacheUse) compActionCache[state+1][toSite] = move; } else { move = compActionCache[state+1][toSite]; } moves.moves().add(move); } } } context.setTo(origTo); context.setFrom(origFrom); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- private Moves evalLargePiece(final Context context, final Component largePiece) { final BaseMoves moves = new BaseMoves(super.then()); final int largePieceId = largePiece.index(); final int nbPossibleStates = largePiece.walk().length * 4; final int localStateToAdd = (localState == null) ? Constants.UNDEFINED : localState.eval(context); final int mover = context.state().mover(); if (site != null) { final int siteEval = site.eval(context); final ContainerState cs = context.containerState(context.containerId()[siteEval]); for (int state = 0; state < nbPossibleStates; state++) { if (localStateToAdd != Constants.UNDEFINED && localStateToAdd != state) continue; final TIntArrayList locsLargePiece = largePiece.locs(context, siteEval, state, context.topology()); if (locsLargePiece == null || locsLargePiece.size() <= 0) continue; boolean valid = true; for (int i = 0; i < locsLargePiece.size(); i++) { final int siteToCheck = locsLargePiece.get(i); if (!cs.isEmpty(siteToCheck, type)) { valid = false; break; } } if (valid) { final Action actionAdd = new ActionAdd(type, siteEval, largePieceId, 1, state, Constants.UNDEFINED, Constants.UNDEFINED, null); actionAdd.setDecision(isDecision()); final Move move = new Move(actionAdd); move.setFromNonDecision(siteEval); move.setToNonDecision(siteEval); move.setMover(mover); move.setStateNonDecision(state); moves.moves().add(move); } } // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } final Region sites = region.eval(context); for (int toSite = sites.bitSet().nextSetBit(0); toSite >= 0; toSite = sites.bitSet().nextSetBit(toSite + 1)) { final ContainerState cs = context.containerState(context.containerId()[toSite]); for (int state = 0; state < nbPossibleStates; state++) { if (localStateToAdd != Constants.UNDEFINED && localStateToAdd != state) continue; final TIntArrayList locsLargePiece = largePiece.locs(context, toSite, state, context.topology()); if (locsLargePiece == null || locsLargePiece.size() <= 0) continue; boolean valid = true; for (int i = 0; i < locsLargePiece.size(); i++) { final int siteToCheck = locsLargePiece.get(i); if (!cs.isEmpty(siteToCheck, type)) { valid = false; break; } } if (valid) { final Action actionAdd = new ActionAdd(type, toSite, largePieceId, 1, state, Constants.UNDEFINED, Constants.UNDEFINED, null); actionAdd.setDecision(isDecision()); final Move move = new Move(actionAdd); move.setFromNonDecision(toSite); move.setToNonDecision(toSite); move.setMover(mover); move.setStateNonDecision(state); moves.moves().add(move); } } } // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game); if (onStack) gameFlags |= GameType.Stacking; else if (!(countFn instanceof IntConstant) || ((countFn instanceof IntConstant) && ((IntConstant) countFn).eval(new Context(game, new Trial(game))) != 1)) gameFlags |= GameType.Count; gameFlags |= SiteType.gameFlags(type); if (region != null) gameFlags |= region.gameFlags(game); if (countFn != null) gameFlags |= countFn.gameFlags(game); if (test != null) gameFlags |= test.gameFlags(game); for (final IntFunction comp : components) gameFlags |= comp.gameFlags(game); if (site != null) gameFlags |= site.gameFlags(game); if (localState != null) gameFlags |= GameType.SiteState; if (level != null) { gameFlags |= level.gameFlags(game); gameFlags |= GameType.Stacking; } if (sideEffect != null) gameFlags |= sideEffect.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); if (isDecision()) concepts.set(Concept.AddDecision.id(), true); else concepts.set(Concept.AddEffect.id(), true); if (region != null) concepts.or(region.concepts(game)); if (test != null) concepts.or(test.concepts(game)); for (final IntFunction comp : components) concepts.or(comp.concepts(game)); if (countFn != null) concepts.or(countFn.concepts(game)); if (site != null) concepts.or(site.concepts(game)); if (level != null) concepts.or(level.concepts(game)); if (sideEffect != null) concepts.or(sideEffect.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); if (region != null) writeEvalContext.or(region.writesEvalContextRecursive()); if (test != null) writeEvalContext.or(test.writesEvalContextRecursive()); for (final IntFunction comp : components) writeEvalContext.or(comp.writesEvalContextRecursive()); if (countFn != null) writeEvalContext.or(countFn.writesEvalContextRecursive()); if (site != null) writeEvalContext.or(site.writesEvalContextRecursive()); if (level != null) writeEvalContext.or(level.writesEvalContextRecursive()); if (sideEffect != null) writeEvalContext.or(sideEffect.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (region != null) readEvalContext.or(region.readsEvalContextRecursive()); if (test != null) readEvalContext.or(test.readsEvalContextRecursive()); for (final IntFunction comp : components) readEvalContext.or(comp.readsEvalContextRecursive()); if (countFn != null) readEvalContext.or(countFn.readsEvalContextRecursive()); if (site != null) readEvalContext.or(site.readsEvalContextRecursive()); if (level != null) readEvalContext.or(level.readsEvalContextRecursive()); if (sideEffect != null) readEvalContext.or(sideEffect.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (region != null) missingRequirement |= region.missingRequirement(game); if (test != null) missingRequirement |= test.missingRequirement(game); for (final IntFunction comp : components) missingRequirement |= comp.missingRequirement(game); if (countFn != null) missingRequirement |= countFn.missingRequirement(game); if (site != null) missingRequirement |= site.missingRequirement(game); if (level != null) missingRequirement |= level.missingRequirement(game); if (sideEffect != null) missingRequirement |= sideEffect.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (region != null) willCrash |= region.willCrash(game); if (test != null) willCrash |= test.willCrash(game); for (final IntFunction comp : components) willCrash |= comp.willCrash(game); if (site != null) willCrash |= site.willCrash(game); if (level != null) willCrash |= level.willCrash(game); if (countFn != null) willCrash |= countFn.willCrash(game); if (sideEffect != null) willCrash |= sideEffect.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); // We check if each player has a piece if the piece of the mover has to be added. boolean moverPieceAdded = false; for(final IntFunction compFn : components) if(compFn instanceof Mover) { moverPieceAdded =true; break; } boolean componentOwnedByEachPlayer = true; if(moverPieceAdded) { for(int pid = 1; pid < game.players().size();pid++) { boolean foundPiece = false; for(int compId = 1; compId < game.equipment().components().length; compId++) { final Component component = game.equipment().components()[compId]; if(component.owner() == pid) { foundPiece = true; break; } } if(!foundPiece) componentOwnedByEachPlayer = false; } } if(moverPieceAdded && !componentOwnedByEachPlayer) { game.addCrashToReport("The ludeme (move Add ...) or (add ...) is used to add the piece of the mover but a player has no piece."); willCrash = true; } return willCrash; } @Override public boolean isStatic() { for (final IntFunction comp : components) if (!comp.isStatic()) return false; if (region != null && !region.isStatic()) return false; if (test != null && !test.isStatic()) return false; if (test != null && !test.isStatic()) return false; if (localState != null && !localState.isStatic()) return false; if (site != null && !site.isStatic()) return false; if (level != null && !level.isStatic()) return false; if (sideEffect != null && !sideEffect.isStatic()) return false; if (countFn != null && !countFn.isStatic()) return false; return true; } @Override public void preprocess(final Game game) { if (type == null) type = game.board().defaultSite(); super.preprocess(game); if (countFn != null) countFn.preprocess(game); if (region != null) region.preprocess(game); if (test != null) test.preprocess(game); if (localState != null) localState.preprocess(game); for (final IntFunction comp : components) comp.preprocess(game); if (site != null) site.preprocess(game); if (sideEffect != null) sideEffect.preprocess(game); final int maxNumStates; if (game.requiresLocalState()) maxNumStates = game.maximalLocalStates(); else maxNumStates = 0; if (game.isStacking()) { // No cache allowed in stacking games allowCacheUse = false; } // Generate action cache if (type.equals(SiteType.Cell)) { actionCache = new Move[game.players().count() + 1][][][]; for (int p = 1; p < actionCache.length; ++p) { actionCache[p] = new Move [game.numComponents() + 1] [maxNumStates + 2] [game.equipment().totalDefaultSites()]; } } else if (type.equals(SiteType.Edge)) { actionCache = new Move[game.players().count() + 1][][][]; for (int p = 1; p < actionCache.length; ++p) { actionCache[p] = new Move [game.numComponents() + 1] [maxNumStates + 2] [game.board().topology().edges().size()]; } } else if (type.equals(SiteType.Vertex)) { actionCache = new Move[game.players().count() + 1][][][]; for (int p = 1; p < actionCache.length; ++p) { actionCache[p] = new Move [game.numComponents() + 1] [maxNumStates + 2] [game.board().topology().vertices().size()]; } } } //------------------------------------------------------------------------- /** * @return Components which can be placed */ public IntFunction[] components() { return components; } /** * @return The RegionFunction that tells us where we're allowed to move to */ public RegionFunction region() { return region; } /** * @return Site we're allowed to move to */ public IntFunction site() { return site; } /** * @return Function telling us which moves are legal */ public BooleanFunction legal() { return test; } /** * @return On stack? */ public boolean onStack() { return onStack; } /** * @return Variable type */ public SiteType type() { return type; } /** * Disables use of the action cache */ public void disableActionCache() { allowCacheUse = false; } //------------------------------------------------------------------------- @Override public String toString() { if (components.length == 1) { return "[Add: " + components[0] + ", " + region + ", " + site + ", " + then() + "]"; } else { return "[Add: " + Arrays.toString(components) + ", " + region + ", " + site + ", " + then() + "]"; } } @Override public String toEnglish(final Game game) { String englishString = ""; if(components != null && region != null) { String textCopm = ""; String textRegion = "any site"; for (final IntFunction comp : components) if (comp instanceof Mover == false) textCopm+=comp.toEnglish(game); if(region.toEnglish(game).startsWith("empty ")) textRegion = "an " + region.toEnglish(game); else textRegion = region.toEnglish(game); if(textCopm.equals("")) englishString = "Add one of your pieces to " + textRegion; else englishString = "Add " + textCopm + " to " + textRegion; } else if(components != null && region == null) { String textCopm=""; for (final IntFunction comp : components) textCopm+=comp.toEnglish(game); englishString = "add " + textCopm; } else if(components == null && region != null) { if(region.toEnglish(game).startsWith("empty ")) englishString = "Add one of your pieces to an " + region.toEnglish(game); else englishString = "Add one of your pieces to " + region.toEnglish(game); } String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return englishString + thenString; } }
24,797
24.670807
132
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Apply.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Name; import game.Game; import game.functions.booleans.BooleanFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.NonDecision; import other.context.Context; /** * Returns the effect to apply only if the condition is satisfied. * * @author Eric.Piette */ public final class Apply extends Moves { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Which condition. */ final BooleanFunction cond; /** If the condition is true. */ final NonDecision effect; //------------------------------------------------------------------------- /** * For checking a condition before to apply the default effect. * * @param If The condition to satisfy to get the effect moves. * * @example (apply if:(is Mover P1)) */ public Apply ( @Name final BooleanFunction If ) { super(null); cond = If; effect = null; } /** * For applying an effect. * * @param effect The moves to apply to make the effect. * * @example (apply (moveAgain)) */ public Apply ( final NonDecision effect ) { super(null); cond = null; this.effect = effect; } /** * For applying an effect if a condition is verified. * * @param If The condition to satisfy to get the effect moves. * @param effect The moves to apply to make the effect. * * @example (apply if:(is Mover P1) (moveAgain)) */ public Apply ( @Name final BooleanFunction If, final NonDecision effect ) { super(null); cond = If; this.effect = effect; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { if (cond == null || cond.eval(context)) return effect.eval(context); return new BaseMoves(super.then()); } //------------------------------------------------------------------------- @Override public boolean canMove(final Context context) { if (cond == null || cond.eval(context)) return effect.canMove(context); return false; } @Override public boolean canMoveTo(final Context context, final int target) { if (cond == null || cond.eval(context)) return effect.canMoveTo(context, target); else return false; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long flags = super.gameFlags(game); if (cond != null) flags |= cond.gameFlags(game); if (effect != null) flags |= effect.gameFlags(game); return flags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); if (cond != null) concepts.or(cond.concepts(game)); if (effect != null) concepts.or(effect.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (cond != null) writeEvalContext.or(cond.writesEvalContextRecursive()); if (effect != null) writeEvalContext.or(effect.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (cond != null) readEvalContext.or(cond.readsEvalContextRecursive()); if (effect != null) readEvalContext.or(effect.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (cond != null) missingRequirement |= cond.missingRequirement(game); if (effect != null) missingRequirement |= effect.missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (cond != null) willCrash |= cond.willCrash(game); if (effect != null) willCrash |= effect.willCrash(game); return willCrash; } @Override public boolean isStatic() { if (cond != null && !cond.isStatic()) return false; if (effect != null && !effect.isStatic()) return false; return true; } @Override public void preprocess(final Game game) { super.preprocess(game); if (cond != null) cond.preprocess(game); if (effect != null) effect.preprocess(game); } /** * @return The condition. */ public BooleanFunction condition() { return cond; } /** * @return The effect. */ public Moves effect() { return effect; } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String text=""; if(cond != null) text += cond.toEnglish(game) + ", "; text += effect.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return text + thenString; } }
5,263
19.091603
76
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Attract.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Opt; import game.Game; import game.functions.directions.Directions; import game.functions.ints.IntFunction; import game.functions.ints.last.LastTo; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import game.util.directions.AbsoluteDirection; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.BaseAction; import other.action.move.ActionAdd; import other.action.move.remove.ActionRemove; import other.context.Context; import other.move.Move; import other.state.container.ContainerState; import other.topology.Topology; import other.topology.TopologyElement; /** * Is used to attract all the pieces as close as possible to a site. * * @author Eric.Piette */ public final class Attract extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** Direction chosen. */ private final Directions dirnChoice; /** Add on Cell/Edge/Vertex. */ protected SiteType type; //------------------------------------------------------------------------- /** * @param from The data of the from location [(from (last To))]. * @param dirn The specific direction [Adjacent]. * @param then The moves applied after that move is applied. * * @example (attract (from (last To)) Diagonal) */ public Attract ( @Opt final game.util.moves.From from, @Opt final AbsoluteDirection dirn, @Opt final Then then ) { super(then); startLocationFn = (from == null) ? new LastTo(null) : from.loc(); dirnChoice = (dirn == null) ? new Directions(AbsoluteDirection.Adjacent, null) : new Directions(dirn, null); type = (from == null) ? null : from.type(); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); if (from == Constants.OFF) return moves; final Topology graph = context.topology(); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); final TopologyElement fromV = graph.getGraphElements(realType).get(from); // Get piece at 'from' final ContainerState containerState = context.state().containerStates()[0]; final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, fromV, null, null, null, context); for (final AbsoluteDirection direction : directions) { final List<Radial> radialList = graph.trajectories().radials(type, fromV.index(), direction); for (final Radial radial : radialList) { final TIntArrayList piecesInThisDirection = new TIntArrayList(); for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int to = radial.steps()[toIdx].id(); final int what = containerState.what(to, realType); if (what != 0) { piecesInThisDirection.add(what); final BaseAction removeAction = ActionRemove.construct(context.board().defaultSite(), to, Constants.UNDEFINED, true); final Move move = new Move(removeAction); moves.moves().add(move); } } for (int toIdx = 1; toIdx <= piecesInThisDirection.size(); toIdx++) { final int to = radial.steps()[toIdx].id(); final int what = piecesInThisDirection.getQuick(toIdx - 1); final Action actionAdd = new ActionAdd(type, to, what, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null); final Move move = new Move(actionAdd); moves.moves().add(move); } } } // for (final Move m : moves.moves()) // m.setMover(context.state().mover()); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | startLocationFn.gameFlags(game); gameFlags |= GameType.UsesFromPositions; gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); concepts.or(startLocationFn.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); if (dirnChoice != null) concepts.or(dirnChoice.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); if (dirnChoice != null) writeEvalContext.or(dirnChoice.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(startLocationFn.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); if (dirnChoice != null) readEvalContext.or(dirnChoice.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= startLocationFn.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= startLocationFn.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); startLocationFn.preprocess(game); type = SiteType.use(type, game); } @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "attracts all pieces towards " + type.name() + " " + startLocationFn.toEnglish(game) + thenString; } }
7,027
27.112
123
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Bet.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Opt; import annotations.Or; import game.Game; import game.functions.ints.IntFunction; import game.functions.range.RangeFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.play.ModeType; import game.types.play.RoleType; import game.types.state.GameType; import game.util.moves.Player; import main.Constants; import other.action.state.ActionBet; import other.concept.Concept; import other.context.Context; import other.move.Move; /** * Is used to bet an amount. * * @author Eric.Piette */ public final class Bet extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The player making the bet. */ private final IntFunction playerFn; /** The role making the bet to check in the required warning. */ private final RoleType role; /** The range of the bet. */ private final RangeFunction range; /** * @param who The data about the player to bet. * @param role The roleType of the player to bet. * @param range The range of the bet. * @param then The moves applied after that move is applied. * * @example (bet P1 (range 0 5)) */ public Bet ( @Or final Player who, @Or final RoleType role, final RangeFunction range, @Opt final Then then ) { super(then); int numNonNull = 0; if (who != null) numNonNull++; if (role != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException( "Piece(): One who or role parameter must be non-null."); this.range = range; playerFn = (role != null) ? RoleType.toIntFunction(role) : who.index(); this.role = role; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int player = playerFn.eval(context); final int min = range.minFn().eval(context); final int max = range.maxFn().eval(context); for (int i = min; i <= max; i++) { final ActionBet actionBet = new ActionBet(player, i); if (isDecision()) actionBet.setDecision(true); final Move move = new Move(actionBet); move.setDecision(true); move.setFromNonDecision(Constants.OFF); move.setToNonDecision(Constants.OFF); if (context.game().mode().mode() == ModeType.Simultaneous) move.setMover(player); else move.setMover(context.state().mover()); moves.moves().add(move); } if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public boolean canMoveTo(final Context context, final int target) { return false; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | range.gameFlags(game) | playerFn.gameFlags(game) | GameType.Bet; if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(range.concepts(game)); concepts.or(playerFn.concepts(game)); if (isDecision()) concepts.set(Concept.BetDecision.id(), true); else concepts.set(Concept.BetEffect.id(), true); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(range.writesEvalContextRecursive()); writeEvalContext.or(playerFn.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(range.readsEvalContextRecursive()); readEvalContext.or(playerFn.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; // We check if the role is correct. if (role != null) { final int indexOwnerPhase = role.owner(); if ((indexOwnerPhase < 1 && !role.equals(RoleType.Mover) && !role.equals(RoleType.Prev) && !role.equals(RoleType.Next) && !role.equals(RoleType.All)) || indexOwnerPhase > game.players().count()) { game.addRequirementToReport( "The ludeme (bet ...) or (move Bet ...) is used with a wrong RoleType: " + role + "."); missingRequirement = true; } } missingRequirement |= super.missingRequirement(game); missingRequirement |= range.missingRequirement(game); missingRequirement |= playerFn.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= range.willCrash(game); willCrash |= playerFn.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); range.preprocess(game); playerFn.preprocess(game); } @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return playerFn.toEnglish(game) + " makes a bet between " + range.toEnglish(game) + thenString; } //------------------------------------------------------------------------- }
6,343
24.893878
107
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Claim.java
package game.rules.play.moves.nonDecision.effect; import java.util.Arrays; import java.util.BitSet; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanFunction; import game.functions.ints.IntFunction; import game.functions.ints.state.Mover; import game.functions.region.RegionFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.util.equipment.Region; import game.util.moves.Piece; import game.util.moves.To; import main.Constants; import other.action.Action; import other.action.move.ActionAdd; import other.context.Context; import other.context.EvalContextData; import other.move.Move; /** * Claims a site by adding a piece of the specified colour there. * * @author Eric.Piette and cambolbro * * @remarks This ludeme is used for graph games. */ public final class Claim extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Which local state. */ private final IntFunction localState; /** Which components. */ private IntFunction[] components; /** Which region. */ private final RegionFunction region; /** Which site. */ private final IntFunction site; /** Which site. */ private final BooleanFunction test; /** Add on Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** Action cache (indexed by move first, component second, state+1 third, site fourth) */ private Move[][][][] actionCache = null; /** Set to false if use of action cache is not allowed */ private boolean allowCacheUse = false; //------------------------------------------------------------------------- /** * @param what The data about the components to claim. * @param to The data on the location to claim. * @param then The moves applied after that move is applied. * * @example (claim (to Cell (site)) (then (and (addScore Mover 1) (moveAgain)))) */ public Claim ( @Opt final Piece what, final To to, @Opt final Then then ) { super(then); if (what != null && what.components() == null) { if (what.component() == null) components = new IntFunction[] {new Mover()}; else components = new IntFunction[] { what.component() }; } else { components = (what == null) ? new IntFunction[] { new Mover() } : what.components(); } localState = (what == null) ? null : (what.state() == null) ? null : what.state(); site = to.loc(); region = to.region(); test = to.cond(); type = to.type(); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { // Return list of legal "to" moves final BaseMoves moves = new BaseMoves(super.then()); final int origFrom = context.from(); final int origTo = context.to(); final int mover = context.state().mover(); for (final IntFunction compomentFn : components) { final int componentId = compomentFn.eval(context); if (site != null) { // TODO we're not making use of cache inside this block? final int siteEval = site.eval(context); context.setTo(siteEval); if (test == null || test.eval(context)) { final Move action; final int state = (localState == null) ? -1 : localState.eval(context); final Action actionAdd = new ActionAdd(type, siteEval, componentId, 1, state, Constants.UNDEFINED, Constants.UNDEFINED, null); if (isDecision()) actionAdd.setDecision(true); action = new Move(actionAdd); if (type.equals(SiteType.Edge)) { action.setFromNonDecision(siteEval); action.setToNonDecision(siteEval); action.setEdgeMove(siteEval); action.setOrientedMove(false); } else { action.setFromNonDecision(siteEval); action.setToNonDecision(siteEval); } if (then() != null) { // action.consequents().add(consequents().moves()); final int fromOrigCsq = context.from(); final int toOrigCsq = context.to(); context.setFrom(action.fromNonDecision()); context.setTo(action.toNonDecision()); final Moves m = then().moves().eval(context); context.setFrom(fromOrigCsq); context.setTo(toOrigCsq); for (final Move mCsq : m.moves()) { for (final Action a : mCsq.actions()) { action.actions().add(a); } } } moves.moves().add(action); // for (final Move m : moves.moves()) // { // System.out.println(m); // if (m.consequents() != null) // System.out.println("csq: " + m.consequents()); // } context.setFrom(origFrom); context.setTo(origTo); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } } final Move[][] compActionCache = actionCache[mover][componentId]; final Region sites = region.eval(context); for (int toSite = sites.bitSet().nextSetBit(0); toSite >= 0; toSite = sites.bitSet().nextSetBit(toSite + 1)) { final Move action; context.setTo(toSite); if (test == null || test.eval(context)) { final int state = (localState == null) ? -1 : localState.eval(context); if (compActionCache[state+1][toSite] == null) { final Action actionAdd = new ActionAdd(type, toSite, componentId, 1, state, Constants.UNDEFINED, Constants.UNDEFINED, null); if (isDecision()) actionAdd.setDecision(true); action = new Move(actionAdd); if (type.equals(SiteType.Edge)) { action.setFromNonDecision(toSite); action.setToNonDecision(toSite); action.setEdgeMove(toSite); action.setOrientedMove(false); } else { action.setFromNonDecision(toSite); action.setToNonDecision(toSite); } if (then() != null) action.then().add(then().moves()); action.setMover(mover); if (allowCacheUse) compActionCache[state+1][toSite] = action; } else { action = compActionCache[state+1][toSite]; // action.consequents().clear(); } moves.moves().add(action); } } } context.setTo(origTo); context.setFrom(origFrom); // System.out.println("MOVES ARE"); // for (final Move m : moves.moves()) // System.out.println(m); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (region != null) gameFlags |= region.gameFlags(game); if (test != null) gameFlags |= test.gameFlags(game); for (final IntFunction comp : components) gameFlags |= comp.gameFlags(game); if (site != null) gameFlags |= site.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); if (region != null) concepts.or(region.concepts(game)); if (test != null) concepts.or(test.concepts(game)); for (final IntFunction comp : components) concepts.or(comp.concepts(game)); if (site != null) concepts.or(site.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); if (region != null) writeEvalContext.or(region.writesEvalContextRecursive()); if (test != null) writeEvalContext.or(test.writesEvalContextRecursive()); for (final IntFunction comp : components) writeEvalContext.or(comp.writesEvalContextRecursive()); if (site != null) writeEvalContext.or(site.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (region != null) readEvalContext.or(region.readsEvalContextRecursive()); if (test != null) readEvalContext.or(test.readsEvalContextRecursive()); for (final IntFunction comp : components) readEvalContext.or(comp.readsEvalContextRecursive()); if (site != null) readEvalContext.or(site.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (region != null) missingRequirement |= region.missingRequirement(game); if (test != null) missingRequirement |= test.missingRequirement(game); for (final IntFunction comp : components) missingRequirement |= comp.missingRequirement(game); if (site != null) missingRequirement |= site.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (region != null) willCrash |= region.willCrash(game); if (test != null) willCrash |= test.willCrash(game); for (final IntFunction comp : components) willCrash |= comp.willCrash(game); if (site != null) willCrash |= site.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { for (final IntFunction comp : components) if (!comp.isStatic()) return false; if (region != null && !region.isStatic()) return false; if (test != null && !test.isStatic()) return false; if (test != null && !test.isStatic()) return false; if (localState != null && !localState.isStatic()) return false; if (site != null && !site.isStatic()) return false; return true; } @Override public void preprocess(final Game game) { if (type == null) type = game.board().defaultSite(); super.preprocess(game); if (region != null) region.preprocess(game); if (test != null) test.preprocess(game); if (localState != null) localState.preprocess(game); for (final IntFunction comp : components) comp.preprocess(game); if (site != null) site.preprocess(game); final int maxNumStates; if (game.requiresLocalState()) maxNumStates = game.maximalLocalStates(); else maxNumStates = 0; // generate action cache if (type.equals(SiteType.Cell)) { actionCache = new Move[game.players().count() + 1][][][]; for (int p = 1; p < actionCache.length; ++p) { actionCache[p] = new Move [game.numComponents() + 1] [maxNumStates + 2] [game.equipment().totalDefaultSites()]; } } else if (type.equals(SiteType.Edge)) { actionCache = new Move[game.players().count() + 1][][][]; for (int p = 1; p < actionCache.length; ++p) { actionCache[p] = new Move [game.players().count() + 1] [maxNumStates + 2] [game.board().topology().edges().size()]; } } else if (type.equals(SiteType.Vertex)) { actionCache = new Move[game.players().count() + 1][][][]; for (int p = 1; p < actionCache.length; ++p) { actionCache[p] = new Move [game.numComponents() + 1] [maxNumStates + 2] [game.board().topology().vertices().size()]; } } } //------------------------------------------------------------------------- /** * @return Components which can be placed */ public IntFunction[] components() { return components; } /** * @return The RegionFunction that tells us where we're allowed to move to */ public RegionFunction region() { return region; } /** * @return Site we're allowed to move to */ public IntFunction site() { return site; } /** * @return Function telling us which moves are legal */ public BooleanFunction legal() { return test; } /** * @return Variable type */ public SiteType type() { return type; } /** * Disables use of the action cache */ public void disableActionCache() { allowCacheUse = false; } //------------------------------------------------------------------------- @Override public String toString() { if (components.length == 1) { return "[Colour: " + components[0] + ", " + region + ", " + site + ", " + then() + "]"; } else { return "[Colour: " + Arrays.toString(components) + ", " + region + ", " + site + ", " + then() + "]"; } } @Override public String toEnglish(final Game game) { String englishString = ""; if (region != null) englishString = "claim the region " + region.toEnglish(game); else englishString = "claim the site " + site.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return englishString + thenString; } }
13,968
22.596284
111
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Custodial.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanFunction; import game.functions.booleans.is.player.IsEnemy; import game.functions.booleans.is.player.IsFriend; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.iterator.Between; import game.functions.ints.iterator.To; import game.functions.ints.last.LastTo; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import game.util.directions.AbsoluteDirection; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import main.StringRoutines; import main.collections.FastTIntArrayList; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.MoveUtilities; import other.topology.Topology; import other.topology.TopologyElement; /** * Is used to apply an effect to all the sites flanked between two sites. * * @author mrraow and cambolbro and Eric.Piette * * @remarks Used for example in all the Tafl games. */ public final class Custodial extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** Direction chosen. */ private final AbsoluteDirection dirnChoice; /** Limit to flank. */ private final IntFunction limit; /** The piece to flank. */ private final BooleanFunction targetRule; /** The rule to detect the friend to flank. */ private final BooleanFunction friendRule; /** The effect to apply on the pieces flanked. */ private final Moves targetEffect; /** Add on Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** * @param from The data about the sites used as an origin to flank [(from * (last To))]. * @param dirnChoice The direction to compute the flanking [Adjacent]. * @param between The condition and effect on the pieces flanked [(between * if:(is Enemy (between)) (apply (remove (between))))]. * @param to The condition on the pieces surrounding [(to if:(is Friend * (to)))]. * @param then The moves applied after that move is applied. * * @example (custodial (from (last To)) Orthogonal (between (max 1) if:(is Enemy * (who at:(between))) (apply (remove (between))) ) (to if:(is Friend * (who at:(to)))) ) */ public Custodial ( @Opt final game.util.moves.From from, @Opt final AbsoluteDirection dirnChoice, @Opt final game.util.moves.Between between, @Opt final game.util.moves.To to, @Opt final Then then ) { super(then); startLocationFn = (from == null) ? new LastTo(null) : from.loc(); type = (from == null) ? null : from.type(); limit = (between == null || between.range() == null) ? new IntConstant(Constants.MAX_DISTANCE) : between.range().maxFn(); this.dirnChoice = (dirnChoice == null) ? AbsoluteDirection.Adjacent : dirnChoice; targetRule = (between == null || between.condition() == null) ? new IsEnemy(Between.instance(), null) : between.condition(); friendRule = (to == null || to.cond() == null) ? new IsFriend(To.instance(), null) : to.cond(); targetEffect = (between == null || between.effect() == null) ? new Remove(null, Between.instance(), null, null, null, null, null) : between.effect(); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); final int fromOrig = context.from(); final int toOrig = context.to(); final int betweenOrig = context.between(); final Topology graph = context.topology(); if (from == Constants.UNDEFINED) return new BaseMoves(null); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); final TopologyElement fromV = graph.getGraphElements(realType).get(from); final List<Radial> radialList = graph.trajectories().radials(type, fromV.index(), dirnChoice); final int maxPathLength = limit.eval(context); if (maxPathLength == 1) shortSandwich(context, moves, fromV, radialList); else longSandwich(context, moves, fromV, radialList, maxPathLength); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); context.setBetween(betweenOrig); context.setTo(toOrig); context.setFrom(fromOrig); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } /** * To compute a short flank (= 1). * * @param context * @param moves * @param fromV * @param directionIndices */ private void shortSandwich ( final Context context, final Moves moves, final TopologyElement fromV, final List<Radial> radials ) { for (final Radial radial : radials) { final int between = radial.steps()[1].id(); if (radial.steps().length < 3 || !isTarget(context, between) || !isFriend(context, radial.steps()[2].id())) continue; context.setBetween(between); MoveUtilities.chainRuleCrossProduct(context, moves, targetEffect, null, false); final TIntArrayList betweenSites = new TIntArrayList(1); betweenSites.add(between); moves.moves().get(moves.moves().size() - 1).setBetweenNonDecision(betweenSites); } } private boolean isFriend ( final Context context, final int location ) { context.setTo(location); return friendRule.eval(context); } private boolean isTarget ( final Context context, final int location ) { context.setBetween(location); return targetRule.eval(context); } /** * To compute a longer flank (> 1). * * @param context * @param moves * @param fromV * @param directionIndices * @param maxPathLength */ private void longSandwich ( final Context context, final Moves moves, final TopologyElement fromV, final List<Radial> radials, final int maxPathLength ) { for (final Radial radial : radials) { final FastTIntArrayList betweenSites = new FastTIntArrayList(); boolean foundEnemy = false; int posIdx = 1; while (posIdx < radial.steps().length && posIdx <= maxPathLength) { if (!isTarget(context, radial.steps()[posIdx].id())) break; foundEnemy = true; posIdx++; } if (!foundEnemy) continue; final int friendPos = posIdx < radial.steps().length ? radial.steps()[posIdx].id() : Constants.OFF; if (isFriend(context, friendPos)) { for (int i = 1; i < posIdx; i++) { final int between = radial.steps()[i].id(); betweenSites.add(between); context.setBetween(between); MoveUtilities.chainRuleCrossProduct(context, moves, targetEffect, null, false); } if(!moves.moves().isEmpty()) moves.moves().get(moves.moves().size() - 1).setBetweenNonDecision(new FastTIntArrayList(betweenSites)); } } } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | startLocationFn.gameFlags(game) | limit.gameFlags(game) | targetRule.gameFlags(game) | friendRule.gameFlags(game) | targetEffect.gameFlags(game); gameFlags |= GameType.UsesFromPositions; gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); concepts.or(startLocationFn.concepts(game)); concepts.or(limit.concepts(game)); concepts.or(targetRule.concepts(game)); concepts.or(friendRule.concepts(game)); concepts.or(targetEffect.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); // We check if that's effectively a capture (remove or fromTo). if (targetEffect.concepts(game).get(Concept.RemoveEffect.id()) || targetEffect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.CustodialCapture.id(), true); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); writeEvalContext.or(limit.writesEvalContextRecursive()); writeEvalContext.or(targetRule.writesEvalContextRecursive()); writeEvalContext.or(friendRule.writesEvalContextRecursive()); writeEvalContext.or(targetEffect.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); writeEvalContext.set(EvalContextData.Between.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(startLocationFn.readsEvalContextRecursive()); readEvalContext.or(limit.readsEvalContextRecursive()); readEvalContext.or(targetRule.readsEvalContextRecursive()); readEvalContext.or(friendRule.readsEvalContextRecursive()); readEvalContext.or(targetEffect.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= startLocationFn.missingRequirement(game); missingRequirement |= limit.missingRequirement(game); missingRequirement |= targetRule.missingRequirement(game); missingRequirement |= friendRule.missingRequirement(game); missingRequirement |= targetEffect.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= startLocationFn.willCrash(game); willCrash |= limit.willCrash(game); willCrash |= targetRule.willCrash(game); willCrash |= friendRule.willCrash(game); willCrash |= targetEffect.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return startLocationFn.isStatic() && limit.isStatic() && targetRule.isStatic() && friendRule.isStatic() && targetEffect.isStatic(); } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); startLocationFn.preprocess(game); limit.preprocess(game); targetRule.preprocess(game); friendRule.preprocess(game); targetEffect.preprocess(game); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String targetString = ""; if (targetRule != null) targetString = " if the target is " + targetRule.toEnglish(game); String friendString = ""; if (friendRule != null) friendString = " if the friend is " + friendRule.toEnglish(game); String directionString = ""; if (dirnChoice != null) directionString += " with "+ dirnChoice.name()+ " direction"; String fromString = ""; if (startLocationFn != null) fromString = " starting from " + startLocationFn.toEnglish(game); String limitString = ""; if (limit != null) limitString = " with a limit of " + limit.toEnglish(game) + " pieces"; String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); final SiteType realType = (type != null) ? type : game.board().defaultSite(); return "for all flanked pieces on " + realType.name() + StringRoutines.getPlural(realType.name()) + fromString + directionString + limitString + targetString + friendString + targetEffect.toEnglish(game) + thenString; } //------------------------------------------------------------------------- }
12,920
28.703448
219
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Deal.java
package game.rules.play.moves.nonDecision.effect; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import annotations.Name; import annotations.Opt; import game.Game; import game.equipment.component.Component; import game.equipment.container.Container; import game.equipment.container.other.Deck; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.component.DealableType; import game.types.state.GameType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.BaseAction; import other.action.move.ActionAdd; import other.action.move.move.ActionMove; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.state.container.ContainerState; /** * Deals cards or dominoes to each player. * * @author Eric.Piette */ public final class Deal extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The number to deal. */ private final IntFunction countFn; /** The number to deal. */ private final DealableType type; /** To start to deal with a specific player. */ private final IntFunction beginWith; //------------------------------------------------------------------------- /** * @param type Type of deal. * @param count The number of components to deal [1]. * @param beginWith To start to deal with a specific player. * @param then The moves applied after that move is applied. * * @example (deal Cards 3 beginWith:(mover)) */ public Deal ( final DealableType type, @Opt final IntFunction count, @Opt @Name final IntFunction beginWith, @Opt final Then then ) { super(then); this.type = type; countFn = (count == null) ? new IntConstant(1) : count; this.beginWith = beginWith; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { if (type == DealableType.Cards) return evalCards(context); else if (type == DealableType.Dominoes) return evalDominoes(context); return new BaseMoves(super.then()); } //------------------------------------------------------------------------- /** * @param context * @return The moves to deal cards. */ public Moves evalCards(final Context context) { final Moves moves = new BaseMoves(super.then()); // If no deck nothing to do. if (context.game().handDeck().isEmpty()) return moves; final List<Integer> handIndex = new ArrayList<>(); for (final Container c : context.containers()) if (c.isHand() && !c.isDeck() && !c.isDice()) handIndex.add(Integer.valueOf(context.sitesFrom()[c.index()])); // If each player does not have a hand, nothing to do. if (handIndex.size() != context.game().players().count()) return moves; final Deck deck = context.game().handDeck().get(0); final ContainerState cs = context.containerState(deck.index()); final int indexSiteDeck = context.sitesFrom()[deck.index()]; final int sizeDeck = cs.sizeStackCell(indexSiteDeck); final int count = countFn.eval(context); if (sizeDeck < count * handIndex.size()) throw new IllegalArgumentException("You can not deal so much cards."); int hand = (beginWith == null) ? 0 : (beginWith.eval(context) - 1); int counter = 0; for (int indexCard = 0; indexCard < count * handIndex.size(); indexCard++) { final Action dealAction = ActionMove.construct(SiteType.Cell, indexSiteDeck, cs.sizeStackCell(indexSiteDeck) - 1 - counter, SiteType.Cell, handIndex.get(hand).intValue(), Constants.OFF, Constants.OFF, Constants.OFF, Constants.OFF, false); final Move move = new Move(dealAction); moves.moves().add(move); if (hand == context.game().players().count() - 1) hand = 0; else hand++; counter++; } // The subsequents to add to the moves if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- /** * @param context * @return The moves to deal dominoes. */ public Moves evalDominoes(final Context context) { final Moves moves = new BaseMoves(super.then()); final TIntArrayList handIndex = new TIntArrayList(); for (final Container c : context.containers()) if (c.isHand() && !c.isDeck() && !c.isDice()) handIndex.add(context.sitesFrom()[c.index()]); // If each player does not have a hand, nothing to do. if (handIndex.size() != context.game().players().count()) return moves; final Component[] components = context.components(); final int count = countFn.eval(context); if (components.length < count * handIndex.size()) throw new IllegalArgumentException("You can not deal so much dominoes."); final TIntArrayList toDeal = new TIntArrayList(); for (int i = 1; i < components.length; i++) toDeal.add(i); final int nbPlayers = context.players().size() - 1; final ArrayList<boolean[]> masked = new ArrayList<>(); for (int i = 1; i <= nbPlayers; i++) { masked.add(new boolean[nbPlayers]); for (int j = 1; j <= nbPlayers; j++) { if (i == j) masked.get(i - 1)[j - 1] = false; else masked.get(i - 1)[j - 1] = true; } } int dealed = 0; while (dealed < (count * 2)) { final int index = context.rng().nextInt(toDeal.size()); final int indexComponent = toDeal.getQuick(index); final Component component = components[indexComponent]; final int currentPlayer = dealed % nbPlayers; final BaseAction actionAtomic = new ActionAdd(SiteType.Cell, handIndex.getQuick(currentPlayer) + (dealed / nbPlayers), component.index(), count, Constants.OFF, Constants.OFF, Constants.UNDEFINED, null); final Move move = new Move(actionAtomic); moves.moves().add(move); toDeal.removeAt(index); dealed++; } // The subsequents to add to the moves. if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); return moves; } @Override public boolean canMove(final Context context) { return false; } @Override public boolean canMoveTo(final Context context, final int target) { return false; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = countFn.gameFlags(game) | super.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); if (type == DealableType.Cards) return GameType.Card | gameFlags; else if (type == DealableType.Dominoes) return GameType.LargePiece | GameType.Dominoes | GameType.Stochastic | GameType.HiddenInfo | gameFlags; else return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(countFn.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); if (type == DealableType.Cards) concepts.set(Concept.Card.id(), true); else if (type == DealableType.Dominoes) concepts.set(Concept.Domino.id(), true); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(countFn.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(countFn.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; if (type == DealableType.Cards) { boolean gameHasCard = false; for (int i = 1; i < game.equipment().components().length; i++) { final Component component = game.equipment().components()[i]; if (component.isCard()) { gameHasCard = true; break; } } if (!gameHasCard) { game.addRequirementToReport("The ludeme (deal Cards ...) is used but the equipment has no cards."); missingRequirement = true; } } else if (type == DealableType.Dominoes) { if (!game.hasDominoes()) { game.addRequirementToReport( "The ludeme (deal Dominoes ...) is used but the equipment has no dominoes."); missingRequirement = true; } } missingRequirement |= super.missingRequirement(game); missingRequirement |= countFn.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= countFn.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); countFn.preprocess(game); if (beginWith != null) beginWith.preprocess(game); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String beginString = ""; if (beginWith != null) beginString = " beginning with " + beginWith.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "deal " + countFn.toEnglish(game) + " " + type.name().toLowerCase() + " to each player" + beginString + thenString; } //------------------------------------------------------------------------- }
10,346
26.445623
241
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Directional.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanFunction; import game.functions.booleans.is.player.IsEnemy; import game.functions.directions.Directions; import game.functions.directions.DirectionsFunction; import game.functions.ints.IntFunction; import game.functions.ints.iterator.From; import game.functions.ints.iterator.To; import game.functions.ints.last.LastFrom; import game.functions.ints.last.LastTo; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.graph.Radial; import main.Constants; import main.StringRoutines; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.MoveUtilities; import other.topology.Topology; import other.topology.TopologyElement; /** * Is used to apply an effect to all the pieces in a direction from a location. * * @author Eric.Piette * @remarks For example, used in Fanorona. */ public final class Directional extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** The kind of piece to capture. */ private final BooleanFunction targetRule; /** Moves to apply. */ private final Moves effect; /** Add on Cell/Edge/Vertex. */ private SiteType type; /** Direction to use. */ private final DirectionsFunction dirnChoice; //------------------------------------------------------------------------- /** * @param from The origin of the move [(from (last To))]. * @param directions The directions to use [(directions from:(last From) * to:(last To))]. * @param to The condition of the location to apply the effect [(to * if:(is Enemy (to)) (apply (remove (from))))]. * @param then The moves applied after that move is applied. * * @example (directional (from (last To)) (to if:(is Enemy (who at:(to))) (apply * (remove (to))) )) */ public Directional ( @Opt final game.util.moves.From from, @Opt final game.util.directions.Direction directions, @Opt final game.util.moves.To to, @Opt final Then then ) { super(then); startLocationFn = (from == null) ? new LastTo(null) : from.loc(); type = (from == null) ? null : from.type(); targetRule = (to == null || to.cond() == null) ? new IsEnemy(To.instance(), null) : to.cond(); effect = (to == null || to.effect() == null) ? new Remove(null, new From(null), null, null, null, null, null) : to.effect(); // The directions dirnChoice = (directions != null) ? directions.directionsFunctions() : null; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); final int fromOrig = context.from(); final int toOrig = context.to(); final Topology topology = context.topology(); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); final TopologyElement fromV = topology.getGraphElements(realType).get(from); final List<AbsoluteDirection> directions = (dirnChoice != null) ? dirnChoice.convertToAbsolute(realType, fromV, null, null, null, context) : new Directions(realType, new LastFrom(null), new LastTo(null)).convertToAbsolute(realType, fromV, null, null, null, context); for (final AbsoluteDirection direction : directions) { final List<Radial> radials = topology.trajectories().radials(type, fromV.index(), direction); for (final Radial radial : radials) { for (int i = 1; i < radial.steps().length; i++) { final int locUnderThreat = radial.steps()[i].id(); if (!isTarget(context, locUnderThreat)) break; final int saveFrom = context.from(); final int saveTo = context.to(); context.setFrom(Constants.OFF); context.setTo(locUnderThreat); MoveUtilities.chainRuleCrossProduct(context, moves, effect, null, false); context.setTo(saveTo); context.setFrom(saveFrom); } } } context.setFrom(fromOrig); context.setTo(toOrig); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } /** * @param context The context. * @param location The location. * @return True if the target condition is true. */ private boolean isTarget ( final Context context, final int location ) { context.setTo(location); return targetRule.eval(context); } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = startLocationFn.gameFlags(game) | targetRule.gameFlags(game) | effect.gameFlags(game) | super.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); concepts.or(startLocationFn.concepts(game)); concepts.or(targetRule.concepts(game)); concepts.or(effect.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); // We check if that's effectively a capture (remove or fromTo). if (effect.concepts(game).get(Concept.RemoveEffect.id()) || effect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.DirectionCapture.id(), true); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); writeEvalContext.or(targetRule.writesEvalContextRecursive()); writeEvalContext.or(effect.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(startLocationFn.readsEvalContextRecursive()); readEvalContext.or(targetRule.readsEvalContextRecursive()); readEvalContext.or(effect.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean isStatic() { return startLocationFn.isStatic() && targetRule.isStatic() && effect.isStatic(); } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); startLocationFn.preprocess(game); targetRule.preprocess(game); effect.preprocess(game); } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= startLocationFn.missingRequirement(game); missingRequirement |= targetRule.missingRequirement(game); missingRequirement |= effect.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= startLocationFn.willCrash(game); willCrash |= targetRule.willCrash(game); willCrash |= effect.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String targetString = ""; if (targetRule != null) targetString = " if the target is " + targetRule.toEnglish(game); String directionString = ""; if (dirnChoice != null) directionString += " with "+ dirnChoice.toEnglish(game)+ " direction"; String fromString = ""; if (startLocationFn != null) fromString = " starting from " + startLocationFn.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "for all pieces on " + type.name() + StringRoutines.getPlural(type.name()) + fromString + directionString + targetString + effect.toEnglish(game) + thenString; } //------------------------------------------------------------------------- }
9,192
28.750809
168
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Effect.java
package game.rules.play.moves.nonDecision.effect; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.NonDecision; import other.context.Context; //----------------------------------------------------------------------------- /** * Defines moves which do not involve a player decision. * * @author Eric.Piette and cambolbro * * Effect moves are typically applied in response to player decision moves, * e.g. the capture of a piece following the move of another piece. */ public abstract class Effect extends NonDecision { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @param then The effect of the moves. */ public Effect ( final Then then ) { super(then); } //------------------------------------------------------------------------- /** * Trick ludeme into joining the grammar. */ @Override public Moves eval(final Context context) { return null; } //------------------------------------------------------------------------- }
1,087
21.666667
79
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Enclose.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Name; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanFunction; import game.functions.booleans.is.player.IsEnemy; import game.functions.directions.Directions; import game.functions.directions.DirectionsFunction; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.iterator.Between; import game.functions.ints.last.LastTo; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.Direction; import gnu.trove.list.array.TIntArrayList; import main.StringRoutines; import main.collections.FastTIntArrayList; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.MoveUtilities; import other.state.container.ContainerState; import other.topology.Topology; import other.topology.TopologyElement; /** * Applies a move to an enclosed group. * * @author Eric Piette * * @remarks A group of components is 'enclosed' if it has no adjacent empty * sites, where board sides count as boundaries. This ludeme is used * for surround capture games such as Go. */ public final class Enclose extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The starting point of the loop. */ private final IntFunction startFn; /** Direction chosen. */ private final DirectionsFunction dirnChoice; /** The piece to surround. */ private final BooleanFunction targetRule; /** The number of liberties allowed in the group to enclose. */ private final IntFunction numEmptySitesInGroupEnclosed; /** Effect to apply to each site inside the group. */ private final Moves effect; /** The graph element type. */ private SiteType type; //------------------------------------------------------------------------- /** * @param type The graph element type [default site type of the board]. * @param from The origin of the enclosed group [(from (last To))]. * @param directions The direction to use [Adjacent]. * @param between The condition and effect on the pieces enclosed [(between * if:(is Enemy (between)) (apply (remove (between))))]. * @param numException The number of liberties allowed in the group to enclose * [0]. * @param then The moves applied after that move is applied. * * @example (enclose (from (last To)) Orthogonal (between if:(is Enemy (who * at:(between))) (apply (remove (between) ) ) )) */ public Enclose ( @Opt final SiteType type, @Opt final game.util.moves.From from, @Opt final Direction directions, @Opt final game.util.moves.Between between, @Opt @Name final IntFunction numException, @Opt final Then then ) { super(then); startFn = (from == null) ? new LastTo(null) : (from.loc() == null) ? new LastTo(null) : from.loc(); dirnChoice = (directions != null) ? directions.directionsFunctions() : new Directions(AbsoluteDirection.Adjacent, null); targetRule = (between == null || between.condition() == null) ? new IsEnemy(Between.instance(), null) : between.condition(); effect = (between == null || between.effect() == null) ? new Remove(null, Between.instance(), null, null, null, null, null) : between.effect(); this.type = type; numEmptySitesInGroupEnclosed = (numException == null) ? new IntConstant(0) : numException; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startFn.eval(context); final int originBetween = context.between(); final int originTo = context.to(); // Check if this is a site. if (from < 0) return moves; final Topology topology = context.topology(); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); final List<? extends TopologyElement> graphElements = topology.getGraphElements(realType); // Check if the site is in the board. if (from >= graphElements.size()) return moves; final ContainerState cs = context.containerState(0); final int what = cs.what(from, realType); // Check if the site is not empty. if (what <= 0) return moves; final int numException = numEmptySitesInGroupEnclosed.eval(context); final boolean atLeastAnEmpty = targetRule.concepts(context.game()).get(Concept.IsEmpty.id()); // We get all the sites around the starting positions satisfying the target // rule. final TIntArrayList aroundTarget = new TIntArrayList(); final TopologyElement element = graphElements.get(from); final List<AbsoluteDirection> directionsElement = dirnChoice.convertToAbsolute(type, element, null, null, null, context); for (final AbsoluteDirection direction : directionsElement) { final List<game.util.graph.Step> steps = topology.trajectories().steps(type, element.index(), type, direction); for (final game.util.graph.Step step : steps) { final int between = step.to().id(); if (!aroundTarget.contains(between)) { if (isTarget(context, between)) aroundTarget.add(between); else if (numException > 0 && cs.what(between, realType) == 0) aroundTarget.add(between); } } } // We look the group of each possible target, if no liberties, we apply the // effect. final boolean[] sitesChecked = new boolean[graphElements.size()]; aroundTargetLoop: for (int indexEnclosed = 0; indexEnclosed < aroundTarget.size(); indexEnclosed++) { final int target = aroundTarget.get(indexEnclosed); // If already checked we continue; if (sitesChecked[target]) continue; int numExceptionToUse = numException; if (numExceptionToUse > 0 && cs.what(target, realType) == 0) numExceptionToUse--; // We get the group of sites satisfying the target rule. final boolean[] enclosedGroup = new boolean[graphElements.size()]; final FastTIntArrayList enclosedGroupList = new FastTIntArrayList(); enclosedGroup[target] = true; enclosedGroupList.add(target); int i = 0; while (i != enclosedGroupList.size()) { final int site = enclosedGroupList.getQuick(i); final TopologyElement siteElement = graphElements.get(site); final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(type, siteElement, null, null, null, context); for (final AbsoluteDirection direction : directions) { final List<game.util.graph.Step> steps = topology.trajectories().steps(type, site, type, direction); for (final game.util.graph.Step step : steps) { final int between = step.to().id(); // If we already have it we continue to look the others. if (enclosedGroup[between]) continue; if (isTarget(context, between)) { enclosedGroup[between] = true; enclosedGroupList.add(between); } else if (cs.what(between, realType) == 0) { if (numExceptionToUse > 0) { enclosedGroup[between] = true; enclosedGroupList.add(between); numExceptionToUse--; } else { // It's a liberty, so move on continue aroundTargetLoop; } } } } sitesChecked[site] = true; i++; } final TIntArrayList enclosingGroup = new TIntArrayList(); // We check whether we have liberties for (int indexGroup = 0; indexGroup < enclosedGroupList.size(); indexGroup++) { final int siteGroup = enclosedGroupList.getQuick(indexGroup); final TopologyElement elem = graphElements.get(siteGroup); final List<AbsoluteDirection> directionsElem = dirnChoice.convertToAbsolute(type, elem, null, null, null, context); for (final AbsoluteDirection direction : directionsElem) { final List<game.util.graph.Step> steps = topology.trajectories().steps(type, siteGroup, type, direction); for (final game.util.graph.Step step : steps) { final int to = step.to().id(); if (!enclosedGroup[to] && !enclosingGroup.contains(to)) if (atLeastAnEmpty ? isTarget(context, to) : cs.what(to, type) == 0) continue aroundTargetLoop; // At least one liberty, so move on else enclosingGroup.add(to); } } } // If the enclosed site can be empty. if(atLeastAnEmpty) { // Check if that's a single group. boolean aSingleGroup = true; int siteGroup = enclosingGroup.get(0); while(enclosingGroup.size() != 1) { final List<game.util.graph.Step> steps = topology.trajectories().steps(type, siteGroup, type, AbsoluteDirection.All); boolean inSameGroup = false; for (final game.util.graph.Step step : steps) { final int to = step.to().id(); if(enclosingGroup.contains(to)) { enclosingGroup.remove(siteGroup); siteGroup = to; inSameGroup = true; break; } } if(!inSameGroup) { aSingleGroup = false; break; } } if(!aSingleGroup) continue aroundTargetLoop; } // If we reach this point and didn't continue the "aroundTargetLoop" above, // this means that we have no liberties. // If no liberties, this group is enclosed and we apply the effect. for (int indexBetween = 0; indexBetween < enclosedGroupList.size(); indexBetween++) { final int between = enclosedGroupList.getQuick(indexBetween); context.setBetween(between); MoveUtilities.chainRuleCrossProduct(context, moves, effect, null, false); } moves.moves().get(moves.moves().size() - 1).setBetweenNonDecision(new FastTIntArrayList(enclosedGroupList)); } context.setTo(originTo); context.setBetween(originBetween); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } /** * @param context The context. * @param location The site. * @return True if the target rule is true. */ private boolean isTarget(final Context context, final int location) { context.setBetween(location); return targetRule.eval(context); } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return startFn.gameFlags(game) | targetRule.gameFlags(game) | effect.gameFlags(game) | numEmptySitesInGroupEnclosed.gameFlags(game) | gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); // We check if that's effectively a capture (remove or fromTo). if (effect.concepts(game).get(Concept.RemoveEffect.id()) || effect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.EncloseCapture.id(), true); concepts.or(startFn.concepts(game)); concepts.or(targetRule.concepts(game)); concepts.or(effect.concepts(game)); concepts.or(numEmptySitesInGroupEnclosed.concepts(game)); if (dirnChoice != null) concepts.or(dirnChoice.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); writeEvalContext.or(startFn.writesEvalContextRecursive()); writeEvalContext.or(targetRule.writesEvalContextRecursive()); writeEvalContext.or(effect.writesEvalContextRecursive()); writeEvalContext.or(numEmptySitesInGroupEnclosed.writesEvalContextRecursive()); if (dirnChoice != null) writeEvalContext.or(dirnChoice.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.Between.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); readEvalContext.or(startFn.readsEvalContextRecursive()); readEvalContext.or(targetRule.readsEvalContextRecursive()); readEvalContext.or(effect.readsEvalContextRecursive()); readEvalContext.or(numEmptySitesInGroupEnclosed.readsEvalContextRecursive()); if (dirnChoice != null) readEvalContext.or(dirnChoice.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); missingRequirement |= startFn.missingRequirement(game); missingRequirement |= targetRule.missingRequirement(game); missingRequirement |= effect.missingRequirement(game); missingRequirement |= numEmptySitesInGroupEnclosed.missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); willCrash |= startFn.willCrash(game); willCrash |= targetRule.willCrash(game); willCrash |= effect.willCrash(game); willCrash |= numEmptySitesInGroupEnclosed.willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); startFn.preprocess(game); targetRule.preprocess(game); effect.preprocess(game); numEmptySitesInGroupEnclosed.preprocess(game); type = SiteType.use(type, game); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String targetString = ""; if (targetRule != null) targetString = " if the target is " + targetRule.toEnglish(game); String directionString = ""; if (dirnChoice != null) directionString += " with "+ dirnChoice.toEnglish(game)+ " direction"; String fromString = ""; if (startFn != null) fromString = " starting from " + startFn.toEnglish(game); String limitString = ""; if (numEmptySitesInGroupEnclosed != null) limitString = " if the number of liberties is less than or equal to " + numEmptySitesInGroupEnclosed.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "for all enclosed pieces on " + type.name() + StringRoutines.getPlural(type.name()) + fromString + directionString + limitString + targetString + effect.toEnglish(game) + thenString; } //------------------------------------------------------------------------- }
15,817
29.95499
191
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Flip.java
package game.rules.play.moves.nonDecision.effect; import java.util.ArrayList; import java.util.BitSet; import annotations.Opt; import game.Game; import game.equipment.component.Component; import game.functions.ints.IntFunction; import game.functions.ints.iterator.To; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import game.util.moves.Flips; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.BaseAction; import other.action.move.ActionAdd; import other.action.state.ActionSetState; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.state.container.ContainerState; /** * Is used to flip a piece. * * @author Eric.Piette */ public final class Flip extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** location. */ protected final IntFunction locFn; /** Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** * @param type The graph element type [default SiteType of the board]. * @param loc The location to flip the piece [(to)]. * @param then The moves applied after that move is applied. * * @example (flip) * * @example (flip (last To)) */ public Flip ( @Opt final SiteType type, @Opt final IntFunction loc, @Opt final Then then ) { super(then); locFn = (loc == null) ? To.instance() : loc; this.type = type; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int loc = locFn.eval(context); if (loc == Constants.OFF) return moves; final int cid = loc >= context.containerId().length ? 0 : context.containerId()[loc]; SiteType realType = type; if (cid > 0) realType = SiteType.Cell; else if (realType == null) realType = context.board().defaultSite(); final ContainerState cs = context.state().containerStates()[cid]; final int stackSize = cs.sizeStack(loc, realType); if (stackSize > 1) { final Move move = new Move(new ArrayList<other.action.Action>()); final TIntArrayList whats = new TIntArrayList(); final TIntArrayList states = new TIntArrayList(); final TIntArrayList rotations = new TIntArrayList(); final TIntArrayList values = new TIntArrayList(); for (int level = 0; level < stackSize; level++) { whats.add(cs.what(loc, level, realType)); states.add(cs.state(loc, level, realType)); rotations.add(cs.rotation(loc, level, realType)); values.add(cs.value(loc, level, realType)); move.actions().add(other.action.move.remove.ActionRemove.construct(realType, loc, level, true)); } for (int level = 0; level < stackSize; level++) { final int what = whats.get(whats.size() - level - 1); final int value = values.get(whats.size() - level - 1); final int rotation = rotations.get(whats.size() - level - 1); int state = states.get(states.size() - level - 1); final Flips flips = context.components()[what].getFlips(); if (flips != null) state = flips.flipState(state); move.actions().add(new ActionAdd(realType, loc, what, 1, state, rotation, value, Boolean.TRUE)); } moves.moves().add(move); } else if (stackSize == 1) { final int currentState = context.containerState(context.containerId()[loc]).state(loc, realType); final int whatValue = context.containerState(context.containerId()[loc]).what(loc, realType); if (whatValue == 0) return moves; final Flips flips = context.components()[whatValue].getFlips(); if (flips == null) return moves; final int newState = flips.flipState(currentState); final BaseAction action = new ActionSetState(realType, loc, Constants.UNDEFINED, newState); final Move m = new Move(action); moves.moves().add(m); } if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public String toString() { return "Flip(" + locFn + ")"; } @Override public long gameFlags(final Game game) { long gameFlags = GameType.SiteState | locFn.gameFlags(game) | super.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); concepts.set(Concept.Flip.id(), true); concepts.or(locFn.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(locFn.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(locFn.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; boolean gameHasComponentsWithFlips = false; for (int i = 1; i < game.equipment().components().length; i++) { final Component component = game.equipment().components()[i]; if (component.getFlips() != null) { gameHasComponentsWithFlips = true; break; } } if (!gameHasComponentsWithFlips) { game.addRequirementToReport("The ludeme (flip ...) is used but no component has flips defined."); missingRequirement = true; } missingRequirement |= super.missingRequirement(game); missingRequirement |= locFn.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= locFn.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return locFn.isStatic(); } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); locFn.preprocess(game); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String englishString = ""; if(locFn != null) englishString = "flip piece in "+ locFn.toEnglish(game); else englishString = "flip piece"; String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); englishString += thenString; return englishString; } }
7,506
25.620567
100
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/FromTo.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Name; import annotations.Opt; import game.Game; import game.equipment.component.Component; import game.functions.booleans.BooleanConstant; import game.functions.booleans.BooleanFunction; import game.functions.intArray.state.Rotations; import game.functions.ints.IntFunction; import game.functions.ints.board.Id; import game.functions.region.RegionFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.play.RoleType; import game.types.state.GameType; import game.util.moves.From; import game.util.moves.To; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.move.ActionCopy; import other.action.move.ActionMoveN; import other.action.move.ActionSubStackMove; import other.action.move.move.ActionMove; import other.action.state.ActionSetRotation; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.Move; import other.move.MoveUtilities; import other.state.container.ContainerState; /** * Moves a piece from one site to another, possibly in another container, with * no direction link between the ``from'' and ``to'' sites. * * @author Eric.Piette * * @remarks If the ``copy'' parameter is set, then a copy of the piece is * duplicated at the ``to'' site rather than actually moving there. */ public final class FromTo extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Loc from. */ private final IntFunction locFrom; /** Level. */ private final IntFunction levelFrom; /** Count. */ private final IntFunction countFn; /** Loc to. */ private final IntFunction locTo; /** Rotation to. */ private final Rotations rotationTo; /** Level. */ private final IntFunction levelTo; /** Region from. */ private final RegionFunction regionFrom; /** Region to. */ private final RegionFunction regionTo; /** From Condition Rule. */ private final BooleanFunction fromCondition; /** Move Rule. */ private final BooleanFunction moveRule; /** Capture Rule. */ private final BooleanFunction captureRule; /** Capture Effect. */ private final Moves captureEffect; /** The mover of this moves for simultaneous game (e.g. Rock-Paper-Scissors). */ private final RoleType mover; /** To move a complete stack. */ private final boolean stack; /** Cell/Edge/Vertex for the origin. */ private SiteType typeFrom; /** Cell/Edge/Vertex for the target. */ private SiteType typeTo; /** If true, we do not move the piece, we copy it. */ private final BooleanFunction copy; //------------------------------------------------------------------------- /** True if the to type was defined explicitly */ private final boolean typeToDefined; /** * @param from The data of the ``from'' location [(from)]. * @param to The data of the ``to'' location. * @param count The number of pieces to move. * @param copy Whether to duplicate the piece rather than moving it [False]. * @param stack To move a complete stack [False]. * @param mover The mover of the move. * @param then The moves applied after that move is applied. * * @example (fromTo (from (last To)) (to (last From))) * * @example (fromTo (from (handSite Mover)) (to (sites Empty))) * * @example (fromTo (from (to)) (to (sites Empty)) count:(count at:(to))) * * @example (fromTo (from (handSite Shared)) (to (sites Empty)) copy:True ) */ public FromTo ( final From from, final To to, @Opt @Name final IntFunction count, @Opt @Name final BooleanFunction copy, @Opt @Name final Boolean stack, @Opt final RoleType mover, @Opt final Then then ) { super(then); locFrom = from.loc(); fromCondition = from.cond(); levelFrom = from.level(); countFn = count; locTo = to.loc(); levelTo = to.level(); regionFrom = from.region(); regionTo = to.region(); moveRule = (to.cond() == null) ? new BooleanConstant(true) : to.cond(); captureRule = (to.effect() == null) ? null : to.effect().condition(); captureEffect = (to.effect() == null) ? null : to.effect().effect(); this.mover = mover; rotationTo = to.rotations(); this.stack = (stack == null) ? false : stack.booleanValue(); typeFrom = from.type(); typeTo = to.type(); typeToDefined = (to.type() != null); this.copy = (copy == null) ? new BooleanConstant(false) : copy; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final int[] sitesFrom = (regionFrom == null) ? new int[] { locFrom.eval(context) } : regionFrom.eval(context).sites(); final int origFrom = context.from(); final int origTo = context.to(); final BaseMoves moves = new BaseMoves(super.then()); final boolean stackingGame = context.currentInstanceContext().game().isStacking(); for (final int from : sitesFrom) { if (from > Constants.OFF) { final int cidFrom = from >= context.containerId().length ? 0 : context.containerId()[from]; SiteType realTypeFrom = typeFrom; if (cidFrom > 0) realTypeFrom = SiteType.Cell; else if (realTypeFrom == null) realTypeFrom = context.board().defaultSite(); final ContainerState cs = context.containerState(cidFrom); final int what = cs.what(from, realTypeFrom); if (what <= 0) continue; context.setFrom(from); final boolean copyTo = copy.eval(context); if (fromCondition != null && !fromCondition.eval(context)) continue; final int[] sitesTo = (regionTo == null) ? new int[] { locTo.eval(context) } : regionTo.eval(context).sites(); final int count = (countFn == null) ? 1 : countFn.eval(context); context.setFrom(origFrom); final Component component = context.components()[what]; // Special case for LargePiece. if (component != null && component.isLargePiece()) { final BaseMoves movesLargePiece = evalLargePiece(context, from, sitesTo); for (final Move m : movesLargePiece.moves()) moves.moves().add(m); continue; } for (final int to : sitesTo) { if (to > Constants.OFF) { // Get the right container id for 'to' and the right site type of the 'to'. int cidTo; SiteType realTypeTo = typeTo; if (typeToDefined) { cidTo = (!typeTo.equals(SiteType.Cell)) ? 0 : context.containerId()[to]; } else { cidTo = to >= context.containerId().length ? 0 : context.containerId()[to]; if (cidTo > 0) realTypeTo = SiteType.Cell; else if (realTypeTo == null) realTypeTo = context.board().defaultSite(); } final ContainerState csTo = context.containerState(cidTo); // Compute the right action to move the piece(s). final Action actionMove; if (levelTo != null) { if (!stack) { if (levelFrom == null) { actionMove = ActionMove.construct ( realTypeFrom, from, Constants.UNDEFINED, realTypeTo, to, levelTo.eval(context), Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false ); actionMove.setLevelFrom(cs.sizeStack(from, typeFrom) - 1); } else { actionMove = ActionMove.construct ( realTypeFrom, from, levelFrom.eval(context), realTypeTo, to, levelTo.eval(context), Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false ); } } else { actionMove = ActionMove.construct ( realTypeFrom, from, Constants.UNDEFINED, realTypeTo, to, levelTo.eval(context), Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, true ); actionMove.setLevelFrom(0); } } else if (levelFrom == null && countFn == null) { if (copyTo) { actionMove = new ActionCopy ( realTypeFrom, from, Constants.UNDEFINED, realTypeTo, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, false ); } else { actionMove = ActionMove.construct ( realTypeFrom, from, Constants.UNDEFINED, realTypeTo, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, stack ); } if(stack) actionMove.setLevelFrom(0); else actionMove.setLevelFrom(cs.sizeStack(from, typeFrom) - 1); } else if (levelFrom != null) { actionMove = ActionMove.construct ( realTypeFrom, from, levelFrom.eval(context), realTypeTo, to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false ); } else { if (!stackingGame && !stack) { actionMove = new ActionMoveN(realTypeFrom, from, realTypeTo, to, count); actionMove.setLevelFrom(cs.sizeStack(from, typeFrom) - 1); } // Move a sub stack. else { actionMove = new ActionSubStackMove(realTypeFrom, from, realTypeTo, to, count); actionMove.setLevelFrom(cs.sizeStack(from, realTypeFrom) - (count)); actionMove.setLevelTo(csTo.sizeStack(to, realTypeTo)); } } if (isDecision()) actionMove.setDecision(true); context.setFrom(from); context.setTo(to); if (moveRule.eval(context)) { context.setFrom(origFrom); Move move = new Move(actionMove); move.setFromNonDecision(from); move.setToNonDecision(to); // to add the levels to move a stack on the Move class (only for GUI) if (context.game().isStacking()) { if (levelFrom == null) { move.setLevelMinNonDecision(cs.sizeStack(from, realTypeFrom) - 1); move.setLevelMaxNonDecision(cs.sizeStack(from, realTypeFrom) - 1); } else { move.setLevelMinNonDecision(levelFrom.eval(context)); move.setLevelMaxNonDecision(levelFrom.eval(context)); } // To add the levels to move a stack on the Move class (only for GUI) if (stack) { move.setLevelMinNonDecision(0); move.setLevelMaxNonDecision(cs.sizeStack(from, realTypeFrom) - 1); move.setLevelFrom(0); } } if (rotationTo != null) { final int[] rotations = rotationTo.eval(context); for (final int rotation : rotations) { final Move moveWithRotation = new Move(move); final Action actionRotation = new ActionSetRotation(typeTo, to, rotation); moveWithRotation.actions().add(actionRotation); moves.moves().add(moveWithRotation); } } else if (captureRule == null || (captureRule != null && (captureRule.eval(context)))) { context.setFrom(from); context.setTo(to); move = MoveUtilities.chainRuleWithAction(context, captureEffect, move, true, false); move.setFromNonDecision(from); move.setToNonDecision(to); MoveUtilities.chainRuleCrossProduct(context, moves, null, move, false); } else { moves.moves().add(move); } } } } } } context.setTo(origTo); context.setFrom(origFrom); // We set the mover to the move. final int moverToSet = (mover == null) ? context.state().mover() : new Id(null, mover).eval(context); MoveUtilities.setGeneratedMovesData(moves.moves(), this, moverToSet); return moves; } //------------------------------------------------------------------------- private BaseMoves evalLargePiece(final Context context, final int from, final int[] sitesTo) { final int origFrom = context.from(); final int origTo = context.to(); final BaseMoves moves = new BaseMoves(super.then()); final ContainerState cs = context.containerState(context.containerId()[from]); final int what = cs.what(from, typeFrom); final int localState = cs.state(from, typeFrom); final Component largePiece = context.components()[what]; final int nbPossibleStates = largePiece.walk().length * 4; final TIntArrayList currentLocs = largePiece.locs(context, from, localState, context.topology()); final TIntArrayList newSitesTo = new TIntArrayList(); for (int i = 0; i < sitesTo.length; i++) newSitesTo.add(sitesTo[i]); for (int i = 1; i < currentLocs.size(); i++) newSitesTo.add(currentLocs.getQuick(i)); for (int index = 0; index < newSitesTo.size(); index++) { final int to = newSitesTo.getQuick(index); for (int state = 0; state < nbPossibleStates; state++) { final TIntArrayList locs = largePiece.locs(context, to, state, context.topology()); if (locs == null || locs.size() <= 0) continue; final ContainerState csTo = context.containerState(context.containerId()[locs.getQuick(0)]); boolean valid = true; for (int i = 0; i < locs.size(); i++) { if (!largePiece.isDomino()) { if (!newSitesTo.contains(locs.getQuick(i)) && locs.getQuick(i) != from) { valid = false; break; } } else if (!csTo.isPlayable(locs.getQuick(i)) && context.trial().moveNumber() > 0) { valid = false; break; } } if (valid && (from != to || (from == to) && localState != state)) { final Action actionMove = ActionMove.construct ( typeFrom, from, Constants.UNDEFINED, typeTo, to, Constants.OFF, state, Constants.OFF, Constants.OFF, false ); if (isDecision()) actionMove.setDecision(true); Move move = new Move(actionMove); move = MoveUtilities.chainRuleWithAction(context, captureEffect, move, true, false); move.setFromNonDecision(from); move.setToNonDecision(to); move.setStateNonDecision(state); MoveUtilities.chainRuleCrossProduct(context, moves, null, move, false); } } } context.setTo(origTo); context.setFrom(origFrom); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game); gameFlags |= GameType.UsesFromPositions; gameFlags |= SiteType.gameFlags(typeFrom); gameFlags |= SiteType.gameFlags(typeTo); if (locFrom != null) gameFlags |= locFrom.gameFlags(game); if (locTo != null) gameFlags |= locTo.gameFlags(game); if (fromCondition != null) gameFlags |= fromCondition.gameFlags(game); if (regionFrom != null) gameFlags |= regionFrom.gameFlags(game); if (captureRule != null) gameFlags |= captureRule.gameFlags(game); if (moveRule != null) gameFlags |= moveRule.gameFlags(game); if (levelTo != null) gameFlags |= levelTo.gameFlags(game); if (countFn != null) gameFlags |= countFn.gameFlags(game); if (captureEffect != null) gameFlags |= captureEffect.gameFlags(game); if (regionTo != null) gameFlags |= regionTo.gameFlags(game); if (levelFrom != null || stack) gameFlags |= GameType.Stacking; if (rotationTo != null) gameFlags |= rotationTo.gameFlags(game) | GameType.Rotation; gameFlags |= copy.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(SiteType.concepts(typeFrom)); concepts.or(SiteType.concepts(typeTo)); if(isDecision()) { concepts.set(Concept.FromToDecision.id(), true); if (moveRule.concepts(game).get(Concept.IsEmpty.id())) concepts.set(Concept.FromToDecisionEmpty.id(), true); if (moveRule.concepts(game).get(Concept.IsFriend.id())) concepts.set(Concept.FromToDecisionFriend.id(), true); if (moveRule.concepts(game).get(Concept.IsEnemy.id())) concepts.set(Concept.FromToDecisionEnemy.id(), true); if (moveRule instanceof BooleanConstant.TrueConstant) { concepts.set(Concept.FromToDecisionEmpty.id(), true); concepts.set(Concept.FromToDecisionFriend.id(), true); concepts.set(Concept.FromToDecisionEnemy.id(), true); } } else concepts.set(Concept.FromToEffect.id(), true); if (isDecision()) concepts.set(Concept.FromToDecision.id(), true); if (locFrom != null) concepts.or(locFrom.concepts(game)); if (fromCondition != null) concepts.or(fromCondition.concepts(game)); if (locTo != null) concepts.or(locTo.concepts(game)); if (regionFrom != null) concepts.or(regionFrom.concepts(game)); if (captureRule != null) concepts.or(captureRule.concepts(game)); if (levelTo != null) concepts.or(levelTo.concepts(game)); if (countFn != null) concepts.or(countFn.concepts(game)); if (captureEffect != null) concepts.or(captureEffect.concepts(game)); if (regionTo != null) concepts.or(regionTo.concepts(game)); if (rotationTo != null) concepts.or(rotationTo.concepts(game)); concepts.or(copy.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); // We check if that's effectively a capture (remove or fromTo). if (captureEffect != null) if (captureEffect.concepts(game).get(Concept.RemoveEffect.id()) || captureEffect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.ReplacementCapture.id(), true); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); if (locFrom != null) writeEvalContext.or(locFrom.writesEvalContextRecursive()); if (fromCondition != null) writeEvalContext.or(fromCondition.writesEvalContextRecursive()); if (locTo != null) writeEvalContext.or(locTo.writesEvalContextRecursive()); if (regionFrom != null) writeEvalContext.or(regionFrom.writesEvalContextRecursive()); if (captureRule != null) writeEvalContext.or(captureRule.writesEvalContextRecursive()); if (moveRule != null) writeEvalContext.or(moveRule.writesEvalContextRecursive()); if (levelTo != null) writeEvalContext.or(levelTo.writesEvalContextRecursive()); if (countFn != null) writeEvalContext.or(countFn.writesEvalContextRecursive()); if (captureEffect != null) writeEvalContext.or(captureEffect.writesEvalContextRecursive()); if (regionTo != null) writeEvalContext.or(regionTo.writesEvalContextRecursive()); if (rotationTo != null) writeEvalContext.or(rotationTo.writesEvalContextRecursive()); writeEvalContext.or(copy.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (locFrom != null) readEvalContext.or(locFrom.readsEvalContextRecursive()); if (fromCondition != null) readEvalContext.or(fromCondition.readsEvalContextRecursive()); if (locTo != null) readEvalContext.or(locTo.readsEvalContextRecursive()); if (regionFrom != null) readEvalContext.or(regionFrom.readsEvalContextRecursive()); if (captureRule != null) readEvalContext.or(captureRule.readsEvalContextRecursive()); if (moveRule != null) readEvalContext.or(moveRule.readsEvalContextRecursive()); if (levelTo != null) readEvalContext.or(levelTo.readsEvalContextRecursive()); if (countFn != null) readEvalContext.or(countFn.readsEvalContextRecursive()); if (captureEffect != null) readEvalContext.or(captureEffect.readsEvalContextRecursive()); if (regionTo != null) readEvalContext.or(regionTo.readsEvalContextRecursive()); if (rotationTo != null) readEvalContext.or(rotationTo.readsEvalContextRecursive()); readEvalContext.or(copy.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (locFrom != null) missingRequirement |= locFrom.missingRequirement(game); if (fromCondition != null) missingRequirement |= fromCondition.missingRequirement(game); if (locTo != null) missingRequirement |= locTo.missingRequirement(game); if (regionFrom != null) missingRequirement |= regionFrom.missingRequirement(game); if (captureRule != null) missingRequirement |= captureRule.missingRequirement(game); if (moveRule != null) missingRequirement |= moveRule.missingRequirement(game); if (levelTo != null) missingRequirement |= levelTo.missingRequirement(game); if (countFn != null) missingRequirement |= countFn.missingRequirement(game); if (captureEffect != null) missingRequirement |= captureEffect.missingRequirement(game); if (regionTo != null) missingRequirement |= regionTo.missingRequirement(game); if (rotationTo != null) missingRequirement |= rotationTo.missingRequirement(game); missingRequirement |= copy.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (locFrom != null) willCrash |= locFrom.willCrash(game); if (fromCondition != null) willCrash |= fromCondition.willCrash(game); if (locTo != null) willCrash |= locTo.willCrash(game); if (regionFrom != null) willCrash |= regionFrom.willCrash(game); if (captureRule != null) willCrash |= captureRule.willCrash(game); if (moveRule != null) willCrash |= moveRule.willCrash(game); if (levelTo != null) willCrash |= levelTo.willCrash(game); if (countFn != null) willCrash |= countFn.willCrash(game); if (captureEffect != null) willCrash |= captureEffect.willCrash(game); if (regionTo != null) willCrash |= regionTo.willCrash(game); if (rotationTo != null) willCrash |= rotationTo.willCrash(game); willCrash |= copy.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { boolean isStatic = true; if (locFrom != null) isStatic = isStatic && locFrom.isStatic(); if (fromCondition != null) isStatic = isStatic && fromCondition.isStatic(); if (locTo != null) isStatic = isStatic && locTo.isStatic(); if (regionFrom != null) isStatic = isStatic && regionFrom.isStatic(); if (regionTo != null) isStatic = isStatic && regionTo.isStatic(); isStatic = isStatic && copy.isStatic(); return isStatic; } @Override public void preprocess(final Game game) { if (typeFrom == null) typeFrom = game.board().defaultSite(); if (typeTo == null) typeTo = game.board().defaultSite(); super.preprocess(game); if (locFrom != null) locFrom.preprocess(game); if (fromCondition != null) fromCondition.preprocess(game); if (locTo != null) locTo.preprocess(game); if (regionFrom != null) regionFrom.preprocess(game); if (regionTo != null) regionTo.preprocess(game); if (rotationTo != null) rotationTo.preprocess(game); if (levelFrom != null) levelFrom.preprocess(game); if (countFn != null) countFn.preprocess(game); if (levelTo != null) levelTo.preprocess(game); if (moveRule != null) moveRule.preprocess(game); if (captureRule != null) captureRule.preprocess(game); if (captureEffect != null) captureEffect.preprocess(game); copy.preprocess(game); } //------------------------------------------------------------------------- /** * @return Location to move from */ public IntFunction locFrom() { return locFrom; } /** * @return Location to move to */ public IntFunction locTo() { return locTo; } /** * @return Region to move from */ public RegionFunction regionFrom() { return regionFrom; } /** * @return Region to move to */ public RegionFunction regionTo() { return regionTo; } /** * @return Move rule */ public BooleanFunction moveRule() { return moveRule; } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { final SiteType realTypeFrom = (typeFrom != null) ? typeFrom : game.board().defaultSite(); String englishString = "from " + realTypeFrom.name().toLowerCase() + (regionFrom == null ? "" : " in " + regionFrom.toEnglish(game)) + (locFrom == null ? "" : " in " + locFrom.toEnglish(game)) + (levelFrom == null ? "" : " " + levelFrom.toEnglish(game)) + (fromCondition == null ? "" : " if " + fromCondition.toEnglish(game)); final SiteType realTypeTo = (typeTo != null) ? typeTo : game.board().defaultSite(); if (regionTo != null) englishString += " to " + realTypeTo.name().toLowerCase() + " in " + regionTo.toEnglish(game) + (levelTo == null ? "" : " " + levelTo.toEnglish(game)); if (locTo != null) englishString += " to " + realTypeTo.name().toLowerCase() + " " + locTo.toEnglish(game) + (levelTo == null ? "" : " " + levelTo.toEnglish(game)); if (moveRule != null) englishString += " moveRule: " + moveRule.toEnglish(game); if (captureRule != null) englishString += " captureRule: " + captureRule.toEnglish(game); if (captureEffect != null) englishString += " captureEffect: " + captureEffect.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); englishString += thenString; return englishString; } //------------------------------------------------------------------------- }
27,377
26.160714
120
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Hop.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Name; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanConstant; import game.functions.booleans.BooleanFunction; import game.functions.directions.Directions; import game.functions.directions.DirectionsFunction; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.iterator.From; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import game.util.directions.AbsoluteDirection; import game.util.graph.GraphElement; import game.util.graph.Radial; import game.util.moves.To; import gnu.trove.list.array.TIntArrayList; import main.Constants; import main.collections.FastTIntArrayList; import other.action.Action; import other.action.move.move.ActionMove; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.Move; import other.move.MoveUtilities; import other.state.stacking.BaseContainerStateStacking; import other.topology.Topology; import other.topology.TopologyElement; import other.trial.Trial; /** * Defines a hop in which a piece hops over a hurdle (the {\it pivot}) in a direction. * * @author Eric.Piette and cambolbro * * @remarks Capture moves in Draughts are typical hop moves. * Note that we extend the standard definition of ``hop'' to include cases * where the pivot is empty, for example in games such as Lines of Action * and Quantum Leap. */ public final class Hop extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** Direction chosen. */ private final DirectionsFunction dirnChoice; /** Move without to reach the hurdle. */ private final BooleanFunction goRule; /** To detect the hurdle. */ private final BooleanFunction hurdleRule; /** Rule to stop the move after to jump the hurdle. */ private final BooleanFunction stopRule; /** Effect on the stop component corresponding to the stopRule. */ private final Moves stopEffect; /** Maximum distance between from and the hurdle. */ private final IntFunction maxDistanceFromHurdleFn; /** Minimum length of the hurdle. */ private final IntFunction minLengthHurdleFn; /** Maximum length of the hurdle. */ private final IntFunction maxLengthHurdleFn; /** Maximum distance between the hurdle and to. */ private final IntFunction maxDistanceHurdleToFn; /** From Condition Rule. */ private final BooleanFunction fromCondition; /** effect on the Hurdle. */ private final Moves sideEffect; /** To Hop with a complete stack. */ private final boolean stack; /** Add on Cell/Edge/Vertex. */ protected SiteType type; //------------------------------------------------------------------------- /** * @param from The data of the from location [(from)]. * @param directions The directions of the move [Adjacent]. * @param between The information about the locations between ``from'' and * ``to'' [(between if:true)]. * @param to The condition on the location to move. * @param stack True if the move has to be applied for stack [False]. * @param then The moves applied after that move is applied. * * @example (hop (between if:(is Enemy (who at:(between))) (apply (remove * (between))) ) (to if:(is Empty (to))) ) * * @example (hop Orthogonal (between if:(is Friend (who at:(between))) (apply * (remove (between))) ) (to if:(is Empty (to))) ) */ public Hop ( @Opt final game.util.moves.From from, @Opt final game.util.directions.Direction directions, @Opt final game.util.moves.Between between, final To to, @Opt @Name final Boolean stack, @Opt final Then then ) { super(then); startLocationFn = (from == null || from.loc() == null) ? new From(null) : from.loc(); fromCondition = (from == null) ? null : from.cond(); type = (from == null) ? null : from.type(); maxDistanceFromHurdleFn = (between == null || between.before() == null ? new IntConstant(0) : between.before()); minLengthHurdleFn = (between == null || between.range() == null) ? new IntConstant(1) : between.range().minFn(); maxLengthHurdleFn = (between == null || between.range() == null) ? new IntConstant(1) : between.range().maxFn(); maxDistanceHurdleToFn = (between == null || between.after() == null ? new IntConstant(0) : between.after()); sideEffect = between == null ? null : between.effect(); goRule = to.cond(); hurdleRule = (between == null) ? new BooleanConstant(true): between.condition(); dirnChoice = (directions != null) ? directions.directionsFunctions() : new Directions(AbsoluteDirection.Adjacent, null); // Stop effect stopRule = (to.effect() == null) ? null : to.effect().condition(); stopEffect = (to.effect() == null) ? null : to.effect().effect(); // Stack this.stack = (stack == null) ? false : stack.booleanValue(); } //------------------------------------------------------------------------- @Override public final Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); if (from == Constants.OFF) return moves; final int origFrom = context.from(); final int origTo = context.to(); final int origBetween = context.between(); final Topology graph = context.topology(); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); final TopologyElement fromV = graph.getGraphElements(realType).get(from); final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, fromV, null, null, null, context); final int maxDistanceFromHurdle = maxDistanceFromHurdleFn.eval(context); final int minLengthHurdle = minLengthHurdleFn.eval(context); final int maxLengthHurdle = (minLengthHurdleFn == maxLengthHurdleFn) ? minLengthHurdle : maxLengthHurdleFn.eval(context); final int maxDistanceHurdleTo = maxDistanceHurdleToFn.eval(context); context.setFrom(from); // If the min length is 0 we can step. if (minLengthHurdle == 0) { for (final AbsoluteDirection direction : directions) { final List<game.util.graph.Step> steps = graph.trajectories().steps(realType, from, realType, direction); for (final game.util.graph.Step step : steps) { final int to = step.to().id(); // context.setFrom(from); if (fromCondition != null && !fromCondition.eval(context)) continue; context.setTo(to); if (!goRule.eval(context)) continue; if (!alreadyCompute(moves, from, to)) { final Action action = ActionMove.construct(type, from, Constants.UNDEFINED, type, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, stack); if (isDecision()) action.setDecision(true); Move thisAction = new Move(action); // to add the levels to move a stack on the Move class (only for GUI) if (stack) { thisAction.setLevelMinNonDecision(0); thisAction.setLevelMaxNonDecision(((BaseContainerStateStacking) context.state().containerStates()[0]) .sizeStack(from, type) - 1); } thisAction = MoveUtilities.chainRuleWithAction(context, sideEffect, thisAction, true, false); MoveUtilities.chainRuleCrossProduct(context, moves, null, thisAction, false); thisAction.setFromNonDecision(from); thisAction.setToNonDecision(to); } } } // context.setTo(origTo); // context.setFrom(origFrom); } // From here the code to hop at least a site. if (maxLengthHurdle > 0) for (final AbsoluteDirection direction : directions) { final List<Radial> radialList = graph.trajectories().radials(type, from, direction); for (final Radial radial : radialList) { final GraphElement[] steps = radial.steps(); for (int toIdx = 1; toIdx < steps.length; toIdx++) { final FastTIntArrayList betweenSites = new FastTIntArrayList(); final int between = steps[toIdx].id(); //context.setFrom(from); if (fromCondition != null && !fromCondition.eval(context)) continue; context.setBetween(between); if (hurdleRule != null && (hurdleRule.eval(context))) { final TIntArrayList hurdleLocs = new TIntArrayList(); hurdleLocs.add(between); int lengthHurdle = 1; int hurdleIdx = toIdx + 1; boolean hurdleWrong = false; for (/**/; hurdleIdx < steps.length && lengthHurdle < maxLengthHurdle; hurdleIdx++) { final int hurdleLoc = steps[hurdleIdx].id(); context.setBetween(hurdleLoc); if (!hurdleRule.eval(context)) { hurdleWrong = true; break; } hurdleLocs.add(hurdleLoc); lengthHurdle++; } if (lengthHurdle < minLengthHurdle || (hurdleWrong && lengthHurdle == maxLengthHurdle)) break; betweenSites.addAll(hurdleLocs); // Jump between the min size of the hurdle to the length of the hurdle detected. for (int fromMinHurdle = lengthHurdle - minLengthHurdle; fromMinHurdle >= 0; fromMinHurdle--) { int afterHurdleToIdx = hurdleIdx - fromMinHurdle; for (/**/; afterHurdleToIdx < steps.length; afterHurdleToIdx++) { final int afterHurdleTo = steps[afterHurdleToIdx].id(); //context.setFrom(from); context.setTo(afterHurdleTo); if (!goRule.eval(context)) { if (stopRule != null && stopRule.eval(context)) { final Action action = ActionMove.construct(type, from, Constants.UNDEFINED, type, afterHurdleTo, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, stack); if (isDecision()) action.setDecision(true); Move move = new Move(action); if (stopEffect != null) move = MoveUtilities.chainRuleWithAction(context, stopEffect, move, true, false); MoveUtilities.chainRuleCrossProduct(context, moves, null, move, false); move.setFromNonDecision(from); move.setBetweenNonDecision(new FastTIntArrayList(betweenSites)); move.setToNonDecision(afterHurdleTo); } break; } if (stopRule == null) { final Action action = ActionMove.construct(type, from, Constants.UNDEFINED, type, afterHurdleTo, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, stack); if (isDecision()) action.setDecision(true); Move move = new Move(action); if (stopEffect != null) move = MoveUtilities.chainRuleWithAction(context, stopEffect, move, true, false); for (int hurdleLocIndex = 0; hurdleLocIndex < hurdleLocs.size() - fromMinHurdle; hurdleLocIndex++) { final int hurdleLoc = hurdleLocs.getQuick(hurdleLocIndex); context.setBetween(hurdleLoc); if (sideEffect != null) move = MoveUtilities.chainRuleWithAction(context, sideEffect, move, true, false); } MoveUtilities.chainRuleCrossProduct(context, moves, null, move, false); move.setFromNonDecision(from); move.setBetweenNonDecision(new FastTIntArrayList(betweenSites)); move.setToNonDecision(afterHurdleTo); // to add the levels to move a stack on the Move class (only for GUI) if (stack) { move.setLevelMinNonDecision(0); move.setLevelMaxNonDecision( ((BaseContainerStateStacking) context.state().containerStates()[0]) .sizeStack(from, type) - 1); } } if ((afterHurdleToIdx - hurdleIdx + 1) > (maxDistanceHurdleTo - fromMinHurdle)) break; } } break; } context.setTo(between); if (toIdx > maxDistanceFromHurdle || (!goRule.eval(context))) break; } } } context.setTo(origTo); context.setFrom(origFrom); context.setBetween(origBetween); MoveUtilities.setGeneratedMovesData(moves.moves(), this, context.state().mover()); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game); gameFlags |= GameType.UsesFromPositions; if (stack) gameFlags |= GameType.Stacking; if (goRule != null) gameFlags |= goRule.gameFlags(game); if (startLocationFn != null) gameFlags |= startLocationFn.gameFlags(game); if (fromCondition != null) gameFlags |= fromCondition.gameFlags(game); if (hurdleRule != null) gameFlags |= hurdleRule.gameFlags(game); if (maxDistanceFromHurdleFn != null) gameFlags = gameFlags | maxDistanceFromHurdleFn.gameFlags(game); if (maxDistanceHurdleToFn != null) gameFlags = gameFlags | maxDistanceHurdleToFn.gameFlags(game); if (maxLengthHurdleFn != null) gameFlags = gameFlags | maxLengthHurdleFn.gameFlags(game); if (minLengthHurdleFn != null) gameFlags = gameFlags | minLengthHurdleFn.gameFlags(game); if (sideEffect != null) gameFlags = gameFlags | sideEffect.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(SiteType.concepts(type)); if(isDecision()) { concepts.set(Concept.HopDecision.id(), true); if (hurdleRule != null && goRule != null) { if ((goRule.concepts(game).get(Concept.IsEmpty.id()) || goRule instanceof BooleanConstant.TrueConstant) && (hurdleRule.concepts(game).get(Concept.IsEnemy.id()) || hurdleRule instanceof BooleanConstant.TrueConstant)) concepts.set(Concept.HopDecisionEnemyToEmpty.id(), true); if ((goRule.concepts(game).get(Concept.IsEmpty.id()) || goRule instanceof BooleanConstant.TrueConstant) && (hurdleRule.concepts(game).get(Concept.IsFriend.id()) || hurdleRule instanceof BooleanConstant.TrueConstant)) concepts.set(Concept.HopDecisionFriendToEmpty.id(), true); if ((goRule.concepts(game).get(Concept.IsFriend.id()) || goRule instanceof BooleanConstant.TrueConstant) && (hurdleRule.concepts(game).get(Concept.IsEnemy.id()) || hurdleRule instanceof BooleanConstant.TrueConstant)) concepts.set(Concept.HopDecisionEnemyToFriend.id(), true); if ((goRule.concepts(game).get(Concept.IsFriend.id()) || goRule instanceof BooleanConstant.TrueConstant) && (hurdleRule.concepts(game).get(Concept.IsFriend.id()) || hurdleRule instanceof BooleanConstant.TrueConstant)) concepts.set(Concept.HopDecisionFriendToFriend.id(), true); if ((goRule.concepts(game).get(Concept.IsEnemy.id()) || goRule instanceof BooleanConstant.TrueConstant) && (hurdleRule.concepts(game).get(Concept.IsEnemy.id()) || hurdleRule instanceof BooleanConstant.TrueConstant)) concepts.set(Concept.HopDecisionEnemyToEnemy.id(), true); if ((goRule.concepts(game).get(Concept.IsEnemy.id()) || goRule instanceof BooleanConstant.TrueConstant) && (hurdleRule.concepts(game).get(Concept.IsFriend.id()) || hurdleRule instanceof BooleanConstant.TrueConstant)) concepts.set(Concept.HopDecisionFriendToEnemy.id(), true); } } else concepts.set(Concept.HopEffect.id(), true); if (goRule != null) concepts.or(goRule.concepts(game)); if (fromCondition != null) concepts.or(fromCondition.concepts(game)); if (startLocationFn != null) concepts.or(startLocationFn.concepts(game)); if (hurdleRule != null) concepts.or(hurdleRule.concepts(game)); if (maxDistanceFromHurdleFn != null) concepts.or(maxDistanceFromHurdleFn.concepts(game)); if (maxDistanceHurdleToFn != null) concepts.or(maxDistanceHurdleToFn.concepts(game)); if (maxLengthHurdleFn != null) concepts.or(maxLengthHurdleFn.concepts(game)); if (minLengthHurdleFn != null) concepts.or(minLengthHurdleFn.concepts(game)); if (sideEffect != null) concepts.or(sideEffect.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); if (dirnChoice != null) concepts.or(dirnChoice.concepts(game)); // We check if that's effectively a replacement capture (remove or fromTo). if (stopEffect != null) if (stopEffect.concepts(game).get(Concept.RemoveEffect.id()) || stopEffect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.ReplacementCapture.id(), true); // We check if that's effectively a hop capture (remove or fromTo). if (sideEffect != null) if (sideEffect.concepts(game).get(Concept.RemoveEffect.id()) || sideEffect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.HopCapture.id(), true); // We check if some pieces can jump more than one site. if (isDecision()) { if (minLengthHurdleFn instanceof IntConstant) { if (((IntConstant) minLengthHurdleFn).eval(new Context(game, new Trial(game))) > 1) concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } else concepts.set(Concept.HopDecisionMoreThanOne.id(), true); if (maxLengthHurdleFn instanceof IntConstant) { if (((IntConstant) maxLengthHurdleFn).eval(new Context(game, new Trial(game))) > 1) concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } else concepts.set(Concept.HopDecisionMoreThanOne.id(), true); // If the pieces jumped are potentially more than one and capture is // activated we active the HopCaptureMoreThanOne too. if (concepts.get(Concept.HopDecisionMoreThanOne.id()) && concepts.get(Concept.HopCapture.id())) concepts.set(Concept.HopCaptureMoreThanOne.id()); if (maxDistanceHurdleToFn instanceof IntConstant) { if (((IntConstant) maxDistanceHurdleToFn).eval(new Context(game, new Trial(game))) > 1) concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } else concepts.set(Concept.HopDecisionMoreThanOne.id(), true); if (maxDistanceFromHurdleFn instanceof IntConstant) { if (((IntConstant) maxDistanceFromHurdleFn).eval(new Context(game, new Trial(game))) > 1) concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } else concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); if (goRule != null) writeEvalContext.or(goRule.writesEvalContextRecursive()); if (fromCondition != null) writeEvalContext.or(fromCondition.writesEvalContextRecursive()); if (startLocationFn != null) writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); if (hurdleRule != null) writeEvalContext.or(hurdleRule.writesEvalContextRecursive()); if (maxDistanceFromHurdleFn != null) writeEvalContext.or(maxDistanceFromHurdleFn.writesEvalContextRecursive()); if (maxDistanceHurdleToFn != null) writeEvalContext.or(maxDistanceHurdleToFn.writesEvalContextRecursive()); if (maxLengthHurdleFn != null) writeEvalContext.or(maxLengthHurdleFn.writesEvalContextRecursive()); if (minLengthHurdleFn != null) writeEvalContext.or(minLengthHurdleFn.writesEvalContextRecursive()); if (sideEffect != null) writeEvalContext.or(sideEffect.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); if (dirnChoice != null) writeEvalContext.or(dirnChoice.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); writeEvalContext.set(EvalContextData.Between.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (goRule != null) readEvalContext.or(goRule.readsEvalContextRecursive()); if (fromCondition != null) readEvalContext.or(fromCondition.readsEvalContextRecursive()); if (startLocationFn != null) readEvalContext.or(startLocationFn.readsEvalContextRecursive()); if (hurdleRule != null) readEvalContext.or(hurdleRule.readsEvalContextRecursive()); if (maxDistanceFromHurdleFn != null) readEvalContext.or(maxDistanceFromHurdleFn.readsEvalContextRecursive()); if (maxDistanceHurdleToFn != null) readEvalContext.or(maxDistanceHurdleToFn.readsEvalContextRecursive()); if (maxLengthHurdleFn != null) readEvalContext.or(maxLengthHurdleFn.readsEvalContextRecursive()); if (minLengthHurdleFn != null) readEvalContext.or(minLengthHurdleFn.readsEvalContextRecursive()); if (sideEffect != null) readEvalContext.or(sideEffect.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); if (dirnChoice != null) readEvalContext.or(dirnChoice.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (goRule != null) missingRequirement |= goRule.missingRequirement(game); if (fromCondition != null) missingRequirement |= fromCondition.missingRequirement(game); if (startLocationFn != null) missingRequirement |= startLocationFn.missingRequirement(game); if (hurdleRule != null) missingRequirement |= hurdleRule.missingRequirement(game); if (maxDistanceFromHurdleFn != null) missingRequirement |= maxDistanceFromHurdleFn.missingRequirement(game); if (maxDistanceHurdleToFn != null) missingRequirement |= maxDistanceHurdleToFn.missingRequirement(game); if (maxLengthHurdleFn != null) missingRequirement |= maxLengthHurdleFn.missingRequirement(game); if (minLengthHurdleFn != null) missingRequirement |= minLengthHurdleFn.missingRequirement(game); if (sideEffect != null) missingRequirement |= sideEffect.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (fromCondition != null) willCrash |= fromCondition.willCrash(game); if (goRule != null) willCrash |= goRule.willCrash(game); if (startLocationFn != null) willCrash |= startLocationFn.willCrash(game); if (hurdleRule != null) willCrash |= hurdleRule.willCrash(game); if (maxDistanceFromHurdleFn != null) willCrash |= maxDistanceFromHurdleFn.willCrash(game); if (maxDistanceHurdleToFn != null) willCrash |= maxDistanceHurdleToFn.willCrash(game); if (maxLengthHurdleFn != null) willCrash |= maxLengthHurdleFn.willCrash(game); if (minLengthHurdleFn != null) willCrash |= minLengthHurdleFn.willCrash(game); if (sideEffect != null) willCrash |= sideEffect.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); if (goRule != null) goRule.preprocess(game); if (stopRule != null) stopRule.preprocess(game); if (fromCondition != null) fromCondition.preprocess(game); if (stopEffect != null) stopEffect.preprocess(game); if (startLocationFn != null) startLocationFn.preprocess(game); if (hurdleRule != null) hurdleRule.preprocess(game); if (maxDistanceFromHurdleFn != null) maxDistanceFromHurdleFn.preprocess(game); if (maxDistanceHurdleToFn != null) maxDistanceHurdleToFn.preprocess(game); if (maxLengthHurdleFn != null) maxLengthHurdleFn.preprocess(game); if (minLengthHurdleFn != null) minLengthHurdleFn.preprocess(game); if (sideEffect != null) sideEffect.preprocess(game); } //------------------------------------------------------------------------- /** * @return Rule that tells us the kinds of cells we're allowed to traverse * on the way to the hurdle. */ public BooleanFunction goRule() { return goRule; } /** * @return Rule that tells us what kinds of cells are recognised as hurdle */ public BooleanFunction hurdleRule() { return hurdleRule; } /** * @return Maximum number of steps we're allowed to take to reach a hurdle */ public IntFunction maxDistanceFromHurdleFn() { return maxDistanceFromHurdleFn; } /** * @return Minimum number of steps that must be occupied by hurdle */ public IntFunction minLengthHurdleFn() { return minLengthHurdleFn; } /** * @return Maximum number of steps that must be occupied by hurdle */ public IntFunction maxLengthHurdleFn() { return maxLengthHurdleFn; } /** * @return Maximum number of steps we're allowed to take "behind" hurdle */ public IntFunction maxDistanceHurdleToFn() { return maxDistanceHurdleToFn; } /** * To know if a move is already compute (for wheel board with the center, this * is possible). * * @param moves * @param from * @param to * @return */ private static boolean alreadyCompute(final Moves moves, final int from, final int to) { for (final Move m : moves.moves()) { if (m.fromNonDecision() == from && m.toNonDecision() == to) { return true; } } return false; } @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "hop " + dirnChoice.toEnglish(game) + thenString; } }
26,531
30.548157
181
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Intervene.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanFunction; import game.functions.booleans.is.player.IsEnemy; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.iterator.To; import game.functions.ints.last.LastTo; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import game.util.directions.AbsoluteDirection; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import main.StringRoutines; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.MoveUtilities; import other.topology.Topology; import other.topology.TopologyElement; /** * Is used to apply an effect to all the sites flanking a site. * * @author Eric.Piette */ public final class Intervene extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** Direction chosen. */ private final AbsoluteDirection dirnChoice; /** Limit to intervene. */ private final IntFunction limit; /** Min to intervene. */ private final IntFunction min; /** The piece to intervene. */ private final BooleanFunction targetRule; /** The effect to apply on the pieces flanked. */ private final Moves targetEffect; /** Add on Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** * @param from The data about the sites to intervene [(from (last To))]. * @param dirnChoice The direction to compute the flanking [Adjacent]. * @param between The condition on the pieces flanked [(between (exact 1))]. * @param to The condition and effect on the pieces flanking [(to if:(is * Enemy (who at:(to))) (apply (remove (to))))]. * @param then The moves applied after that move is applied. * * @example (intervene (from (last To)) (to if:(is Enemy (who at:(to))) (apply * (remove (to))) ) ) */ public Intervene ( @Opt final game.util.moves.From from, @Opt final AbsoluteDirection dirnChoice, @Opt final game.util.moves.Between between, @Opt final game.util.moves.To to, @Opt final Then then ) { super(then); startLocationFn = (from == null) ? new LastTo(null) : from.loc(); type = (from == null) ? null : from.type(); limit = (between == null || between.range() == null) ? new IntConstant(1) : between.range().maxFn(); min = (between == null || between.range() == null) ? new IntConstant(1) : between.range().minFn(); this.dirnChoice = (dirnChoice == null) ? AbsoluteDirection.Adjacent : dirnChoice; targetRule = (to == null || to.cond() == null) ? new IsEnemy(To.instance(), null) : to.cond(); targetEffect = (to == null || to.effect() == null) ? new Remove(null, To.instance(), null, null, null, null, null) : to.effect(); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); final int fromOrig = context.from(); final int toOrig = context.to(); final Topology graph = context.topology(); if (from == Constants.UNDEFINED) return new BaseMoves(null); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); final TopologyElement fromV = graph.getGraphElements(realType).get(from); final List<Radial> radialList = graph.trajectories().radials(type, fromV.index()) .distinctInDirection(dirnChoice); final int minPathLength = min.eval(context); final int maxPathLength = limit.eval(context); if (maxPathLength == 1 && minPathLength == 1) shortSandwich(context, moves, fromV, radialList); else longSandwich(context, moves, fromV, radialList, maxPathLength, minPathLength); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); context.setTo(toOrig); context.setFrom(fromOrig); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } /** * To compute a short flank (= 1). * * @param context * @param actions * @param fromV * @param directionIndices */ private void shortSandwich(final Context context, final Moves actions, final TopologyElement fromV, final List<Radial> radials) { for (final Radial radial : radials) { if (radial.steps().length < 2 || !isTarget(context, radial.steps()[1].id())) continue; final List<Radial> oppositeRadials = radial.opposites(); if (oppositeRadials != null) { boolean oppositeFound = false; for (final Radial oppositeRadial : oppositeRadials) { if (oppositeRadial.steps().length < 2 || !isTarget(context, oppositeRadial.steps()[1].id())) continue; context.setTo(oppositeRadial.steps()[1].id()); MoveUtilities.chainRuleCrossProduct(context, actions, targetEffect, null, false); oppositeFound = true; } if (oppositeFound) { context.setTo(radial.steps()[1].id()); MoveUtilities.chainRuleCrossProduct(context, actions, targetEffect, null, false); } } } } private boolean isTarget(final Context context, final int location) { context.setTo(location); return targetRule.eval(context); } /** * To compute a longer flank (> 1). * * @param context * @param actions * @param fromV * @param directionIndices * @param maxPathLength */ private void longSandwich(final Context context, final Moves actions, final TopologyElement fromV, final List<Radial> radials, final int maxPathLength, final int minPathLength) { for (final Radial radial : radials) { final TIntArrayList sitesToIntervene = new TIntArrayList(); int posIdx = 1; while (posIdx < radial.steps().length && posIdx <= maxPathLength) { if (!isTarget(context, radial.steps()[posIdx].id())) break; sitesToIntervene.add(radial.steps()[posIdx].id()); posIdx++; } if (sitesToIntervene.size() < minPathLength || sitesToIntervene.size() > maxPathLength) continue; final List<Radial> oppositeRadials = radial.opposites(); if (oppositeRadials != null) { final TIntArrayList sitesOppositeToIntervene = new TIntArrayList(); boolean oppositeFound = false; for (final Radial oppositeRadial : oppositeRadials) { int posOppositeIdx = 1; while (posOppositeIdx < oppositeRadial.steps().length && posOppositeIdx <= maxPathLength) { if (!isTarget(context, oppositeRadial.steps()[posOppositeIdx].id())) break; sitesOppositeToIntervene.add(oppositeRadial.steps()[posOppositeIdx].id()); posOppositeIdx++; } if (sitesOppositeToIntervene.size() < minPathLength || sitesOppositeToIntervene.size() > maxPathLength) continue; for (int i = 0; i < sitesOppositeToIntervene.size(); i++) { final int oppositeSite = sitesOppositeToIntervene.get(i); context.setTo(oppositeSite); MoveUtilities.chainRuleCrossProduct(context, actions, targetEffect, null, false); } oppositeFound = true; } if (oppositeFound) { for (int i = 0; i < sitesToIntervene.size(); i++) { final int oppositeSite = sitesToIntervene.get(i); context.setTo(oppositeSite); MoveUtilities.chainRuleCrossProduct(context, actions, targetEffect, null, false); } } } } } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | startLocationFn.gameFlags(game) | limit.gameFlags(game) | min.gameFlags(game) | targetRule.gameFlags(game) | targetEffect.gameFlags(game); gameFlags |= GameType.UsesFromPositions; gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); concepts.or(startLocationFn.concepts(game)); concepts.or(limit.concepts(game)); concepts.or(min.concepts(game)); concepts.or(targetRule.concepts(game)); concepts.or(targetEffect.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); // We check if that's effectively a capture (remove or fromTo). if (targetEffect.concepts(game).get(Concept.RemoveEffect.id()) || targetEffect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.InterveneCapture.id(), true); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); writeEvalContext.or(limit.writesEvalContextRecursive()); writeEvalContext.or(min.writesEvalContextRecursive()); writeEvalContext.or(targetRule.writesEvalContextRecursive()); writeEvalContext.or(targetEffect.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(startLocationFn.readsEvalContextRecursive()); readEvalContext.or(limit.readsEvalContextRecursive()); readEvalContext.or(min.readsEvalContextRecursive()); readEvalContext.or(targetRule.readsEvalContextRecursive()); readEvalContext.or(targetEffect.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= startLocationFn.missingRequirement(game); missingRequirement |= limit.missingRequirement(game); missingRequirement |= min.missingRequirement(game); missingRequirement |= targetRule.missingRequirement(game); missingRequirement |= targetEffect.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= startLocationFn.willCrash(game); willCrash |= limit.willCrash(game); willCrash |= min.willCrash(game); willCrash |= targetRule.willCrash(game); willCrash |= targetEffect.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return startLocationFn.isStatic() && limit.isStatic() && targetRule.isStatic() && targetEffect.isStatic() && min.isStatic(); } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); startLocationFn.preprocess(game); min.preprocess(game); limit.preprocess(game); targetRule.preprocess(game); targetEffect.preprocess(game); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String directionString = ""; if (dirnChoice != null) directionString = " in direction " + dirnChoice.toString(); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); final SiteType realType = (type != null) ? type : game.board().defaultSite(); return "apply " + targetEffect.toEnglish(game) + " to all sites flanking " + realType.name() + StringRoutines.getPlural(realType.name()) + " " + startLocationFn.toEnglish(game) + directionString + thenString; } //------------------------------------------------------------------------- }
12,751
29.801932
210
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Leap.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Name; import annotations.Opt; import game.Game; import game.equipment.component.Component; import game.functions.booleans.BooleanConstant; import game.functions.booleans.BooleanFunction; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.iterator.From; import game.functions.region.RegionFunction; import game.functions.region.sites.Sites; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.board.StepType; import game.types.state.GameType; import game.util.directions.CompassDirection; import game.util.moves.To; import main.Constants; import other.ContainerId; import other.action.Action; import other.action.move.move.ActionMove; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.Move; import other.move.MoveUtilities; import other.topology.TopologyElement; /** * Allows a player to leap a piece to sites defined by walks through the board graph. * * @author Eric.Piette and cambolbro * * @remarks Use this ludeme to make leaping moves to pre-defined destination sites * that do not care about intervening pieces, such as knight moves in Chess. */ public final class Leap extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** From Condition Rule. */ private final BooleanFunction fromCondition; /** The specific walk of the move. */ private final RegionFunction walk; /** If the leap has to be only in a forward direction. */ private final BooleanFunction forward; /** The rule to continue the move */ private final BooleanFunction goRule; /** The Move applied on the location reached. */ private final Moves sideEffect; /** Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** * @param from The site to leap from [(from)]. * @param walk The walk that defines the landing site(s). * @param forward Whether to only keep moves that land forwards [False]. * @param rotations Whether to apply the leap to all rotations [True]. * @param to Details about the site to move to. * @param then Moves to apply after the leap. * * @example (leap { {F F R F} {F F L F} } (to if:(or (is Empty (to)) (is Enemy * (who at:(to)))) (apply (if (is Enemy (who at:(to))) (remove (to) ) ) * ) ) ) */ public Leap ( @Opt final game.util.moves.From from, final StepType[][] walk, @Opt @Name final BooleanFunction forward, @Opt @Name final BooleanFunction rotations, final To to, @Opt final Then then ) { super(then); startLocationFn = (from == null) ? new From(null) : from.loc(); fromCondition = (from == null) ? null : from.cond(); type = (from == null) ? null : from.type(); this.walk = Sites.construct(null, startLocationFn, walk, rotations); this.forward = (forward == null) ? new BooleanConstant(false) : forward; goRule = to.cond(); sideEffect = to.effect(); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); final int cid = new ContainerId(null, null, null, null, new IntConstant(from)).eval(context); final other.topology.Topology graph = context.containers()[cid].topology(); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); CompassDirection facing = null; if (forward.eval(context)) { final int pieceIndex = context.state().containerStates()[cid].what(from, type); if (pieceIndex != 0) { final Component piece = context.game().equipment().components()[pieceIndex]; facing = (CompassDirection) piece.getDirn(); } } if (from == Constants.OFF) return moves; final int origFrom = context.from(); final int origTo = context.to(); context.setFrom(from); if (fromCondition != null && !fromCondition.eval(context)) return moves; final int[] sitesAfterWalk = walk.eval(context).sites(); for (final int to : sitesAfterWalk) { final TopologyElement fromV = graph.getGraphElement(realType, from); final TopologyElement toV = graph.getGraphElement(realType, to); if (facing == null || checkForward(facing, fromV, toV)) { context.setTo(to); if (!goRule.eval(context)) continue; final Action actionMove = ActionMove.construct(realType, from, Constants.UNDEFINED, realType, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, false); if (isDecision()) actionMove.setDecision(true); Move thisAction = new Move(actionMove); thisAction = MoveUtilities.chainRuleWithAction(context, sideEffect, thisAction, true, false); MoveUtilities.chainRuleCrossProduct(context, moves, null, thisAction, false); thisAction.setFromNonDecision(from); thisAction.setToNonDecision(to); } } context.setTo(origTo); context.setFrom(origFrom); for (final Move m : moves.moves()) m.setMover(context.state().mover()); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- /** * @param facing * @param from * @param to * @return True only if the forward condition is respecting according to the * facing direction. */ private static boolean checkForward(final CompassDirection facing, final TopologyElement from, final TopologyElement to) { switch (facing) { case N: return from.row() < to.row(); case NE: return from.row() < to.row() && from.col() < to.col(); case E: return from.col() < to.col(); case SE: return from.row() > to.row() && from.col() < to.col(); case S: return from.row() > to.row(); case SW: return from.row() > to.row() && from.col() > to.col(); case W: return from.col() > to.col(); case NW: return from.row() < to.row() && from.col() > to.col(); case ENE: case ESE: case NNE: case NNW: case SSE: case SSW: case WNW: case WSW: default: return false; } } @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game); gameFlags |= GameType.UsesFromPositions; if (startLocationFn != null) gameFlags |= startLocationFn.gameFlags(game); if (sideEffect != null) gameFlags |= sideEffect.gameFlags(game); if (walk != null) gameFlags |= walk.gameFlags(game); if (fromCondition != null) gameFlags |= fromCondition.gameFlags(game); if (goRule != null) gameFlags |= goRule.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); if (isDecision()) { concepts.set(Concept.LeapDecision.id(), true); if (goRule != null) { if (goRule.concepts(game).get(Concept.IsEmpty.id())) concepts.set(Concept.LeapDecisionToEmpty.id(), true); if (goRule.concepts(game).get(Concept.IsFriend.id())) concepts.set(Concept.LeapDecisionToFriend.id(), true); if (goRule.concepts(game).get(Concept.IsEnemy.id())) concepts.set(Concept.LeapDecisionToEnemy.id(), true); if (goRule instanceof BooleanConstant.TrueConstant) { concepts.set(Concept.LeapDecisionToEmpty.id(), true); concepts.set(Concept.LeapDecisionToFriend.id(), true); concepts.set(Concept.LeapDecisionToEnemy.id(), true); } } } else concepts.set(Concept.LeapEffect.id(), true); if (startLocationFn != null) concepts.or(startLocationFn.concepts(game)); if (sideEffect != null) concepts.or(sideEffect.concepts(game)); if (walk != null) concepts.or(walk.concepts(game)); if (fromCondition != null) concepts.or(fromCondition.concepts(game)); if (goRule != null) concepts.or(goRule.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); // We check if that's effectively a capture (remove or fromTo). if (sideEffect != null) if (sideEffect.concepts(game).get(Concept.RemoveEffect.id()) || sideEffect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.ReplacementCapture.id(), true); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); if (startLocationFn != null) writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); if (sideEffect != null) writeEvalContext.or(sideEffect.writesEvalContextRecursive()); if (walk != null) writeEvalContext.or(walk.writesEvalContextRecursive()); if (fromCondition != null) writeEvalContext.or(fromCondition.writesEvalContextRecursive()); if (goRule != null) writeEvalContext.or(goRule.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (startLocationFn != null) readEvalContext.or(startLocationFn.readsEvalContextRecursive()); if (sideEffect != null) readEvalContext.or(sideEffect.readsEvalContextRecursive()); if (walk != null) readEvalContext.or(walk.readsEvalContextRecursive()); if (fromCondition != null) readEvalContext.or(fromCondition.readsEvalContextRecursive()); if (goRule != null) readEvalContext.or(goRule.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (fromCondition != null) missingRequirement |= fromCondition.missingRequirement(game); if (startLocationFn != null) missingRequirement |= startLocationFn.missingRequirement(game); if (sideEffect != null) missingRequirement |= sideEffect.missingRequirement(game); if (walk != null) missingRequirement |= walk.missingRequirement(game); if (goRule != null) missingRequirement |= goRule.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (fromCondition != null) willCrash |= fromCondition.willCrash(game); if (startLocationFn != null) willCrash |= startLocationFn.willCrash(game); if (sideEffect != null) willCrash |= sideEffect.willCrash(game); if (walk != null) willCrash |= walk.willCrash(game); if (goRule != null) willCrash |= goRule.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); if (startLocationFn != null) startLocationFn.preprocess(game); if (walk != null) walk.preprocess(game); if (goRule != null) goRule.preprocess(game); if (sideEffect != null) sideEffect.preprocess(game); if (fromCondition != null) fromCondition.preprocess(game); } //------------------------------------------------------------------------- /** * @return Start locations */ public IntFunction startLocationFn() { return startLocationFn; } /** * @return Our walk function */ public RegionFunction walk() { return walk; } /** * @return Our go rule */ public BooleanFunction goRule() { return goRule; } @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "leap a piece to "+ goRule.toEnglish(game) + thenString; } }
13,107
25.915811
175
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Note.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Name; import annotations.Opt; import annotations.Or; import annotations.Or2; import game.Game; import game.functions.booleans.BooleanFunction; import game.functions.directions.DirectionsFunction; import game.functions.floats.FloatFunction; import game.functions.graph.GraphFunction; import game.functions.intArray.IntArrayFunction; import game.functions.ints.IntFunction; import game.functions.ints.board.Id; import game.functions.range.RangeFunction; import game.functions.region.RegionFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.play.RoleType; import game.types.state.GameType; import game.util.directions.Direction; import gnu.trove.list.array.TIntArrayList; import other.action.others.ActionNote; import other.context.Context; import other.move.Move; /** * Makes a note to a player or to all the players. * * @author Eric.Piette and cambolbro */ public final class Note extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the player. */ final IntFunction playerMessage; /** The index of the player. */ final IntFunction playerFn; /** The role in the message. */ final RoleType roleMessage; /** The role. */ final RoleType role; /** The message. */ final String message; /** The int message. */ final IntFunction messageInt; /** The int array message. */ final IntArrayFunction messageIntArray; /** The float message. */ final FloatFunction messageFloat; /** The boolean message. */ final BooleanFunction messageBoolean; /** The region message. */ final RegionFunction messageRegion; /** The range message. */ final RangeFunction messageRange; /** The directions message. */ final DirectionsFunction messageDirection; /** The graph message. */ final GraphFunction messageGraph; //------------------------------------------------------------------------- /** * @param player The index of the player to add at the beginning of * the message. * @param Player The role of the player to add at the beginning of the * message. * @param message The message as a string. * @param messageInt The message as an integer. * @param messageIntArray The message as an array of integer. * @param messageFloat The message as a float. * @param messageBoolean The message as a boolean. * @param messageRegion The message as a region. * @param messageRange The message as a range. * @param messageDirection The message as a set of directions. * @param messageGraph The message as a graph. * @param to The index of the player. * @param To The role of the player [ALL]. * * @example (note "Opponent has played") */ public Note ( @Opt @Or @Name final IntFunction player, @Opt @Or @Name final RoleType Player, @Or2 final String message, @Or2 final IntFunction messageInt, @Or2 final IntArrayFunction messageIntArray, @Or2 final FloatFunction messageFloat, @Or2 final BooleanFunction messageBoolean, @Or2 final RegionFunction messageRegion, @Or2 final RangeFunction messageRange, @Or2 final Direction messageDirection, @Or2 final GraphFunction messageGraph, @Opt @Or @Name final game.util.moves.Player to, @Opt @Or @Name final RoleType To ) { super(null); int numNonNull = 0; if (Player != null) numNonNull++; if (player != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException("Note(): Only one 'playerMessage' or 'roleMessage' parameters can be non-null."); numNonNull = 0; if (to != null) numNonNull++; if (To != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException("Note(): Only one 'to' or 'role' parameters can be non-null."); numNonNull = 0; if (message != null) numNonNull++; if (messageInt != null) numNonNull++; if (messageIntArray != null) numNonNull++; if (messageFloat != null) numNonNull++; if (messageBoolean != null) numNonNull++; if (messageRegion != null) numNonNull++; if (messageRange != null) numNonNull++; if (messageDirection != null) numNonNull++; if (messageGraph != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException( "Note(): One 'message', 'messageInt', 'messageIntArray', messageFloat', 'messageBoolean', 'messageRegion', 'messageRange'," + " 'messageDirection' or 'messageGraph' parameters must be non-null."); playerFn = (to != null) ? to.index() : (To != null) ? RoleType.toIntFunction(To) : new Id(null, RoleType.All); role = (to == null && To == null) ? RoleType.All : To; this.message = message; this.messageInt = messageInt; this.messageIntArray = messageIntArray; this.messageFloat = messageFloat; this.messageBoolean = messageBoolean; this.messageRegion = messageRegion; this.messageRange = messageRange; this.messageDirection = (messageDirection != null) ? messageDirection.directionsFunctions() : null; this.messageGraph = messageGraph; playerMessage = (Player != null) ? new Id(null, Player) : player; roleMessage = Player; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { // Return list of legal "to" moves final BaseMoves moves = new BaseMoves(super.then()); // final String msg = // (message != null) // ? message // : (messageInt != null) // ? messageInt.eval(context) + "" // : (messageIntArray != null) // ? messageIntArray.eval(context) + "" // : (messageFloat != null) // ? messageFloat.eval(context) + "" // : (messageBoolean != null) // ? messageBoolean.eval(context) + "" // : (messageRegion != null) // ? new TIntArrayList(messageRegion.eval(context).sites()) + "" // : (messageRange != null) // ? "[" + messageRange.eval(context).min(context) + ";" + messageRange.eval(context).max(context) + "]" // : // // For the directions we look the result for the first centre site of the default SiteType on the board. // (messageDirection != null) // ? messageDirection.convertToAbsolute(context.board().defaultSite(),context.topology().centre(context.board().defaultSite()).get(0),null, null, null, context) + "" // : (messageGraph != null) // ? messageGraph.eval(context, context.board().defaultSite()) + "" // : null; final String msg; if ( message != null) msg = message; else if ( messageInt != null) msg = messageInt.eval(context) + ""; else if ( messageIntArray != null) msg = messageIntArray.eval(context) + ""; else if ( messageFloat != null) msg = messageFloat.eval(context) + ""; else if ( messageBoolean != null) msg = messageBoolean.eval(context) + ""; else if ( messageRegion != null) msg = new TIntArrayList(messageRegion.eval(context).sites()) + ""; else if ( messageRange != null) msg = "[" + messageRange.eval(context).min(context) + ";" + messageRange.eval(context).max(context) + "]"; else if ( messageDirection != null) // For the directions we look the result for the first centre site of the default SiteType on the board. msg = messageDirection.convertToAbsolute ( context.board().defaultSite(),context.topology().centre(context.board().defaultSite()).get(0), null, null, null, context ) + ""; else if ( messageGraph != null) msg = messageGraph.eval(context, context.board().defaultSite()) + ""; else msg = null; final String messageToSend = (playerMessage == null) ? msg : "P" + playerMessage.eval(context) + " " + msg; if (role == RoleType.All) { for(int i = 1; i < context.game().players().size();i++) { final Move move = new Move(new ActionNote(messageToSend, i)); moves.moves().add(move); } } else { final int pid = playerFn.eval(context); if (pid > 0 && pid < context.game().players().size()) { final Move move = new Move(new ActionNote(messageToSend, pid)); moves.moves().add(move); } } return moves; } //------------------------------------------------------------------------- @Override public boolean canMove(final Context context) { return false; } @Override public boolean canMoveTo(final Context context, final int target) { return false; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | GameType.Note | playerFn.gameFlags(game); if (playerMessage != null) gameFlags |= playerMessage.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); if (messageInt != null) gameFlags |= messageInt.gameFlags(game); if (messageIntArray != null) gameFlags |= messageIntArray.gameFlags(game); if (messageFloat != null) gameFlags |= messageFloat.gameFlags(game); if (messageBoolean != null) gameFlags |= messageBoolean.gameFlags(game); if (messageRange != null) gameFlags |= messageRange.gameFlags(game); if (messageRegion != null) gameFlags |= messageRegion.gameFlags(game); if (messageGraph != null) gameFlags |= messageGraph.gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(playerFn.concepts(game)); concepts.or(super.concepts(game)); if (playerMessage != null) concepts.or(playerMessage.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); if (messageInt != null) concepts.or(messageInt.concepts(game)); if (messageIntArray != null) concepts.or(messageIntArray.concepts(game)); if (messageFloat != null) concepts.or(messageFloat.concepts(game)); if (messageBoolean != null) concepts.or(messageBoolean.concepts(game)); if (messageRange != null) concepts.or(messageRange.concepts(game)); if (messageRegion != null) concepts.or(messageRegion.concepts(game)); if (messageGraph != null) concepts.or(messageGraph.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(playerFn.writesEvalContextRecursive()); writeEvalContext.or(super.writesEvalContextRecursive()); if (playerMessage != null) writeEvalContext.or(playerMessage.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); if (messageInt != null) writeEvalContext.or(messageInt.writesEvalContextRecursive()); if (messageIntArray != null) writeEvalContext.or(messageIntArray.writesEvalContextRecursive()); if (messageBoolean != null) writeEvalContext.or(messageBoolean.writesEvalContextRecursive()); if (messageRange != null) writeEvalContext.or(messageRange.writesEvalContextRecursive()); if (messageRegion != null) writeEvalContext.or(messageRegion.writesEvalContextRecursive()); if (messageGraph != null) writeEvalContext.or(messageGraph.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(playerFn.readsEvalContextRecursive()); readEvalContext.or(super.readsEvalContextRecursive()); if (playerMessage != null) readEvalContext.or(playerMessage.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); if (messageInt != null) readEvalContext.or(messageInt.readsEvalContextRecursive()); if (messageIntArray != null) readEvalContext.or(messageIntArray.readsEvalContextRecursive()); if (messageBoolean != null) readEvalContext.or(messageBoolean.readsEvalContextRecursive()); if (messageRange != null) readEvalContext.or(messageRange.readsEvalContextRecursive()); if (messageRegion != null) readEvalContext.or(messageRegion.readsEvalContextRecursive()); if (messageGraph != null) readEvalContext.or(messageGraph.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= playerFn.missingRequirement(game); missingRequirement |= super.missingRequirement(game); // We check if the role is correct. if (role != null) { final int indexOwnerPhase = role.owner(); if ((indexOwnerPhase < 1 && !role.equals(RoleType.All) && !role.equals(RoleType.Mover) && !role.equals(RoleType.Prev) && !role.equals(RoleType.Next)) || indexOwnerPhase > game.players().count()) { game.addRequirementToReport("A (note ...) ludeme is used with an incorrect RoleType " + role + "."); missingRequirement = true; } } // We check if the role is correct. if (roleMessage != null) { final int indexOwnerPhase = roleMessage.owner(); if ((indexOwnerPhase < 1 && !roleMessage.equals(RoleType.Mover) && !roleMessage.equals(RoleType.Prev) && !roleMessage.equals(RoleType.Next)) || indexOwnerPhase > game.players().count()) { game.addRequirementToReport("A (note ...) ludeme is used with an incorrect RoleType " + roleMessage + "."); missingRequirement = true; } } if (playerMessage != null) missingRequirement |= playerMessage.missingRequirement(game); if (messageInt != null) missingRequirement |= messageInt.missingRequirement(game); if (messageIntArray != null) missingRequirement |= messageIntArray.missingRequirement(game); if (messageFloat != null) missingRequirement |= messageFloat.missingRequirement(game); if (messageBoolean != null) missingRequirement |= messageBoolean.missingRequirement(game); if (messageRange != null) missingRequirement |= messageRange.missingRequirement(game); if (messageRegion != null) missingRequirement |= messageRegion.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= playerFn.willCrash(game); willCrash |= super.willCrash(game); if (playerMessage != null) willCrash |= playerMessage.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); if (messageInt != null) willCrash |= messageInt.willCrash(game); if (messageIntArray != null) willCrash |= messageIntArray.willCrash(game); if (messageFloat != null) willCrash |= messageFloat.willCrash(game); if (messageBoolean != null) willCrash |= messageBoolean.willCrash(game); if (messageRange != null) willCrash |= messageRange.willCrash(game); if (messageRegion != null) willCrash |= messageRegion.willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); playerFn.preprocess(game); if (playerMessage != null) playerMessage.preprocess(game); if (messageInt != null) messageInt.preprocess(game); if (messageIntArray != null) messageIntArray.preprocess(game); if (messageFloat != null) messageFloat.preprocess(game); if (messageBoolean != null) messageBoolean.preprocess(game); if (messageRange != null) messageRange.preprocess(game); if (messageRegion != null) messageRegion.preprocess(game); if (messageGraph != null) messageGraph.preprocess(game); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String msg = "No Message"; if ( message != null) msg = message; else if ( messageInt != null) msg = messageInt.toEnglish(game); else if ( messageIntArray != null) msg = messageIntArray.toEnglish(game); else if ( messageFloat != null) msg = messageFloat.toEnglish(game); else if ( messageBoolean != null) msg = messageBoolean.toEnglish(game); else if ( messageRegion != null) msg = messageRegion.toEnglish(game); else if ( messageRange != null) msg = messageRange.toEnglish(game); else if ( messageDirection != null) // For the directions we look the result for the first centre site of the default SiteType on the board. msg = messageDirection.toEnglish(game); else if ( messageGraph != null) msg = messageGraph.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "send message " + msg + thenString; } //------------------------------------------------------------------------- }
17,214
31.117537
175
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Pass.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Opt; import game.Game; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.state.GameType; import main.Constants; import other.action.others.ActionPass; import other.concept.Concept; import other.context.Context; import other.move.Move; /** * Passes this turn. * * @author Eric.Piette and cambolbro */ public final class Pass extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @param then The moves applied after that move is applied. * * @example (pass) */ public Pass ( @Opt final Then then ) { super(then); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final ActionPass actionPass = new ActionPass(false); if (isDecision()) actionPass.setDecision(true); final Move move = new Move(actionPass); move.setFromNonDecision(Constants.OFF); move.setToNonDecision(Constants.OFF); move.setMover(context.state().mover()); moves.moves().add(move); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); return moves; } //------------------------------------------------------------------------- @Override public boolean canMoveTo(final Context context, final int target) { return false; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game); // If only one player but pass is a legal move, we do not stop the game if the // player passes. if (game.players().count() == 1) gameFlags |= GameType.NotAllPass; if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); if (isDecision()) concepts.set(Concept.PassDecision.id(), true); else concepts.set(Concept.PassEffect.id(), true); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return super.isStatic(); } @Override public void preprocess(final Game game) { super.preprocess(game); } @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "pass" + thenString; } }
3,761
21
80
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/PlayCard.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Opt; import game.Game; import game.equipment.component.Component; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import main.Constants; import other.action.Action; import other.action.move.move.ActionMove; import other.context.Context; import other.move.Move; /** * Plays any card in a player's hand to the board at their position. * * @author Eric.Piette and cambolbro */ public final class PlayCard extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @param then The moves applied after that move is applied. * * @example (playCard) */ public PlayCard ( @Opt final Then then ) { super(then); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final BaseMoves moves = new BaseMoves(super.then()); for (int cid = 1; cid < context.containers().length; cid++) { if (context.containers()[cid].owner() == context.state().mover()) { final int siteFrom = context.sitesFrom()[cid]; for (int site = siteFrom; site < context.containers()[cid].numSites() + siteFrom; site++) { for (int level = 0; level < context.containerState(cid).sizeStackCell(site); level++) { final int to = context.state().mover() - 1; final Action actionMove = ActionMove.construct(SiteType.Cell, site, level, SiteType.Cell, to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, false); if (isDecision()) actionMove.setDecision(true); final Move move = new Move(actionMove); move.setFromNonDecision(site); move.setLevelMinNonDecision(level); move.setLevelMaxNonDecision(level); move.setToNonDecision(to); move.setMover(context.state().mover()); moves.moves().add(move); } } } } if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | GameType.Cell | GameType.Card | GameType.HiddenInfo | GameType.NotAllPass | GameType.UsesFromPositions; if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; boolean gameHasCard = false; for (int i = 1; i < game.equipment().components().length; i++) { final Component component = game.equipment().components()[i]; if (component.isCard()) { gameHasCard = true; break; } } if (!gameHasCard) { game.addRequirementToReport("The ludeme (playCard ...) is used but the equipment has no cards."); missingRequirement = true; } missingRequirement |= super.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); } }
4,552
24.154696
185
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Promote.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Opt; import annotations.Or; import game.Game; import game.equipment.component.Component; import game.functions.ints.IntFunction; import game.functions.ints.iterator.To; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.play.RoleType; import game.util.moves.Piece; import game.util.moves.Player; import other.action.BaseAction; import other.action.move.ActionPromote; import other.concept.Concept; import other.context.Context; import other.move.Move; /** * Is used for promotion into another item. * * @author Eric.Piette and cambolbro */ public final class Promote extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Site to promote. */ private final IntFunction locationFn; /** Owner of the promoted piece. */ private final IntFunction owner; /** Name of the new component. */ private final String[] itemNames; /** Promotion to what piece. */ private final IntFunction toWhat; /** Pieces To Promote */ private final IntFunction[] toWhats; /** Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** * @param type The graph element type [default SiteType of the board]. * @param locationFn The location of the piece to promote [(to)]. * @param what The data about the promoted pieces. * @param who Index of the owner of the promoted piece. * @param role RoleType of the owner of the promoted piece. * @param then The moves applied after that move is applied. * * @example (promote (last To) (piece {"Queen" "Knight" "Bishop" "Rook"}) Mover) */ public Promote ( @Opt final SiteType type, @Opt final IntFunction locationFn, final Piece what, @Opt @Or final Player who, @Opt @Or final RoleType role, @Opt final Then then ) { super(then); int numNonNull = 0; if (who != null) numNonNull++; if (role != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException( "ForEach(): With ForEachPieceType zero or one who, role parameter must be non-null."); this.locationFn = (locationFn == null) ? To.instance() : locationFn; if (what.nameComponent() != null) { itemNames = new String[1]; itemNames[0] = what.nameComponent(); toWhat = null; toWhats = null; } else if (what.nameComponents() != null) { itemNames = what.nameComponents(); toWhat = null; toWhats = null; } else if (what.components() != null) { toWhats = what.components(); toWhat = null; itemNames = null; } else { itemNames = null; toWhat = what.component(); toWhats = null; } owner = (who == null && role == null) ? null : role != null ? RoleType.toIntFunction(role) : who.originalIndex(); this.type = type; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final int location = locationFn.eval(context); final Moves moves = new BaseMoves(super.then()); if (location < 0) return moves; final String[] evalItemNames; if (toWhat != null) { evalItemNames = new String[1]; final int id = toWhat.eval(context); if (id < 1) return new BaseMoves(super.then()); evalItemNames[0] = context.components()[id].name(); } else { evalItemNames = itemNames; } final int[] whats; if (toWhats != null) { whats = new int[toWhats.length]; for (int i = 0; i < toWhats.length; i++) whats[i] = toWhats[i].eval(context); } else { whats = new int[evalItemNames.length]; for (int i = 0; i < evalItemNames.length; i++) { if (owner == null) { final Component component = context.game().getComponent(evalItemNames[i]); if (component == null) throw new RuntimeException("Component " + evalItemNames[i] + " is not defined."); whats[i] = component.index(); } else { final int ownerId = owner.eval(context); for (int j = 1; j < context.components().length; j++) { final Component component = context.components()[j]; if (component.name().contains(evalItemNames[i]) && component.owner() == ownerId) { whats[i] = component.index(); break; } } } } } for (final int what : whats) { final BaseAction actionPromote = new ActionPromote(type, location, what); if (isDecision()) actionPromote.setDecision(true); final Move move = new Move(actionPromote); move.setFromNonDecision(location); move.setToNonDecision(location); move.setMover(context.state().mover()); moves.moves().add(move); } if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public boolean canMoveTo(final Context context, final int target) { return locationFn.eval(context) == target; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | locationFn.gameFlags(game); if (toWhat != null) gameFlags |= toWhat.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); gameFlags |= SiteType.gameFlags(type); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); concepts.or(locationFn.concepts(game)); if (isDecision()) concepts.set(Concept.PromotionDecision.id(), true); else concepts.set(Concept.PromotionEffect.id(), true); if (toWhat != null) concepts.or(toWhat.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(locationFn.writesEvalContextRecursive()); if (toWhat != null) writeEvalContext.or(toWhat.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(locationFn.readsEvalContextRecursive()); if (toWhat != null) readEvalContext.or(toWhat.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= locationFn.missingRequirement(game); if (toWhat != null) missingRequirement |= toWhat.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= locationFn.willCrash(game); if (toWhat != null) willCrash |= toWhat.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); locationFn.preprocess(game); if (toWhat != null) toWhat.preprocess(game); } @Override public String toEnglish(final Game game) { String items=""; int count=0; if(itemNames != null) { for (final String item : itemNames) { items+=item; count++; if(count == itemNames.length-1) items+=" or "; else if(count < itemNames.length) items+=", "; } } String ownerEnglish = "a player"; if (owner != null) ownerEnglish = owner.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "a piece of " + ownerEnglish + " " + locationFn.toEnglish(game) + ", this piece can promote into " + items + thenString; } }
8,862
23.551247
129
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Propose.java
package game.rules.play.moves.nonDecision.effect; import java.util.Arrays; import java.util.BitSet; import annotations.Opt; import annotations.Or; import game.Game; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.state.GameType; import main.Constants; import other.action.Action; import other.action.others.ActionPropose; import other.concept.Concept; import other.context.Context; import other.move.Move; /** * Is used to propose something to the other players. * * @author Eric.Piette and cambolbro */ public final class Propose extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** All the propositions. */ private final String[] propositions; /** The int representations of all the propositions */ private final int[] propositionInts; //------------------------------------------------------------------------- /** * @param proposition The proposition. * @param propositions The propositions. * @param then The moves applied after that move is applied. * * @example (propose "End") */ public Propose ( @Or final String proposition, @Or final String[] propositions, @Opt final Then then ) { super(then); int numNonNull = 0; if (proposition != null) numNonNull++; if (propositions != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException("Only one Or parameter can be non-null."); if (propositions != null) { this.propositions = propositions; } else { this.propositions = new String[1]; this.propositions[0] = proposition; } propositionInts = new int[this.propositions.length]; Arrays.fill(propositionInts, Constants.UNDEFINED); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final BaseMoves moves = new BaseMoves(super.then()); for (final int proposition : propositionInts) { // NOTE: if we have a -1 here, that means that preprocess() was not called! final Action action = new ActionPropose(context.game().voteString(proposition), proposition); if (isDecision()) action.setDecision(true); final Move move = new Move(action); move.setFromNonDecision(Constants.OFF); move.setToNonDecision(Constants.OFF); move.setMover(context.state().mover()); moves.moves().add(move); } if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public boolean canMoveTo(final Context context, final int target) { return false; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | GameType.Vote; if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); if (isDecision()) concepts.set(Concept.ProposeDecision.id(), true); else concepts.set(Concept.ProposeEffect.id(), true); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { final boolean isStatic = false; return isStatic; } @Override public void preprocess(final Game game) { super.preprocess(game); for (int i = 0; i < propositions.length; ++i) { propositionInts[i] = game.registerVoteString(propositions[i]); } } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "propose the following options " + Arrays.toString(propositions) + thenString; } //------------------------------------------------------------------------- }
5,336
23.040541
96
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Push.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Opt; import game.Game; import game.functions.directions.DirectionsFunction; import game.functions.ints.IntFunction; import game.functions.ints.last.LastTo; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.graph.Radial; import main.Constants; import other.action.Action; import other.action.move.ActionAdd; import other.action.move.remove.ActionRemove; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.state.container.ContainerState; import other.topology.Topology; import other.topology.TopologyElement; /** * Pushes all the pieces from a site in one direction. * * @author Eric.Piette */ public final class Push extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** Direction chosen. */ private final DirectionsFunction dirnChoice; /** Add on Cell/Edge/Vertex. */ protected SiteType type; //------------------------------------------------------------------------- /** * @param from Description of the ``from'' location [(from (last To))]. * @param directions The direction to push. * @param then The moves applied after that move is applied. * * @example (push (from (last To)) E) */ public Push ( @Opt final game.util.moves.From from, final game.util.directions.Direction directions, @Opt final Then then ) { super(then); startLocationFn = (from == null) ? new LastTo(null) : from.loc(); type = (from == null) ? null : from.type(); dirnChoice = directions.directionsFunctions(); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); if (from == Constants.OFF) return moves; final Topology topology = context.topology(); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); final TopologyElement fromV = topology.getGraphElements(realType).get(from); final ContainerState cs = context.state().containerStates()[0]; final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, fromV, null, null, null, context); if (directions.isEmpty()) return moves; final List<Radial> radials = topology.trajectories().radials(type, fromV.index(), directions.get(0)); for (final Radial radial : radials) { int currentPiece = cs.what(radial.steps()[0].id(), realType); final Action removeAction = ActionRemove.construct(realType, from, Constants.UNDEFINED, true); moves.moves().add(new Move(removeAction)); for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int to = radial.steps()[toIdx].id(); final int what = cs.what(to, realType); if (what != 0) { final Action removeTo = ActionRemove.construct(realType, to, Constants.UNDEFINED, true); moves.moves().add(new Move(removeTo)); final Action actionAdd = new ActionAdd(realType, to, currentPiece, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null); final Move move = new Move(actionAdd); moves.moves().add(move); currentPiece = what; } else { final Action actionAdd = new ActionAdd(realType, to, currentPiece, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null); final Move move = new Move(actionAdd); moves.moves().add(move); break; } } } // for (final Move m : moves.moves()) // m.setMover(context.state().mover()); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = startLocationFn.gameFlags(game) | super.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); concepts.or(startLocationFn.concepts(game)); concepts.set(Concept.PushEffect.id(), true); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(startLocationFn.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= startLocationFn.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= startLocationFn.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); type = SiteType.use(type, game); startLocationFn.preprocess(game); } @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "push " + dirnChoice.toEnglish(game) + thenString; } }
6,677
26.709544
118
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Random.java
package game.rules.play.moves.nonDecision.effect; import java.util.Arrays; import java.util.BitSet; import annotations.Name; import game.Game; import game.functions.floats.FloatFunction; import game.functions.ints.IntFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.state.GameType; import gnu.trove.list.array.TIntArrayList; import other.concept.Concept; import other.context.Context; /** * Returns a set of moves according to a set of probabilities. * * @author Eric.Piette */ public final class Random extends Moves { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Which probas. */ final FloatFunction[] probaFn; /** Which moves. */ final Moves[] moves; //------------------------------------------------------------------------- /** Which number to return. */ final IntFunction num; /** Which move ludeme. */ final Moves moveLudeme; //------------------------------------------------------------------------- /** * For making probabilities on different set of moves to return. * * @param probas The different probabilities for each move. * @param moves The different possible moves. * * @example (random {0.01 0.99} {(forEach Piece) (move Pass)}) */ public Random ( final FloatFunction[] probas, final Moves[] moves ) { super(null); final int minLength = Math.min(probas.length, moves.length); this.probaFn = Arrays.copyOf(probas, minLength); this.moves = Arrays.copyOf(moves, minLength); this.moveLudeme = null; this.num = null; } /** * For returning a specific number of random selected moves in a set of moves. * * @param moves A list of moves. * @param num The number of moves to return from that list (less if the number of legal moves is lower). * * @example (random (forEach Piece) num:2) */ public Random ( final Moves moves, @Name final IntFunction num ) { super(null); this.probaFn = null; this.moves = null; this.moveLudeme = moves; this.num = num; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { if (moves != null) { final double[] probas = new double[probaFn.length]; if (probas.length == 0) return new BaseMoves(super.then()); for (int i = 0; i < probas.length; i++) probas[i] = probaFn[i].eval(context); double sumProba = 0; for (final double prob : probas) sumProba += prob; final double[] probasNorm = new double[probaFn.length]; for (int i = 0; i < probas.length; i++) probasNorm[i] = probas[i] / sumProba; double randomValue = context.rng().nextDouble(); int returnedIndex = 0; for (; returnedIndex < probasNorm.length; returnedIndex++) { randomValue -= probasNorm[returnedIndex]; if (randomValue <= 0) break; } return moves[returnedIndex].eval(context); } else { final Moves legalMoves = moveLudeme.eval(context); int numToReturn = Math.max(0, Math.min(num.eval(context), legalMoves.moves().size())); final Moves movesToReturn = new BaseMoves(super.then()); TIntArrayList previousIndices = new TIntArrayList(); while (numToReturn > 0) { int randomIndex = context.rng().nextInt(legalMoves.moves().size()); if (previousIndices.contains(randomIndex)) continue; movesToReturn.moves().add(legalMoves.moves().get(randomIndex)); numToReturn --; } return movesToReturn; } } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long flags = super.gameFlags(game) | GameType.Stochastic; if (probaFn != null) for (final FloatFunction floatFn : probaFn) flags |= floatFn.gameFlags(game); if (moves != null) for (final Moves move : moves) flags |= move.gameFlags(game); if (num != null) flags |= num.gameFlags(game); if (moveLudeme != null) flags |= moveLudeme.gameFlags(game); return flags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.set(Concept.Stochastic.id(), true); if (probaFn != null) for (final FloatFunction floatFn : probaFn) concepts.or(floatFn.concepts(game)); if (moves != null) for (final Moves move : moves) concepts.or(move.concepts(game)); if (num != null) concepts.or(num.concepts(game)); if (moveLudeme != null) concepts.or(moveLudeme.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (moves != null) for (final Moves move : moves) writeEvalContext.or(move.writesEvalContextRecursive()); if (moveLudeme != null) writeEvalContext.or(moveLudeme.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (moves != null) for (final Moves move : moves) readEvalContext.or(move.readsEvalContextRecursive()); if (moveLudeme != null) readEvalContext.or(moveLudeme.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (probaFn != null) for (final FloatFunction floatFn : probaFn) missingRequirement |= floatFn.missingRequirement(game); if (moves != null) for (final Moves move : moves) missingRequirement |= move.missingRequirement(game); if (num != null) missingRequirement |= num.missingRequirement(game); if (moveLudeme != null) missingRequirement |= moveLudeme.missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (probaFn != null) for (final FloatFunction floatFn : probaFn) willCrash |= floatFn.willCrash(game); if (moves != null) for (final Moves move : moves) willCrash |= move.willCrash(game); if (num != null) willCrash |= num.willCrash(game); if (moveLudeme != null) willCrash |= moveLudeme.willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); if (probaFn != null) for (final FloatFunction floatFn : probaFn) floatFn.preprocess(game); if (moves != null) for (final Moves move : moves) move.preprocess(game); if (num != null) num.preprocess(game); if (moveLudeme != null) moveLudeme.preprocess(game); } }
7,004
22.665541
107
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Remove.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Name; import annotations.Opt; import annotations.Or; import game.Game; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.region.RegionFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.play.WhenType; import game.types.state.GameType; import main.Constants; import other.IntArrayFromRegion; import other.action.Action; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.state.container.ContainerState; /** * Removes an item from a site. * * @author Eric.Piette and cambolbro * * @remarks If the site is empty, the move is not applied. */ public final class Remove extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Which sites. */ private final IntArrayFromRegion regionFunction; /** The number of pieces to remove. */ private final IntFunction countFn; /** The level of the piece to remove. */ private final IntFunction levelFn; /** Remove on Cell/Edge/Vertex. */ private SiteType type; /** When to apply the removal (immediately unless otherwise specified). */ private final WhenType when; //------------------------------------------------------------------------- /** * @param type The graph element type of the location [Cell (or * Vertex if the main board uses this)]. * @param locationFunction The location to remove a piece. * @param regionFunction The locations to remove a piece. * @param level The level to remove a piece [top level]. * @param at When to perform the removal [immediately]. * @param count The number of pieces to remove [1]. * @param then The moves applied after that move is applied. * * @example (remove (last To)) * * @example (remove (last To) at:EndOfTurn) */ public Remove ( @Opt final SiteType type, @Or final IntFunction locationFunction, @Or final RegionFunction regionFunction, @Opt @Name final IntFunction level, @Opt @Name final WhenType at, @Opt @Name final IntFunction count, @Opt final Then then ) { super(then); int numNonNull = 0; if (locationFunction != null) numNonNull++; if (regionFunction != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException( "Remove(): Only one of locationFunction or regionFunction has to be non-null."); this.regionFunction = new IntArrayFromRegion(locationFunction, regionFunction); this.type = type; when = at; countFn = (count == null) ? new IntConstant(1) : count; levelFn = level; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { // Return list of legal "to" moves final Moves moves = new BaseMoves(super.then()); final int[] locs = regionFunction.eval(context); final int count = countFn.eval(context); for (final int loc : locs) { final int cid = loc >= context.containerId().length ? 0 : context.containerId()[loc]; SiteType realType = type; if (cid > 0) realType = SiteType.Cell; else if (realType == null) realType = context.board().defaultSite(); int numToRemove = count; if (loc < 0) continue; final ContainerState cs = context.state().containerStates()[cid]; if (cs.what(loc, realType) <= 0) continue; final boolean applyNow = (when == WhenType.EndOfTurn) ? false : true; int level = (levelFn != null) ? levelFn.eval(context) : cs.sizeStack(loc, realType) - 1; level = (level < 0) ? 0 : level; level = (!context.game().isStacking() || cs.sizeStack(loc, realType) == (level + 1)) ? Constants.UNDEFINED: level; final Action actionRemove = other.action.move.remove.ActionRemove.construct(realType, loc, level, applyNow); if (isDecision()) actionRemove.setDecision(true); final Move move = new Move(actionRemove); numToRemove--; while (numToRemove > 0) { move.actions().add(other.action.move.remove.ActionRemove.construct(realType, loc, level, applyNow)); numToRemove--; } move.setMover(context.state().mover()); moves.moves().add(move); if (then() != null) move.then().add(then().moves()); } // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (when != null) gameFlags |= GameType.SequenceCapture; return gameFlags | regionFunction.gameFlags(game) | countFn.gameFlags(game); } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); if(isDecision()) concepts.set(Concept.RemoveDecision.id(), true); else concepts.set(Concept.RemoveEffect.id(), true); if (when != null) concepts.set(Concept.CaptureSequence.id(), true); if (isDecision()) concepts.set(Concept.RemoveDecision.id(), true); if (then() != null) concepts.or(then().concepts(game)); concepts.or(regionFunction.concepts(game)); concepts.or(countFn.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); writeEvalContext.or(regionFunction.writesEvalContextRecursive()); writeEvalContext.or(countFn.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); readEvalContext.or(regionFunction.readsEvalContextRecursive()); readEvalContext.or(countFn.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); missingRequirement |= regionFunction.missingRequirement(game); missingRequirement |= countFn.missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); willCrash |= regionFunction.willCrash(game); willCrash |= countFn.willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); regionFunction.preprocess(game); countFn.preprocess(game); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "remove pieces at " + regionFunction.toEnglish(game) + thenString; } //------------------------------------------------------------------------- }
7,955
25.787879
117
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Roll.java
package game.rules.play.moves.nonDecision.effect; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import annotations.Opt; import game.Game; import game.equipment.container.other.Dice; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import main.Constants; import other.action.Action; import other.action.die.ActionSetDiceAllEqual; import other.action.die.ActionUpdateDice; import other.concept.Concept; import other.context.Context; import other.move.Move; /** * Rolls the dice. * * @author Eric.Piette */ public final class Roll extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @param then The moves applied after that move is applied. * * @example (roll) */ public Roll ( @Opt final Then then ) { super(then); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); boolean allEqual = true; int valueToCompare = Constants.UNDEFINED; final List<Action> actions = new ArrayList<Action>(); for (final Dice dice: context.game().handDice()) { for (int loc = context.sitesFrom()[dice.index()]; loc < context.sitesFrom()[dice.index()] + dice.numLocs(); loc++) { final int what = context.containerState(dice.index()).what(loc, SiteType.Cell); final int newValue = context.components()[what].roll(context); if (valueToCompare == Constants.UNDEFINED) valueToCompare = newValue; else if (valueToCompare != newValue) allEqual = false; actions.add(new ActionUpdateDice(loc, newValue)); } } actions.add(new ActionSetDiceAllEqual(allEqual)); moves.moves().add(new Move(actions)); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public boolean canMoveTo(final Context context, final int target) { return false; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = GameType.Stochastic | GameType.SiteState | super.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.set(Concept.Roll.id(), true); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); } @Override public boolean missingRequirement(final Game game) { if (!game.hasHandDice()) { game.addRequirementToReport("The ludeme (roll) is used but the equipment has no dice."); return true; } return false; } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "roll the dice" + thenString; } //------------------------------------------------------------------------- }
4,243
22.191257
92
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Satisfy.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Or; import game.Game; import game.functions.booleans.BooleanFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.puzzle.ActionSet; import other.action.puzzle.ActionToggle; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.context.TempContext; import other.move.Move; import other.move.MoveUtilities; import other.state.puzzle.ContainerDeductionPuzzleState; /** * Defines constraints applied at run-time for filtering legal puzzle moves. * * @author Eric * * @remarks This ludeme applies to deduction puzzles. */ public class Satisfy extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Constraints to apply. */ protected final BooleanFunction[] constraints; //------------------------------------------------------------------------- /** * @param constraint The constraint of the puzzle. * @param constraints The constraints of the puzzle. * * @example (satisfy (all Different)) */ public Satisfy ( @Or final BooleanFunction constraint, @Or final BooleanFunction[] constraints ) { super(null); int numNonNull = 0; if (constraint != null) numNonNull++; if (constraints != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException("Exactly one Or parameter must be non-null."); if (constraints != null) { this.constraints = constraints; } else { this.constraints = new BooleanFunction[1]; this.constraints[0] = constraint; } } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final SiteType type = context.board().defaultSite(); final int min = context.board().getRange(type).min(context); final int max = context.board().getRange(type).max(context); // Eric: improvement possible here in doing the next three steps one time when // the game is started. // We get all the variables constrained by the puzzle. final TIntArrayList varsConstraints = context.game().constraintVariables(); // We got the variables (locations) already solved. final TIntArrayList initLoc = new TIntArrayList(); if (context.game().rules().start() != null) if (context.game().rules().start().rules()[0].isSet()) { final game.rules.start.deductionPuzzle.Set startRule = (game.rules.start.deductionPuzzle.Set) context .game().rules().start().rules()[0]; final Integer[] init = startRule.vars(); for (final Integer in : init) initLoc.add(in.intValue()); } // We keep only the real variables of the problem. final TIntArrayList sites = new TIntArrayList(); for (int i = 0; i < varsConstraints.size(); i++) { final int var = varsConstraints.getQuick(i); if (!initLoc.contains(var)) sites.add(var); } // We compute the legal moves for (int i = 0; i < sites.size(); i++) { final int site = sites.getQuick(i); for (int index = min; index <= max; index++) { // SET final ActionSet actionSet = new ActionSet(type, site, index); actionSet.setDecision(true); final Move moveSet = new Move(actionSet); moveSet.setFromNonDecision(site); moveSet.setToNonDecision(site); // Check constraint final Context newContext = new TempContext(context); newContext.game().apply(newContext, moveSet); boolean constraintOK = true; if (constraints != null) for (final BooleanFunction constraint : constraints) if (!constraint.eval(newContext)) { constraintOK = false; break; } if (constraintOK) { final int saveFrom = context.from(); final int saveTo = context.to(); context.setFrom(site); context.setTo(Constants.OFF); MoveUtilities.chainRuleCrossProduct(context, moves, null, moveSet, false); context.setTo(saveTo); context.setFrom(saveFrom); } // TOGGLE final ActionToggle actionToggle = new ActionToggle(type, site, index); actionToggle.setDecision(true); final Move moveToggle = new Move(actionToggle); moveToggle.setFromNonDecision(site); moveToggle.setToNonDecision(site); final ContainerDeductionPuzzleState ps = (ContainerDeductionPuzzleState) context.state().containerStates()[0]; // Check if all is off if (!(ps.isResolved(site, type) && ps.bit(site, index, type))) { final int saveFrom = context.from(); final int saveTo = context.to(); context.setFrom(site); context.setTo(Constants.OFF); MoveUtilities.chainRuleCrossProduct(context, moves, null, moveToggle, false); context.setTo(saveTo); context.setFrom(saveFrom); } } } for (final Move m : moves.moves()) m.setMover(1); return moves; } //------------------------------------------------------------------------- /** * @return The constraints to satisfy. */ public BooleanFunction[] constraints() { return constraints; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | GameType.DeductionPuzzle; for (final BooleanFunction constraint : constraints) gameFlags |= constraint.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.set(Concept.DeductionPuzzle.id(), true); concepts.set(Concept.CopyContext.id(), true); for (final BooleanFunction constraint : constraints) concepts.or(constraint.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); for (final BooleanFunction constraint : constraints) writeEvalContext.or(constraint.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); for (final BooleanFunction constraint : constraints) readEvalContext.or(constraint.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); for (final BooleanFunction constraint : constraints) missingRequirement |= constraint.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; if (game.players().count() != 1) { game.addCrashToReport("The ludeme (satisfy ...) is used but the number of players is not 1."); willCrash = true; } willCrash |= super.willCrash(game); for (final BooleanFunction constraint : constraints) willCrash |= constraint.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public void preprocess(final Game game) { super.preprocess(game); for (final BooleanFunction constraint : constraints) constraint.preprocess(game); } @Override public boolean isStatic() { return false; } //------------------------------------------------------------------------- @Override public boolean isConstraintsMoves() { return true; } @Override public String toEnglish(final Game game) { String text = ""; for (final BooleanFunction constraint : constraints) text += "Satisfy the constraint: " + constraint.toEnglish(game) + ", "; String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return text.substring(0, text.length()-2) + thenString; } }
8,830
25.760606
114
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Select.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanConstant; import game.functions.booleans.BooleanFunction; import game.functions.ints.IntFunction; import game.functions.ints.board.Id; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.play.RoleType; import game.types.state.GameType; import game.util.moves.From; import game.util.moves.To; import main.Constants; import other.IntArrayFromRegion; import other.action.move.ActionSelect; import other.context.Context; import other.context.EvalContextData; import other.move.Move; import other.move.MoveUtilities; import other.state.container.ContainerState; /** * Selects either a site or a pair of ``from'' and ``to'' locations. * * @author Eric.Piette * * @remarks This ludeme is used to select one or two sites in order to apply a * consequence to them. If the ``to'' location is not specified, then it * is assumed to be the same as the 'from' location. */ public final class Select extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Which region. */ private final IntArrayFromRegion region; /** Condition to select. */ private final BooleanFunction condition; /** Which region To. */ private final IntArrayFromRegion regionTo; /** Condition to select. */ private final BooleanFunction conditionTo; /** Select From Cell/Edge/Vertex. */ private SiteType typeFrom; /** Level From Select */ private final IntFunction levelFromFn; /** Select To Cell/Edge/Vertex. */ private SiteType typeTo; /** Level To Select */ private final IntFunction levelToFn; /** Does our game involve stacking? */ private boolean gameUsesStacking = false; /** The mover of this moves for simultaneous game (e.g. Rock-Paper-Scissors). */ private final RoleType mover; //------------------------------------------------------------------------- /** * @param from Describes the ``from'' location to select [(from)]. * @param to Describes the ``to'' location to select. * @param mover The mover of the move. * @param then The moves applied after that move is applied. * * @example (select (from) (then (remove (last To)))) * * @example (select (from (sites Occupied by:Mover) if:(!= (state at:(to)) 0) ) * (to (sites Occupied by:Next) if:(!= (state at:(to)) 0) ) (then (set * State at:(last To) (% (+ (state at:(last From)) (state at:(last * To))) 5) ) ) ) */ public Select ( final From from, @Opt final To to, @Opt final RoleType mover, @Opt final Then then ) { super(then); region = new IntArrayFromRegion(from.loc(), from.region()); if (to == null) regionTo = null; else if (to.region() != null) regionTo = new IntArrayFromRegion(null, to.region()); else if (to.loc() != null) regionTo = new IntArrayFromRegion(to.loc(), null); else regionTo = null; condition = (from.cond() == null) ? new BooleanConstant(true) : from.cond(); conditionTo = (to == null || to.cond() == null) ? new BooleanConstant(true) : to.cond(); typeFrom = from.type(); typeTo = (to != null) ? to.type() : null; levelToFn = (to != null && to.level() != null) ? to.level() : null; levelFromFn = (from.level() != null) ? from.level() : null; this.mover = mover; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final BaseMoves moves = new BaseMoves(super.then()); final int[] sites; sites = region.eval(context); final int origTo = context.to(); final int origFrom = context.from(); for (final int site : sites) { int cid = 0; if (typeFrom == SiteType.Cell) { if (site >= context.containerId().length) continue; cid = context.containerId()[site]; } else { if (site >= context.topology().getGraphElements(typeFrom).size()) continue; } final ContainerState cs = context.containerState(cid); final int levelFrom = !gameUsesStacking ? Constants.UNDEFINED : (levelFromFn != null) ? levelFromFn.eval(context) : cs.sizeStack(site, typeFrom) - 1; if (site == Constants.UNDEFINED) continue; context.setFrom(site); context.setTo(site); if (condition.eval(context)) { if (regionTo == null) { final ActionSelect ActionSelect = new ActionSelect(typeFrom, site, levelFrom, null, Constants.UNDEFINED, levelFrom); if (isDecision()) ActionSelect.setDecision(true); final Move action = new Move(ActionSelect); action.setFromNonDecision(site); action.setToNonDecision(site); action.setMover(context.state().mover()); moves.moves().add(action); } else { final int[] sitesTo = regionTo.eval(context); for (final int siteTo : sitesTo) { if (siteTo < 0) continue; int cidTo = 0; if (typeTo == SiteType.Cell) { if (siteTo >= context.containerId().length) continue; cidTo = context.containerId()[siteTo]; } else { if (siteTo >= context.topology().getGraphElements(typeTo).size()) continue; } final ContainerState csTo = context.containerState(cidTo); final int levelTo = levelToFn != null ? levelToFn.eval(context) : csTo.sizeStack(siteTo, typeTo) - 1; //context.setFrom(site); context.setTo(siteTo); if (conditionTo.eval(context)) { final ActionSelect ActionSelect = new ActionSelect(typeFrom, site, levelFrom, typeTo, siteTo, levelTo); if (isDecision()) ActionSelect.setDecision(true); final Move action = new Move(ActionSelect); action.setFromNonDecision(site); action.setToNonDecision(siteTo); action.setMover(context.state().mover()); moves.moves().add(action); } //context.setFrom(origFrom); } } } } context.setTo(origTo); context.setFrom(origFrom); // We set the mover to the move. final int moverToSet = (mover == null) ? context.state().mover() : new Id(null, mover).eval(context); MoveUtilities.setGeneratedMovesData(moves.moves(), this, moverToSet); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | region.gameFlags(game) | condition.gameFlags(game) | conditionTo.gameFlags(game); if (regionTo != null) { gameFlags |= regionTo.gameFlags(game); gameFlags |= GameType.UsesFromPositions; } if (then() != null) gameFlags |= then().gameFlags(game); gameFlags |= SiteType.gameFlags(typeFrom); gameFlags |= SiteType.gameFlags(typeTo); if (levelFromFn != null) gameFlags |= levelFromFn.gameFlags(game); if (levelToFn != null) gameFlags |= levelToFn.gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(typeFrom)); concepts.or(SiteType.concepts(typeTo)); concepts.or(super.concepts(game)); concepts.or(region.concepts(game)); concepts.or(condition.concepts(game)); concepts.or(conditionTo.concepts(game)); if (regionTo != null) concepts.or(regionTo.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); if (levelFromFn != null) concepts.or(levelFromFn.concepts(game)); if (levelToFn != null) concepts.or(levelToFn.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(region.writesEvalContextRecursive()); writeEvalContext.or(condition.writesEvalContextRecursive()); writeEvalContext.or(conditionTo.writesEvalContextRecursive()); if (regionTo != null) writeEvalContext.or(regionTo.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); if (levelFromFn != null) writeEvalContext.or(levelFromFn.writesEvalContextRecursive()); if (levelToFn != null) writeEvalContext.or(levelToFn.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(region.readsEvalContextRecursive()); readEvalContext.or(condition.readsEvalContextRecursive()); readEvalContext.or(conditionTo.readsEvalContextRecursive()); if (regionTo != null) readEvalContext.or(regionTo.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); if (levelFromFn != null) readEvalContext.or(levelFromFn.readsEvalContextRecursive()); if (levelToFn != null) readEvalContext.or(levelToFn.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= region.missingRequirement(game); missingRequirement |= condition.missingRequirement(game); missingRequirement |= conditionTo.missingRequirement(game); if (regionTo != null) missingRequirement |= regionTo.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); if (levelFromFn != null) missingRequirement |= levelFromFn.missingRequirement(game); if (levelToFn != null) missingRequirement |= levelToFn.missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= region.willCrash(game); willCrash |= condition.willCrash(game); willCrash |= conditionTo.willCrash(game); if (regionTo != null) willCrash |= regionTo.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); if (levelFromFn != null) willCrash |= levelFromFn.willCrash(game); if (levelToFn != null) willCrash |= levelToFn.willCrash(game); return willCrash; } @Override public boolean isStatic() { if (regionTo != null && !regionTo.isStatic()) return false; if (levelFromFn != null && !levelFromFn.isStatic()) return false; if (levelToFn != null && !levelToFn.isStatic()) return false; return super.isStatic() && region.isStatic() && condition.isStatic() && conditionTo.isStatic(); } @Override public void preprocess(final Game game) { typeFrom = SiteType.use(typeFrom, game); typeTo = SiteType.use(typeTo, game); super.preprocess(game); region.preprocess(game); condition.preprocess(game); if (regionTo != null) regionTo.preprocess(game); conditionTo.preprocess(game); if (levelFromFn != null) levelFromFn.preprocess(game); if (levelToFn != null) levelToFn.preprocess(game); gameUsesStacking = game.isStacking(); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String englishString = "select " + typeFrom.name() + " in " + region.toEnglish(game) + (levelFromFn == null ? "" : " level " + levelFromFn.toEnglish(game)) + (condition == null ? "" : " if " + condition.toEnglish(game)); if (regionTo != null) englishString += " and select " + typeTo.name() + " in " + regionTo.toEnglish(game) + (levelToFn == null ? "" : " level " + levelToFn.toEnglish(game)) + (conditionTo == null ? "" : " if " + conditionTo.toEnglish(game)); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return englishString + thenString; } //------------------------------------------------------------------------- }
12,489
26.755556
124
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Shoot.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanFunction; import game.functions.booleans.is.in.IsIn; import game.functions.directions.Directions; import game.functions.ints.IntFunction; import game.functions.ints.iterator.Between; import game.functions.ints.last.LastTo; import game.functions.region.sites.Sites; import game.functions.region.sites.SitesIndexType; import game.functions.region.sites.index.SitesEmpty; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import game.util.directions.AbsoluteDirection; import game.util.graph.Radial; import game.util.moves.From; import game.util.moves.Piece; import game.util.moves.To; import main.Constants; import main.collections.FastTIntArrayList; import other.action.Action; import other.action.move.ActionAdd; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.Move; import other.move.MoveUtilities; import other.topology.Topology; import other.topology.TopologyElement; /** * Is used to shoot an item from one site to another with a specific direction. * * @author cambolbro * * @remarks This ludeme is used for games including Amazons. */ public final class Shoot extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** Direction chosen. */ private final Directions dirnChoice; /** The rule to continue the move. */ private final BooleanFunction goRule; /** If not null, the site has to go has to follow this condition. */ private final BooleanFunction toRule; /** The piece shot. */ private final IntFunction pieceFn; /** Add on Cell/Edge/Vertex. */ protected SiteType type; //------------------------------------------------------------------------- /** * @param what The data about the piece to shoot. * @param from The ``from'' location [(lastTo)]. * @param dirn The direction to follow [Adjacent]. * @param between The location(s) between ``from'' and ``to''. * @param to The condition on the ``to'' location to allow shooting [(to * if:(in (to) (sites Empty)))]. * @param then The moves applied after that move is applied. * * @example (shoot (piece "Dot0")) */ public Shoot ( final Piece what, @Opt final From from, @Opt final AbsoluteDirection dirn, @Opt final game.util.moves.Between between, @Opt final To to, @Opt final Then then ) { super(then); startLocationFn = (from == null) ? new LastTo(null) : from.loc(); goRule = (between == null || between.condition() == null) ? IsIn.construct(null, new IntFunction[] { Between.instance() }, SitesEmpty.construct(null, null), null) : between.condition(); toRule = (to == null) ? IsIn.construct ( null, new IntFunction[] { game.functions.ints.iterator.To.instance() }, Sites.construct(SitesIndexType.Empty, SiteType.Cell, null), null ) : to.cond(); dirnChoice = (dirn == null) ? new Directions(AbsoluteDirection.Adjacent, null) : new Directions(dirn, null); pieceFn = what.component(); type = (from == null) ? null : from.type(); } //------------------------------------------------------------------------- @Override public final Moves eval(final Context context) { final BaseMoves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); if (from == Constants.OFF) return moves; final int origTo = context.to(); final int origBetween = context.between(); final Topology graph = context.topology(); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); final TopologyElement fromV = graph.getGraphElements(realType).get(from); final int pieceType = pieceFn.eval(context); if (pieceType < 0) return moves; final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, fromV, null, null, null, context); for (final AbsoluteDirection direction : directions) { final List<Radial> radialList = graph.trajectories().radials(type, fromV.index(), direction); for (final Radial radial : radialList) { final FastTIntArrayList betweenSites = new FastTIntArrayList(); context.setBetween(origBetween); for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int to = radial.steps()[toIdx].id(); context.setTo(to); if (!toRule.eval(context)) break; context.setBetween(to); final Action actionAdd = new ActionAdd(type, to, pieceType, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null); if (isDecision()) actionAdd.setDecision(true); final Move move = new Move(actionAdd); MoveUtilities.chainRuleCrossProduct(context, moves, null, move, false); move.setFromNonDecision(to); move.setBetweenNonDecision(new FastTIntArrayList(betweenSites)); move.setToNonDecision(to); betweenSites.add(to); } } } context.setTo(origTo); context.setBetween(origBetween); MoveUtilities.setGeneratedMovesData(moves.moves(), this, context.state().mover()); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game); gameFlags |= GameType.UsesFromPositions; if (startLocationFn != null) gameFlags |= startLocationFn.gameFlags(game); if (goRule!= null) gameFlags |= goRule.gameFlags(game); if (toRule != null) gameFlags |= toRule.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(SiteType.concepts(type)); concepts.set(Concept.LineOfSight.id(), true); // shooting involves the line of sight. if (startLocationFn != null) concepts.or(startLocationFn.concepts(game)); if (goRule != null) concepts.or(goRule.concepts(game)); if (toRule != null) concepts.or(toRule.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); if (isDecision()) { concepts.set(Concept.ShootDecision.id(), true); concepts.set(Concept.AddDecision.id(), true); // shooting is adding pieces. } else { concepts.set(Concept.ShootEffect.id(), true); concepts.set(Concept.AddEffect.id(), true); // shooting is adding pieces. } if (dirnChoice != null) concepts.or(dirnChoice.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); if (startLocationFn != null) writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); if (goRule != null) writeEvalContext.or(goRule.writesEvalContextRecursive()); if (toRule != null) writeEvalContext.or(toRule.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); if (dirnChoice != null) writeEvalContext.or(dirnChoice.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.Between.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (startLocationFn != null) readEvalContext.or(startLocationFn.readsEvalContextRecursive()); if (goRule != null) readEvalContext.or(goRule.readsEvalContextRecursive()); if (toRule != null) readEvalContext.or(toRule.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); if (dirnChoice != null) readEvalContext.or(dirnChoice.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (startLocationFn != null) missingRequirement |= startLocationFn.missingRequirement(game); if (goRule != null) missingRequirement |= goRule.missingRequirement(game); if (toRule != null) missingRequirement |= toRule.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (startLocationFn != null) willCrash |= startLocationFn.willCrash(game); if (goRule != null) willCrash |= goRule.willCrash(game); if (toRule != null) willCrash |= toRule.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); type = SiteType.use(type, game); if (startLocationFn != null) startLocationFn.preprocess(game); if (goRule != null) goRule.preprocess(game); if (toRule != null) toRule.preprocess(game); } //------------------------------------------------------------------------- /** * @return Our go-rule */ public BooleanFunction goRule() { return goRule; } @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "shoot the piece " + pieceFn.toEnglish(game) + thenString; } }
10,297
26.171504
108
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Slide.java
package game.rules.play.moves.nonDecision.effect; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import annotations.Name; import annotations.Opt; import game.Game; import game.equipment.container.board.Track; import game.functions.booleans.BooleanConstant; import game.functions.booleans.BooleanFunction; import game.functions.booleans.is.in.IsIn; import game.functions.directions.Directions; import game.functions.directions.DirectionsFunction; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.iterator.Between; import game.functions.ints.iterator.From; import game.functions.region.sites.index.SitesEmpty; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import game.util.directions.AbsoluteDirection; import game.util.graph.Radial; import game.util.moves.To; import main.Constants; import main.collections.FastTIntArrayList; import other.action.Action; import other.action.move.ActionAdd; import other.action.move.move.ActionMove; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.Move; import other.move.MoveUtilities; import other.topology.Topology; import other.topology.TopologyElement; /** * Slides a piece in a direction through a number of sites. * * @author Eric.Piette * * @remarks The rook in Chess is an example of a piece that slides in Orthogonal * directions. Pieces can be constrained to slide along predefined * tracks, e.g. see Surakarta. Note that we extend the standard * definition of ``slide'' to allow pieces to slide through other * pieces if a specific condition is given, but that pieces are assumed * to slide through empty sites only by default. */ public final class Slide extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** Level from. */ private final IntFunction levelFromFn; /** From Condition Rule. */ private final BooleanFunction fromCondition; /** Limit to slide. */ private final IntFunction limit; /** Minimal distance. */ private final IntFunction minFn; /** The rule to continue the move. */ private final BooleanFunction goRule; /** The rule to stop the move. */ private final BooleanFunction stopRule; /** If not null, the site has to go has to follow this condition. */ private final BooleanFunction toRule; /** The piece let on each site during the movement. */ private final IntFunction let; /** The Move applied on the location crossed. */ private final Moves betweenEffect; /** The Move applied on the location reached. */ private final Moves sideEffect; /** Direction chosen. */ private final DirectionsFunction dirnChoice; /** Track chosen */ private final String trackName; /** Add on Cell/Edge/Vertex. */ protected SiteType type; /** To step a complete stack. */ private final boolean stack; //------------------------------------------------------------------------- /** Pre-computed tracks in case of slide move on the tracks. */ private List<Track> preComputedTracks = new ArrayList<Track>(); //------------------------------------------------------------------------- /** * @param from Description of the ``from'' location [(from)]. * @param track The track on which to slide. * @param directions The directions of the move [Adjacent]. * @param between Description of the location(s) between ``from'' and ``to''. * @param to Description of the ``to'' location. * @param stack True if the move is applied to a stack [False]. * @param then Moves to apply after this one. * * @example (slide) * * @example (slide Orthogonal) * * @example (slide "AllTracks" (between if:(or (= (between) (from)) (is In * (between) (sites Empty)) ) ) (to if:(is Enemy (who at:(to))) (apply * (remove (to))) ) (then (set Counter)) ) */ public Slide ( @Opt final game.util.moves.From from, @Opt final String track, @Opt final game.util.directions.Direction directions, @Opt final game.util.moves.Between between, @Opt final To to, @Opt @Name final Boolean stack, @Opt final Then then ) { super(then); // From if (from != null) { startLocationFn = from.loc(); levelFromFn = from.level(); fromCondition = from.cond(); } else { startLocationFn = new From(null); levelFromFn = null; fromCondition = null; } type = (from == null) ? null : from.type(); minFn = (between == null || between.range() == null) ? new IntConstant(Constants.UNDEFINED) : between.range().minFn(); limit = (between == null || between.range() == null) ? new IntConstant(Constants.MAX_DISTANCE) : between.range().maxFn(); sideEffect = (to == null || to.effect() == null) ? null : to.effect().effect(); goRule = (between == null || between.condition() == null) ? IsIn.construct(null, new IntFunction[] { Between.instance() }, SitesEmpty.construct(null, null), null) : between.condition(); stopRule = (to == null) ? null : to.cond(); let = (between == null) ? null : between.trail(); betweenEffect = (between == null) ? null : between.effect(); dirnChoice = (directions != null) ? directions.directionsFunctions() : new Directions(AbsoluteDirection.Adjacent, null); // Stack this.stack = (stack == null) ? false : stack.booleanValue(); trackName = track; toRule = (to == null || to.effect() == null) ? null : to.effect().condition(); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); final int min = minFn.eval(context); if (from == Constants.OFF) return moves; if (trackName != null) return slideByTrack(context); final int origFrom = context.from(); final int origTo = context.to(); final int origBetween = context.between(); final Topology topology = context.topology(); final TopologyElement fromV = topology.getGraphElements(type).get(from); context.setFrom(from); final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(type, fromV, null, null, null, context); final int levelFrom = (levelFromFn == null) ? Constants.UNDEFINED : levelFromFn.eval(context); // If the level specified is less than 0, no move can be computed. if (levelFrom < Constants.UNDEFINED && levelFromFn != null) return moves; final int maxPathLength = limit.eval(context); if (fromCondition != null && !fromCondition.eval(context)) return moves; for (final AbsoluteDirection direction : directions) { final List<Radial> radials = topology.trajectories().radials(type, from, direction); for (final Radial radial : radials) { final FastTIntArrayList betweenSites = new FastTIntArrayList(); context.setBetween(origBetween); for (int toIdx = 1; toIdx < radial.steps().length && toIdx <= maxPathLength; toIdx++) { final int to = radial.steps()[toIdx].id(); context.setTo(to); if (stopRule != null && stopRule.eval(context)) { if (min <= toIdx) { Action action = null; Move move = null; // Check stack move. if (levelFrom == Constants.UNDEFINED && stack == false) { action = ActionMove.construct(type, from, Constants.UNDEFINED, type, to, Constants.OFF,Constants.UNDEFINED, Constants.OFF, Constants.OFF, false); action.setDecision(isDecision()); move = new Move(action); move = MoveUtilities.chainRuleWithAction(context, sideEffect, move, true, false); } else if (levelFrom == Constants.UNDEFINED || stack == true) { final int level = (context.game().isStacking()) ? (stack) ? Constants.UNDEFINED : context.state().containerStates()[0].sizeStack(from, type) - 1 : Constants.UNDEFINED; action = ActionMove.construct(type, from, level, type, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, stack); action.setDecision(true); move = new Move(action); // To add the levels to move a stack on the Move class (only for GUI) if (stack) { move.setLevelMinNonDecision(0); move.setLevelMaxNonDecision(context.state().containerStates()[0].sizeStack(from, type) - 1); } move = MoveUtilities.chainRuleWithAction(context, sideEffect, move, true, false); } else // Slide a piece at a specific level. { action = ActionMove.construct(type, from, levelFrom, type, to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, stack); action.setDecision(true); move = new Move(action); move.setLevelMinNonDecision(levelFrom); move.setLevelMaxNonDecision(levelFrom); move = MoveUtilities.chainRuleWithAction(context, sideEffect, move, true, false); } // Trail piece if (let != null) { final int pieceToLet = let.eval(context); for (int i = 0; i < toIdx; i++) { final Action add = new ActionAdd(type, radial.steps()[i].id(), pieceToLet, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null); move.actions().add(add); } } // Moves on between sites if (betweenEffect != null) for (int i = 0; i < betweenSites.size(); i++) { context.setBetween(betweenSites.get(i)); move = MoveUtilities.chainRuleWithAction(context, betweenEffect, move, true, false); } // Check to rule. if (toRule == null || toRule.eval(context)) { MoveUtilities.chainRuleCrossProduct(context, moves, null, move, false); move.setFromNonDecision(from); move.setBetweenNonDecision(new FastTIntArrayList(betweenSites)); move.setToNonDecision(to); } break; } } context.setBetween(to); if (!goRule.eval(context)) break; if (min <= toIdx) { Action action = null; Move move = null; // Check stack move. if (levelFrom == Constants.UNDEFINED && stack == false) { action = ActionMove.construct(type, from, Constants.UNDEFINED, type, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, false); action.setDecision(isDecision()); move = new Move(action); move = MoveUtilities.chainRuleWithAction(context, sideEffect, move, true, false); } else if (levelFrom == Constants.UNDEFINED || stack == true) { final int level = (context.game().isStacking()) ? (stack) ? Constants.UNDEFINED : context.state().containerStates()[0].sizeStack(from, type) - 1 : Constants.UNDEFINED; action = ActionMove.construct(type, from, level, type, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, stack); action.setDecision(true); move = new Move(action); // to add the levels to move a stack on the Move class (only for GUI) if (stack) { move.setLevelMinNonDecision(0); move.setLevelMaxNonDecision( context.state().containerStates()[0].sizeStack(from, type) - 1); } } else // Step a piece at a specific level. { action = ActionMove.construct(type, from, levelFrom, type, to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, stack); action.setDecision(true); move = new Move(action); move.setLevelMinNonDecision(levelFrom); move.setLevelMaxNonDecision(levelFrom); } // Trail piece. if (let != null) { final int pieceToLet = let.eval(context); for (int i = 0; i < toIdx; i++) { final Action add = new ActionAdd(type, radial.steps()[i].id(), pieceToLet, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null); move.actions().add(add); } } // Moves on between sites. if (betweenEffect != null) for (int i = 0; i < betweenSites.size(); i++) { context.setBetween(betweenSites.get(i)); move = MoveUtilities.chainRuleWithAction(context, betweenEffect, move, true, false); } // Check to rule. if (toRule == null || (toRule.eval(context))) { MoveUtilities.chainRuleCrossProduct(context, moves, null, move, false); move.setFromNonDecision(from); move.setBetweenNonDecision(new FastTIntArrayList(betweenSites)); move.setToNonDecision(to); } } betweenSites.add(to); } } } context.setTo(origTo); context.setFrom(origFrom); context.setBetween(origBetween); MoveUtilities.setGeneratedMovesData(moves.moves(), this, context.state().mover()); return moves; } //------------------------------------------------------------------------- private Moves slideByTrack(final Context context) { final Moves moves = new BaseMoves(super.then()); // this is not a track if (preComputedTracks.size() == 0) return moves; final int from = startLocationFn.eval(context); final int origFrom = context.from(); context.setFrom(from); if (fromCondition != null && !fromCondition.eval(context)) return moves; final int origTo = context.to(); final int origStep = context.between(); final int min = minFn.eval(context); final int maxPathLength = limit.eval(context); for (final Track track : preComputedTracks) { for (int i = 0; i < track.elems().length; i++) { if (track.elems()[i].site == from) { int index = i; int nbBump = track.elems()[index].bump; int to = track.elems()[index].site; int nbElem = 1; while (track.elems()[index].next != Constants.OFF && nbElem < track.elems().length && nbElem <= maxPathLength) { to = track.elems()[index].next; context.setTo(to); if (nbBump > 0 || !trackName.equals("AllTracks")) { if (stopRule != null && stopRule.eval(context)) { if (min <= nbElem) { final Action actionMove = ActionMove.construct(type, from, Constants.UNDEFINED, type, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, false); actionMove.setDecision(isDecision()); Move thisAction = new Move(actionMove); thisAction = MoveUtilities.chainRuleWithAction(context, sideEffect, thisAction, true, false); MoveUtilities.chainRuleCrossProduct(context, moves, null, thisAction, false); thisAction.setFromNonDecision(from); thisAction.setToNonDecision(to); break; } } else { if (min <= nbElem) { context.setTo(to); if (toRule == null || (toRule.eval(context))) { final Action actionMove = ActionMove.construct(type, from, Constants.UNDEFINED, type, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, false); actionMove.setDecision(isDecision()); final Move thisAction = new Move(actionMove); thisAction.setFromNonDecision(from); thisAction.setToNonDecision(to); MoveUtilities.chainRuleCrossProduct(context, moves, null, thisAction, false); thisAction.setFromNonDecision(from); thisAction.setToNonDecision(to); } } } } nbElem++; context.setBetween(to); if (!goRule.eval(context)) break; index = track.elems()[index].nextIndex; nbBump += track.elems()[index].bump; } } } } context.setTo(origTo); context.setFrom(origFrom); context.setBetween(origStep); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | goRule.gameFlags(game); gameFlags |= GameType.UsesFromPositions; if (startLocationFn != null) gameFlags = gameFlags | startLocationFn.gameFlags(game); if (fromCondition != null) gameFlags |= fromCondition.gameFlags(game); if (limit != null) gameFlags = gameFlags | limit.gameFlags(game); if (stopRule != null) gameFlags = gameFlags | stopRule.gameFlags(game); if (toRule != null) gameFlags = gameFlags | toRule.gameFlags(game); if (let != null) gameFlags = gameFlags | let.gameFlags(game); if (sideEffect != null) gameFlags = gameFlags | sideEffect.gameFlags(game); if (betweenEffect != null) gameFlags = gameFlags | betweenEffect.gameFlags(game); if (levelFromFn != null) gameFlags |= levelFromFn.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (stack) gameFlags |= GameType.Stacking; if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(SiteType.concepts(type)); concepts.set(Concept.LineOfSight.id(), true); concepts.or(goRule.concepts(game)); if (isDecision()) { concepts.set(Concept.SlideDecision.id(), true); if (goRule.concepts(game).get(Concept.IsEmpty.id())) concepts.set(Concept.SlideDecisionToEmpty.id(), true); if (goRule.concepts(game).get(Concept.IsFriend.id())) concepts.set(Concept.SlideDecisionToFriend.id(), true); if (goRule.concepts(game).get(Concept.IsEnemy.id())) concepts.set(Concept.SlideDecisionToEnemy.id(), true); if (goRule instanceof BooleanConstant.TrueConstant) { concepts.set(Concept.SlideDecisionToEmpty.id(), true); concepts.set(Concept.SlideDecisionToFriend.id(), true); concepts.set(Concept.SlideDecisionToEnemy.id(), true); } } else concepts.set(Concept.SlideEffect.id(), true); if (startLocationFn != null) concepts.or(startLocationFn.concepts(game)); if (fromCondition != null) concepts.or(fromCondition.concepts(game)); if (limit != null) concepts.or(limit.concepts(game)); if (stopRule != null) concepts.or(stopRule.concepts(game)); if (toRule != null) { concepts.or(toRule.concepts(game)); if (isDecision()) { if (toRule.concepts(game).get(Concept.IsEmpty.id())) concepts.set(Concept.SlideDecisionToEmpty.id(), true); if (toRule.concepts(game).get(Concept.IsFriend.id())) concepts.set(Concept.SlideDecisionToFriend.id(), true); if (toRule.concepts(game).get(Concept.IsEnemy.id())) concepts.set(Concept.SlideDecisionToEnemy.id(), true); if (toRule instanceof BooleanConstant.TrueConstant) { concepts.set(Concept.SlideDecisionToEmpty.id(), true); concepts.set(Concept.SlideDecisionToFriend.id(), true); concepts.set(Concept.SlideDecisionToEnemy.id(), true); } } } if (let != null) concepts.or(let.concepts(game)); if (sideEffect != null) concepts.or(sideEffect.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); if (dirnChoice != null) concepts.or(dirnChoice.concepts(game)); if (betweenEffect != null) concepts.or(betweenEffect.concepts(game)); if (levelFromFn != null) concepts.or(levelFromFn.concepts(game)); // We check if that's effectively a capture (remove or fromTo). if (sideEffect != null) if (sideEffect.concepts(game).get(Concept.RemoveEffect.id()) || sideEffect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.ReplacementCapture.id(), true); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(goRule.writesEvalContextRecursive()); if (startLocationFn != null) writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); if (fromCondition != null) writeEvalContext.or(fromCondition.writesEvalContextRecursive()); if (limit != null) writeEvalContext.or(limit.writesEvalContextRecursive()); if (stopRule != null) writeEvalContext.or(stopRule.writesEvalContextRecursive()); if (toRule != null) writeEvalContext.or(toRule.writesEvalContextRecursive()); if (let != null) writeEvalContext.or(let.writesEvalContextRecursive()); if (sideEffect != null) writeEvalContext.or(sideEffect.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); if (betweenEffect != null) writeEvalContext.or(betweenEffect.writesEvalContextRecursive()); if (levelFromFn != null) writeEvalContext.or(levelFromFn.writesEvalContextRecursive()); if (dirnChoice != null) writeEvalContext.or(dirnChoice.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); writeEvalContext.set(EvalContextData.Between.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(goRule.readsEvalContextRecursive()); if (startLocationFn != null) readEvalContext.or(startLocationFn.readsEvalContextRecursive()); if (fromCondition != null) readEvalContext.or(fromCondition.readsEvalContextRecursive()); if (limit != null) readEvalContext.or(limit.readsEvalContextRecursive()); if (stopRule != null) readEvalContext.or(stopRule.readsEvalContextRecursive()); if (toRule != null) readEvalContext.or(toRule.readsEvalContextRecursive()); if (let != null) readEvalContext.or(let.readsEvalContextRecursive()); if (sideEffect != null) readEvalContext.or(sideEffect.readsEvalContextRecursive()); if (betweenEffect != null) readEvalContext.or(betweenEffect.readsEvalContextRecursive()); if (levelFromFn != null) readEvalContext.or(levelFromFn.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); if (dirnChoice != null) readEvalContext.or(dirnChoice.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (fromCondition != null) missingRequirement |= fromCondition.missingRequirement(game); missingRequirement |= goRule.missingRequirement(game); if (startLocationFn != null) missingRequirement |= startLocationFn.missingRequirement(game); if (limit != null) missingRequirement |= limit.missingRequirement(game); if (stopRule != null) missingRequirement |= stopRule.missingRequirement(game); if (toRule != null) missingRequirement |= toRule.missingRequirement(game); if (let != null) missingRequirement |= let.missingRequirement(game); if (sideEffect != null) missingRequirement |= sideEffect.missingRequirement(game); if (betweenEffect != null) missingRequirement |= betweenEffect.missingRequirement(game); if (levelFromFn != null) missingRequirement |= levelFromFn.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= goRule.willCrash(game); if (fromCondition != null) willCrash |= fromCondition.willCrash(game); if (startLocationFn != null) willCrash |= startLocationFn.willCrash(game); if (limit != null) willCrash |= limit.willCrash(game); if (stopRule != null) willCrash |= stopRule.willCrash(game); if (toRule != null) willCrash |= toRule.willCrash(game); if (let != null) willCrash |= let.willCrash(game); if (sideEffect != null) willCrash |= sideEffect.willCrash(game); if (betweenEffect != null) willCrash |= betweenEffect.willCrash(game); if (levelFromFn != null) willCrash |= levelFromFn.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); goRule.preprocess(game); if (startLocationFn != null) startLocationFn.preprocess(game); if (fromCondition != null) fromCondition.preprocess(game); if (limit != null) limit.preprocess(game); if (let != null) let.preprocess(game); if (stopRule != null) stopRule.preprocess(game); if (sideEffect != null) sideEffect.preprocess(game); if (toRule != null) toRule.preprocess(game); if (betweenEffect != null) betweenEffect.preprocess(game); if (levelFromFn != null) levelFromFn.preprocess(game); if (dirnChoice != null) dirnChoice.preprocess(game); if (trackName != null) { preComputedTracks = new ArrayList<Track>(); for (final Track t : game.board().tracks()) if (t.name().equals(trackName) || trackName.equals("AllTracks")) preComputedTracks.add(t); } } //------------------------------------------------------------------------- /** * @return The rule that tells us we're allowed to continue sliding */ public BooleanFunction goRule() { return goRule; } /** * @return The rule that tells us we have to stop sliding */ public BooleanFunction stopRule() { return stopRule; } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String text = ""; if(startLocationFn.toEnglish(game).equals("")) text = "slide in the " + dirnChoice.toEnglish(game) + " direction through " + goRule.toEnglish(game); else text = "slide from "+ startLocationFn.toEnglish(game) + " in the " + dirnChoice.toEnglish(game) + " direction through " + goRule.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); text += thenString; return text; } //------------------------------------------------------------------------- }
27,226
29.661036
173
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Sow.java
package game.rules.play.moves.nonDecision.effect; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import annotations.Name; import annotations.Opt; import annotations.Or; import game.Game; import game.equipment.container.board.Track; import game.functions.booleans.BooleanConstant; import game.functions.booleans.BooleanConstant.FalseConstant; import game.functions.booleans.BooleanFunction; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.last.LastTo; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.NonDecision; import game.types.board.SiteType; import game.types.state.GameType; import main.Constants; import other.action.Action; import other.action.move.move.ActionMove; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.context.TempContext; import other.move.Move; import other.state.container.ContainerState; /** * Sows counters by removing them from a site then placing them one-by-one at * each consecutive site along a track. * * @author Eric.Piette and cambolbro * * @remarks Sowing is used in Mancala games. A track must be defined on the * board in order for sowing to work. */ public final class Sow extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Start loc. */ private final IntFunction startLoc; /** How many components to sow. */ private final IntFunction countFn; /** How many components to place in each hole. */ private final IntFunction numPerHoleFn; /** Track to follow. */ private final String trackName; /** Owner of the track. */ private final IntFunction ownerFn; /** Start position included. */ private final boolean includeSelf; /** To put a bean in the original hole before to sow. */ private final BooleanFunction origin; /** Exception in the sow move **/ private final BooleanFunction skipFn; /** Capture rule. */ private final BooleanFunction captureRule; /** Backward capture. */ private final BooleanFunction backtracking; /** Forward capture. */ private final BooleanFunction forward; /** Capture effect. */ private final Moves captureEffect; /** Sow effect. */ private final Moves sowEffect; /** Add on Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** Pre-computed tracks in keeping only the track with the name on them. */ private List<Track> preComputedTracks = new ArrayList<Track>(); //------------------------------------------------------------------------- /** * @param type The graph element type [default SiteType of the board]. * @param start The origin of the sowing [(lastTo)]. * @param count The number of pieces to sow [(count (lastTo))]. * @param numPerHole The number of pieces to sow in each hole [1]. * @param trackName The name of the track to sow [The first track if it * exists]. * @param owner The owner of the track. * @param If The condition to capture some counters after sowing * [True]. * @param apply The move to apply if the condition is satisfied. * @param sowEffect The effect to apply to each hole sowed. * @param includeSelf True if the origin is included in the sowing [True]. * @param origin True to place a counter in the origin at the start of * sowing [False]. * @param skipIf The condition to skip a hole during the sowing. * @param backtracking Whether to apply the capture backwards from the ``to'' * site. * @param forward Whether to apply the capture forwards from the ``to'' * site. * @param then The moves applied after that move is applied. * * @example (sow if:(and (is In (to) (sites Next)) (or (= (count at:(to)) 2) (= * (count at:(to)) 3)) ) apply:(fromTo (from (to)) (to (mapEntry * (mover))) count:(count at:(to))) includeSelf:False * backtracking:True) */ public Sow ( @Opt final SiteType type, @Opt final IntFunction start, @Opt @Name final IntFunction count, @Opt @Name final IntFunction numPerHole, @Opt final String trackName, @Opt @Name final IntFunction owner, @Opt @Name final BooleanFunction If, @Opt @Name final Moves sowEffect, @Opt @Name final NonDecision apply, @Opt @Name final Boolean includeSelf, @Opt @Name final BooleanFunction origin, @Opt @Name final BooleanFunction skipIf, @Or @Opt @Name final BooleanFunction backtracking, @Or @Opt @Name final BooleanFunction forward, @Opt final Then then ) { super(then); startLoc = (start == null) ? new LastTo(null) : start; this.includeSelf = (includeSelf == null) ? true : includeSelf.booleanValue(); countFn = (count == null) ? new game.functions.ints.count.site.CountNumber(null, null, startLoc) : count; this.trackName = trackName; captureRule = (If == null) ? new BooleanConstant(true) : If; captureEffect = apply; skipFn = skipIf; this.backtracking = backtracking; this.forward = forward; this.origin = (origin == null) ? new BooleanConstant(false) : origin; ownerFn = owner; this.type = type; numPerHoleFn = (numPerHole == null) ? new IntConstant(1) : numPerHole; this.sowEffect = sowEffect; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final int start = startLoc.eval(context); final int count = countFn.eval(context); int numPerHole = numPerHoleFn.eval(context); final Moves moves = new BaseMoves(super.then()); final Move move = new Move(new ArrayList<Action>()); int numSeedSowed = 0; final ContainerState cs = context.containerState(0); final int origFrom = context.from(); final int origTo = context.to(); final int origValue = context.value(); final int owner = (ownerFn == null) ? Constants.OFF : ownerFn.eval(context); Track track = null; for (final Track t : preComputedTracks) { if (trackName == null || (owner == Constants.OFF && t.name().equals(trackName) || (owner != Constants.OFF && t.owner() == owner && t.name().contains(trackName)))) { track = t; break; } } // If the track does exist we return an empty list of moves. if (track == null) return moves; int i; for (i = 0; i < track.elems().length; i++) if (track.elems()[i].site == start) break; // If we include the origin we remove one piece to sow and we sow on the origin // location. context.setFrom(start); if (origin.eval(context)) { if(sowEffect != null) { final Moves effect = sowEffect.eval(context); for(final Move moveEffect : effect.moves()) for(final Action actionEffect : moveEffect.actions()) move.actions().add(actionEffect); } int numDone = 0; while(numDone != numPerHole) { if(numSeedSowed < count) move.actions() .add(ActionMove.construct(type, start, Constants.UNDEFINED, type, start, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, false)); numDone++; numSeedSowed++; } context.setTo(start); } context.setFrom(origFrom); // Computation of the sowing moves. if(numSeedSowed < count) { int numSkipped = 0; for (int index = 0; index < count; index++) { context.setValue(count - index); if(i >= track.elems().length) return moves; int to = track.elems()[i].next; context.setTo(to); // Check if that site should be skip. if (skipFn != null && skipFn.eval(context) && numSkipped < Constants.MAX_NUM_ITERATION) { index--; numSkipped++; i = track.elems()[i].nextIndex; to = track.elems()[i].next; continue; } else numSkipped = 0; // Check if we include the origin in the sowing movement. if (!includeSelf && to == start) { i = track.elems()[i].nextIndex; to = track.elems()[i].next; } // The sowing action for each location. final int startState = cs.state(start, type); final int startRotation = cs.rotation(start, type); final int startValue = cs.value(start, type); final int toState = cs.state(to, type); final int toRotation = cs.rotation(to, type); final int toValue = cs.value(to, type); numPerHole = numPerHoleFn.eval(context); int numDone = 0; if(sowEffect != null) { final Moves effect = sowEffect.eval(context); for(final Move moveEffect : effect.moves()) for(final Action actionEffect : moveEffect.actions()) move.actions().add(actionEffect); } while(numDone != numPerHole) { if(numSeedSowed < count) move.actions().add(ActionMove.construct(type, start, Constants.UNDEFINED, type, to, Constants.OFF, startState != toState ? toState : Constants.UNDEFINED, startRotation != toRotation ? toRotation : Constants.UNDEFINED, startValue != toValue ? toValue : Constants.UNDEFINED, false)); numDone++; numSeedSowed++; } i = track.elems()[i].nextIndex; if(numSeedSowed >= count) break; } } moves.moves().add(move); // We apply each sow move and we check the condition of capture to apply the // effect with the count value after sowing. if (captureRule != null && captureEffect != null) for (final Move sowMove : moves.moves()) { final Context newContext = new TempContext(context); sowMove.apply(newContext, false); int numCapture = 0; // If true we have to capture the pieces while (captureRule.eval(newContext)) { // We compute the capturing moves. newContext.setFrom(start); final Moves capturingMoves = captureEffect.eval(newContext); for (final Move m : capturingMoves.moves()) sowMove.actions().addAll(m.getActionsWithConsequences(newContext)); if(backtracking == null && forward == null) break; if(backtracking != null) { if (!backtracking.eval(newContext)) break; final int to = track.elems()[i].prev; i = track.elems()[i].prevIndex; newContext.setTo(to); if (!backtracking.eval(newContext)) break; if (to == start) break; } if(forward != null) { if (!forward.eval(newContext)) break; if(!track.islooped() && track.elems()[i].next == Constants.OFF) break; final int to = track.elems()[i].next; i = track.elems()[i].nextIndex; newContext.setTo(to); if (!forward.eval(newContext)) break; } numCapture++; if(numCapture >= track.elems().length) break; } } context.setTo(origTo); context.setFrom(origFrom); context.setValue(origValue); // The subsequents to add to the moves if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = GameType.Count | super.gameFlags(game); gameFlags |= GameType.UsesFromPositions; gameFlags |= startLoc.gameFlags(game); gameFlags |= countFn.gameFlags(game); gameFlags |= numPerHoleFn.gameFlags(game); if (captureEffect != null) { gameFlags |= captureEffect.gameFlags(game); if (captureEffect.then() != null) gameFlags |= captureEffect.then().gameFlags(game); } gameFlags |= SiteType.gameFlags(type); if (ownerFn != null) gameFlags |= ownerFn.gameFlags(game); if (captureRule != null) gameFlags |= captureRule.gameFlags(game); if (sowEffect != null) gameFlags |= sowEffect.gameFlags(game); if (origin != null) gameFlags |= origin.gameFlags(game); if (skipFn != null) gameFlags |= skipFn.gameFlags(game); if (backtracking != null) gameFlags |= backtracking.gameFlags(game); if (forward != null) gameFlags |= forward.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); if (captureRule != null && captureEffect != null) concepts.set(Concept.CopyContext.id(), true); concepts.set(Concept.Sow.id(), true); concepts.or(SiteType.concepts(type)); concepts.or(startLoc.concepts(game)); concepts.or(countFn.concepts(game)); concepts.or(numPerHoleFn.concepts(game)); if (captureEffect != null) { concepts.or(captureEffect.concepts(game)); if (captureEffect.then() != null) concepts.or(captureEffect.then().concepts(game)); concepts.set(Concept.SowWithEffect.id(), true); if (captureEffect.concepts(game).get(Concept.RemoveEffect.id())) concepts.set(Concept.SowRemove.id(), true); if (captureEffect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.SowCapture.id(), true); } if (ownerFn != null) concepts.or(ownerFn.concepts(game)); if (captureRule != null) concepts.or(captureRule.concepts(game)); if (sowEffect != null) concepts.or(sowEffect.concepts(game)); if (origin != null) { if (!(origin instanceof FalseConstant)) concepts.set(Concept.SowOriginFirst.id(), true); concepts.or(origin.concepts(game)); } if (skipFn != null) { concepts.set(Concept.SowSkip.id(), true); concepts.or(skipFn.concepts(game)); } if (!includeSelf) concepts.set(Concept.SowSkip.id(), true); if (backtracking != null) { concepts.or(backtracking.concepts(game)); concepts.set(Concept.SowBacktracking.id(), true); } if (forward != null) concepts.or(forward.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(startLoc.writesEvalContextRecursive()); writeEvalContext.or(countFn.writesEvalContextRecursive()); writeEvalContext.or(numPerHoleFn.writesEvalContextRecursive()); if (captureEffect != null) { writeEvalContext.or(captureEffect.writesEvalContextRecursive()); if (captureEffect.then() != null) writeEvalContext.or(captureEffect.then().writesEvalContextRecursive()); } if (ownerFn != null) writeEvalContext.or(ownerFn.writesEvalContextRecursive()); if (captureRule != null) writeEvalContext.or(captureRule.writesEvalContextRecursive()); if (sowEffect != null) writeEvalContext.or(sowEffect.writesEvalContextRecursive()); if (origin != null) writeEvalContext.or(origin.writesEvalContextRecursive()); if (skipFn != null) writeEvalContext.or(skipFn.writesEvalContextRecursive()); if (backtracking != null) writeEvalContext.or(backtracking.writesEvalContextRecursive()); if (forward != null) writeEvalContext.or(forward.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(startLoc.readsEvalContextRecursive()); readEvalContext.or(countFn.readsEvalContextRecursive()); readEvalContext.or(numPerHoleFn.readsEvalContextRecursive()); if (captureEffect != null) { readEvalContext.or(captureEffect.readsEvalContextRecursive()); if (captureEffect.then() != null) readEvalContext.or(captureEffect.then().readsEvalContextRecursive()); } if (ownerFn != null) readEvalContext.or(ownerFn.readsEvalContextRecursive()); if (captureRule != null) readEvalContext.or(captureRule.readsEvalContextRecursive()); if (sowEffect != null) readEvalContext.or(sowEffect.readsEvalContextRecursive()); if (origin != null) readEvalContext.or(origin.readsEvalContextRecursive()); if (skipFn != null) readEvalContext.or(skipFn.readsEvalContextRecursive()); if (backtracking != null) readEvalContext.or(backtracking.readsEvalContextRecursive()); if (forward != null) readEvalContext.or(forward.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (!game.hasTrack()) { game.addRequirementToReport("The ludeme (sow ...) is used but the board has no tracks."); missingRequirement = true; } if (ownerFn != null) { if (ownerFn instanceof IntConstant) { final int ownerValue = ((IntConstant) ownerFn).eval(null); if (ownerValue < 1 || ownerValue > game.players().count()) { game.addRequirementToReport("A wrong player index is used in (sow ... owner:... ...)."); missingRequirement = true; } } } missingRequirement |= startLoc.missingRequirement(game); missingRequirement |= countFn.missingRequirement(game); missingRequirement |= numPerHoleFn.missingRequirement(game); if (captureEffect != null) { missingRequirement |= captureEffect.missingRequirement(game); if (captureEffect.then() != null) missingRequirement |= captureEffect.then().missingRequirement(game); } if (ownerFn != null) missingRequirement |= ownerFn.missingRequirement(game); if (captureRule != null) missingRequirement |= captureRule.missingRequirement(game); if (sowEffect != null) missingRequirement |= sowEffect.missingRequirement(game); if (origin != null) missingRequirement |= origin.missingRequirement(game); if (skipFn != null) missingRequirement |= skipFn.missingRequirement(game); if (backtracking != null) missingRequirement |= backtracking.missingRequirement(game); if (forward != null) missingRequirement |= forward.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= startLoc.willCrash(game); willCrash |= countFn.willCrash(game); willCrash |= numPerHoleFn.willCrash(game); if (captureEffect != null) { willCrash |= captureEffect.willCrash(game); if (captureEffect.then() != null) willCrash |= captureEffect.then().willCrash(game); } if (ownerFn != null) willCrash |= ownerFn.willCrash(game); if (captureRule != null) willCrash |= captureRule.willCrash(game); if (sowEffect != null) willCrash |= sowEffect.willCrash(game); if (origin != null) willCrash |= origin.willCrash(game); if (skipFn != null) willCrash |= skipFn.willCrash(game); if (backtracking != null) willCrash |= backtracking.willCrash(game); if (forward != null) willCrash |= forward.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { // we look at "count" of specific context, so cannot be static return false; } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); startLoc.preprocess(game); countFn.preprocess(game); numPerHoleFn.preprocess(game); origin.preprocess(game); if (captureEffect != null) captureEffect.preprocess(game); if (ownerFn != null) ownerFn.preprocess(game); if (captureRule != null) captureRule.preprocess(game); if (sowEffect != null) sowEffect.preprocess(game); if (skipFn != null) skipFn.preprocess(game); if (backtracking != null) backtracking.preprocess(game); if (forward != null) forward.preprocess(game); if (captureEffect != null) captureEffect.preprocess(game); preComputedTracks = new ArrayList<Track>(); for (final Track t : game.board().tracks()) if (trackName == null || t.name().contains(trackName)) preComputedTracks.add(t); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String englishString = "Sow with the following rules, "; if (startLoc != null) englishString += "startLoc: " + startLoc.toEnglish(game) + ", "; if (countFn != null) englishString += "countFn: " + countFn.toEnglish(game) + ", "; if (numPerHoleFn != null) englishString += "numPerHoleFn: " + numPerHoleFn.toEnglish(game) + ", "; if (trackName != null) englishString += "trackName: " + trackName + ", "; if (ownerFn != null) englishString += "ownerFn: " + ownerFn.toEnglish(game) + ", "; if (origin != null) englishString += "origin: " + origin.toEnglish(game) + ", "; if (skipFn != null) englishString += "skipFn: " + skipFn.toEnglish(game) + ", "; if (captureRule != null) englishString += "captureRule: " + captureRule.toEnglish(game) + ", "; if (backtracking != null) englishString += "backtracking: " + backtracking.toEnglish(game) + ", "; if (forward != null) englishString += "forward: " + forward.toEnglish(game) + ", "; if (captureEffect != null) englishString += "captureEffect: " + captureEffect.toEnglish(game) + ", "; if (sowEffect != null) englishString += "sowEffect: " + sowEffect.toEnglish(game) + ", "; if (type != null) englishString += "type: " + type.name() + ", "; englishString += "includeSelf: " + includeSelf; String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return englishString + thenString; } //------------------------------------------------------------------------- }
22,721
28.09347
154
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Step.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Name; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanConstant; import game.functions.booleans.BooleanFunction; import game.functions.directions.Directions; import game.functions.directions.DirectionsFunction; import game.functions.ints.IntFunction; import game.functions.ints.iterator.From; import game.functions.region.RegionFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.types.state.GameType; import game.util.directions.AbsoluteDirection; import main.Constants; import other.action.Action; import other.action.move.move.ActionMove; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.Move; import other.move.MoveUtilities; import other.state.stacking.BaseContainerStateStacking; import other.topology.Topology; import other.topology.TopologyElement; /** * Moves to a connected site. * * @author Eric.Piette * * @remarks The (to ...) parameter is used to specify a condition on the site to * step and on the effect to apply. But the region function in entry of * that parameter is ignored because the region to move is implied by a * step move. */ public final class Step extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** From Condition Rule. */ private final BooleanFunction fromCondition; /** Region start of the piece. */ private final RegionFunction startRegionFn; /** Level from. */ private final IntFunction levelFromFn; /** The rule to be able to the move. */ private final BooleanFunction rule; /** The Move applied on the location reached. */ private final Moves sideEffect; /** To step a complete stack. */ private final boolean stack; /** Direction to move. */ private final DirectionsFunction dirnChoice; /** Direction to move. */ private final game.util.moves.To toRule; /** Add on Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** * @param from Description of ``from'' location [(from)]. * @param directions The directions of the move [Adjacent]. * @param to Description of the ``to'' location. * @param stack True if the move is applied to a stack [False]. * @param then Moves to apply after this one. * * @example (step (to if:(is Empty (to))) ) * * @example (step Forward (to if:(is Empty (to))) ) * * @example (step (directions {FR FL}) (to if:(or (is Empty (to)) (is Enemy (who * at:(to)))) (apply (remove (to)))) ) */ public Step ( @Opt final game.util.moves.From from, @Opt final game.util.directions.Direction directions, final game.util.moves.To to, @Opt @Name final Boolean stack, @Opt final Then then ) { super(then); // From if (from != null) { startRegionFn = from.region(); startLocationFn = from.loc(); levelFromFn = from.level(); fromCondition = from.cond(); } else { startRegionFn = null; startLocationFn = new From(null); levelFromFn = null; fromCondition = null; } type = (from == null) ? null : from.type(); // Rule rule = (to == null) ? new BooleanConstant(true) : (to.cond() == null) ? new BooleanConstant(true) : to.cond(); // The directions dirnChoice = (directions != null) ? directions.directionsFunctions() : new Directions(AbsoluteDirection.Adjacent, null); // Effect sideEffect = (to == null) ? null : to.effect(); // Stack this.stack = (stack == null) ? false : stack.booleanValue(); // We store the toRule because that can be needed in CountSteps.java toRule = to; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { if (startRegionFn != null) return evalRegion(context); final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); if (from == Constants.OFF) return moves; final int origFrom = context.from(); final int origTo = context.to(); final Topology graph = context.topology(); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); if (from >= graph.getGraphElements(realType).size()) return moves; final TopologyElement fromV = graph.getGraphElements(realType).get(from); final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, fromV, null, null, null, context); final int levelFrom = (levelFromFn == null) ? Constants.UNDEFINED : levelFromFn.eval(context); // If the level specified is less than 0, no move can be computed. if (levelFrom < Constants.UNDEFINED && levelFromFn != null) return moves; context.setFrom(from); if (fromCondition != null && !fromCondition.eval(context)) return moves; for (final AbsoluteDirection direction : directions) { final List<game.util.graph.Step> steps = graph.trajectories().steps(realType, fromV.index(), realType, direction); for (final game.util.graph.Step step : steps) { final int to = step.to().id(); context.setTo(to); if (!rule.eval(context)) continue; if (!alreadyCompute(moves, from, to)) { Action action = null; Move move = null; if (levelFrom == Constants.UNDEFINED || stack == true) { final int level = (context.game().isStacking()) ? (stack) ? Constants.UNDEFINED : context.state().containerStates()[0].sizeStack(from, type) - 1 : Constants.UNDEFINED; action = ActionMove.construct(type, from, level, type, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, stack); if (isDecision()) action.setDecision(true); move = new Move(action); // to add the levels to move a stack on the Move class (only for GUI) if (stack) { move.setLevelMinNonDecision(0); move.setLevelMaxNonDecision(context.state().containerStates()[0].sizeStack(from, type) - 1); } } else // Step a piece at a specific level. { action = ActionMove.construct(type, from, levelFrom, type, to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.OFF, stack); if (isDecision()) action.setDecision(true); move = new Move(action); move.setLevelMinNonDecision(levelFrom); move.setLevelMaxNonDecision(levelFrom); } move = MoveUtilities.chainRuleWithAction(context, sideEffect, move, true, false); MoveUtilities.chainRuleCrossProduct(context, moves, null, move, false); move.setFromNonDecision(from); move.setToNonDecision(to); } } } context.setTo(origTo); context.setFrom(origFrom); MoveUtilities.setGeneratedMovesData(moves.moves(), this, context.state().mover()); return moves; } //------------------------------------------------------------------------- /** * * Exact same idea of eval(context) but for a starting region * * @param context * @return */ private Moves evalRegion(final Context context) { final Moves moves = new BaseMoves(super.then()); if (startLocationFn == null) return moves; final int fromLocforRegion = startLocationFn.eval(context); final int[] froms = startRegionFn.eval(context).sites(); if (froms.length == 0) return moves; final int origFrom = context.from(); final int origTo = context.to(); for (final int from : froms) { if (from == Constants.OFF) continue; final Topology graph = context.topology(); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); if (from >= graph.getGraphElements(realType).size()) return moves; final TopologyElement fromV = graph.getGraphElements(realType).get(from); context.setFrom(fromV.index()); if (fromCondition != null && !fromCondition.eval(context)) continue; final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, fromV, null, null, null, context); for (final AbsoluteDirection direction : directions) { final List<game.util.graph.Step> steps = graph.trajectories().steps(realType, fromV.index(), direction); for (final game.util.graph.Step step : steps) { final int to = step.to().id(); context.setTo(to); if (!rule.eval(context)) continue; final Action action = ActionMove.construct(SiteType.Cell, from, Constants.UNDEFINED, SiteType.Cell, to, Constants.OFF, Constants.UNDEFINED, Constants.OFF, Constants.OFF, stack); if (isDecision()) action.setDecision(true); Move thisAction = new Move(action); // to add the levels to move a stack on the Move class (only for GUI) if (stack) { thisAction.setLevelMinNonDecision(0); thisAction.setLevelMaxNonDecision(((BaseContainerStateStacking) context.state().containerStates()[0]) .sizeStack(from, type) - 1); } final int origFrom2 = context.from(); final int origTo2 = context.to(); context.setFrom(fromLocforRegion); context.setTo(from); thisAction = new Move(action, sideEffect.eval(context).moves().get(0)); context.setFrom(origFrom2); context.setTo(origTo2); MoveUtilities.chainRuleCrossProduct(context, moves, null, thisAction, false); thisAction.setFromNonDecision(from); thisAction.setToNonDecision(to); } } } context.setTo(origTo); context.setFrom(origFrom); if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | rule.gameFlags(game); gameFlags |= GameType.UsesFromPositions; if (stack) gameFlags |= GameType.Stacking; if (fromCondition != null) gameFlags |= fromCondition.gameFlags(game); if (startLocationFn != null) gameFlags |= startLocationFn.gameFlags(game); if (startRegionFn != null) gameFlags |= startRegionFn.gameFlags(game); if (sideEffect != null) gameFlags |= sideEffect.gameFlags(game); if (levelFromFn != null) gameFlags |= levelFromFn.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(SiteType.concepts(type)); concepts.or(rule.concepts(game)); if (fromCondition != null) concepts.or(fromCondition.concepts(game)); if (isDecision()) { concepts.set(Concept.StepDecision.id(), true); if (rule.concepts(game).get(Concept.IsEmpty.id())) concepts.set(Concept.StepDecisionToEmpty.id(), true); if (rule.concepts(game).get(Concept.IsFriend.id())) concepts.set(Concept.StepDecisionToFriend.id(), true); if (rule.concepts(game).get(Concept.IsEnemy.id())) concepts.set(Concept.StepDecisionToEnemy.id(), true); if (rule instanceof BooleanConstant.TrueConstant) { concepts.set(Concept.StepDecisionToEmpty.id(), true); concepts.set(Concept.StepDecisionToFriend.id(), true); concepts.set(Concept.StepDecisionToEnemy.id(), true); } } else concepts.set(Concept.StepEffect.id(), true); if (startLocationFn != null) concepts.or(startLocationFn.concepts(game)); if (startRegionFn != null) concepts.or(startRegionFn.concepts(game)); if (sideEffect != null) concepts.or(sideEffect.concepts(game)); if (levelFromFn != null) concepts.or(levelFromFn.concepts(game)); if (dirnChoice != null) concepts.or(dirnChoice.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); // We check if that's effectively a capture (remove or fromTo). if (sideEffect != null) if (sideEffect.concepts(game).get(Concept.RemoveEffect.id()) || sideEffect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.ReplacementCapture.id(), true); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(rule.writesEvalContextRecursive()); if (fromCondition != null) writeEvalContext.or(fromCondition.writesEvalContextRecursive()); if (startLocationFn != null) writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); if (startRegionFn != null) writeEvalContext.or(startRegionFn.writesEvalContextRecursive()); if (sideEffect != null) writeEvalContext.or(sideEffect.writesEvalContextRecursive()); if (levelFromFn != null) writeEvalContext.or(levelFromFn.writesEvalContextRecursive()); if (dirnChoice != null) writeEvalContext.or(dirnChoice.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(rule.readsEvalContextRecursive()); if (fromCondition != null) readEvalContext.or(fromCondition.readsEvalContextRecursive()); if (startLocationFn != null) readEvalContext.or(startLocationFn.readsEvalContextRecursive()); if (startRegionFn != null) readEvalContext.or(startRegionFn.readsEvalContextRecursive()); if (sideEffect != null) readEvalContext.or(sideEffect.readsEvalContextRecursive()); if (levelFromFn != null) readEvalContext.or(levelFromFn.readsEvalContextRecursive()); if (dirnChoice != null) readEvalContext.or(dirnChoice.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= rule.missingRequirement(game); if (fromCondition != null) missingRequirement |= fromCondition.missingRequirement(game); if (startLocationFn != null) missingRequirement |= startLocationFn.missingRequirement(game); if (startRegionFn != null) missingRequirement |= startRegionFn.missingRequirement(game); if (sideEffect != null) missingRequirement |= sideEffect.missingRequirement(game); if (levelFromFn != null) missingRequirement |= levelFromFn.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= rule.willCrash(game); if (fromCondition != null) willCrash |= fromCondition.willCrash(game); if (startLocationFn != null) willCrash |= startLocationFn.willCrash(game); if (startRegionFn != null) willCrash |= startRegionFn.willCrash(game); if (sideEffect != null) willCrash |= sideEffect.willCrash(game); if (levelFromFn != null) willCrash |= levelFromFn.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); rule.preprocess(game); if (fromCondition != null) fromCondition.preprocess(game); if (startLocationFn != null) startLocationFn.preprocess(game); if (startRegionFn != null) startRegionFn.preprocess(game); if (sideEffect != null) sideEffect.preprocess(game); if (rule != null) rule.preprocess(game); if (sideEffect != null) sideEffect.preprocess(game); if (dirnChoice != null) dirnChoice.preprocess(game); if (levelFromFn != null) levelFromFn.preprocess(game); } /** * To know if a move is already compute (for wheel board with the center, this * is possible). * * @param moves * @param from * @param to * @return */ private static boolean alreadyCompute(final Moves moves, final int from, final int to) { for (final Move m : moves.moves()) { if (m.fromNonDecision() == from && m.toNonDecision() == to) { return true; } } return false; } //------------------------------------------------------------------------- /** * @return The rule telling us what we're allowed to step into */ public BooleanFunction goRule() { return rule; } /** * @return The directions. */ public DirectionsFunction directions() { return dirnChoice; } /** * @return The to rule. */ public game.util.moves.To toRule() { return toRule; } @Override public String toEnglish(final Game game) { String sideEffectEnglish = ""; if (sideEffect != null) sideEffectEnglish = sideEffect.toEnglish(game) + " then "; String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return sideEffectEnglish + "step " + dirnChoice.toEnglish(game) + thenString; } }
18,055
27.479495
182
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Surround.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import java.util.List; import annotations.Name; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanFunction; import game.functions.booleans.is.player.IsEnemy; import game.functions.booleans.is.player.IsFriend; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.functions.ints.iterator.Between; import game.functions.ints.iterator.From; import game.functions.ints.iterator.To; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.board.RelationType; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.graph.Radial; import game.util.moves.Piece; import main.Constants; import main.StringRoutines; import main.collections.FastTIntArrayList; import other.concept.Concept; import other.context.Context; import other.context.EvalContextData; import other.move.MoveUtilities; import other.topology.Topology; import other.topology.TopologyElement; /** * Is used to apply an effect to all the sites surrounded in a specific * direction. * * @author mrraow and cambolbro and Eric.Piette */ public final class Surround extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location of the piece. */ private final IntFunction startLocationFn; /** Direction chosen. */ private final AbsoluteDirection dirnChoice; /** The piece to surround. */ private final BooleanFunction targetRule; /** The rule to detect the friend to surround. */ private final BooleanFunction friendRule; /** The number of exception to surround. */ private final IntFunction exception; /** The number of exception to surround. */ private final IntFunction withAtLeastPiece; /** Moves applied after that one. */ private final Moves effect; /** Add on Cell/Edge/Vertex. */ private SiteType type; //------------------------------------------------------------------------- /** * @param from The origin to surround [(from)]. * @param relation The way to surround [Adjacent]. * @param between The condition and effect on the pieces to surround [(between * if:(is Enemy (to)) (apply (remove (to))))]. * @param to The condition on the pieces surrounding [(to if:(isFriend * (between)))]. * @param except The number of exceptions allowed to apply the effect [0]. * @param with The piece which should at least be in the surrounded pieces. * @param then The moves applied after that move is applied. * * @example (surround (from (last To)) Orthogonal (between if:(is Friend (who * at:(between))) (apply (trigger "Lost" (mover))) ) (to if:(not * (is In (to) (sites Empty))) ) ) */ public Surround ( @Opt final game.util.moves.From from, @Opt final RelationType relation, @Opt final game.util.moves.Between between, @Opt final game.util.moves.To to, @Opt @Name final IntFunction except, @Opt @Name final Piece with, @Opt final Then then ) { super(then); startLocationFn = (from == null) ? new From(null) : from.loc(); type = (from == null) ? null : from.type(); dirnChoice = (relation == null) ? AbsoluteDirection.Adjacent : RelationType.convert(relation); targetRule = (between == null || between.condition() == null) ? new IsEnemy(Between.instance(), null) : between.condition(); friendRule = (to == null || to.cond() == null) ? new IsFriend(To.instance(), null) : to.cond(); effect = (between == null || between.effect() == null) ? new Remove(null, Between.instance(), null, null, null, null, null) : between.effect(); exception = (except == null) ? new IntConstant(0) : except; withAtLeastPiece = (with == null) ? null : with.component(); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves moves = new BaseMoves(super.then()); final int from = startLocationFn.eval(context); final int fromOrig = context.from(); final int toOrig = context.to(); final int betweenOrig = context.between(); final int nbExcept = exception.eval(context); final int withPiece = (withAtLeastPiece == null) ? Constants.UNDEFINED : withAtLeastPiece.eval(context); final Topology graph = context.topology(); if (from == Constants.UNDEFINED) return new BaseMoves(null); final SiteType realType = (type != null) ? type : context.game().board().defaultSite(); final TopologyElement fromV = graph.getGraphElements(realType).get(from); final List<Radial> radialsFrom = graph.trajectories().radials(realType, fromV.index(), dirnChoice); for (final Radial radialFrom : radialsFrom) { final FastTIntArrayList betweenSites = new FastTIntArrayList(); if (radialFrom.steps().length < 2) continue; final int locationUnderThreat = radialFrom.steps()[1].id(); if (!isTarget(context, locationUnderThreat)) continue; // Check neighbours of threatened pieces int except = 0; // Check if at least one piece surrounding the target is the correct piece. boolean withPieceOk = false; final List<Radial> radialsUnderThreat = graph.trajectories().radials(type, locationUnderThreat, dirnChoice); for (final Radial radialUnderThreat : radialsUnderThreat) { final int friendPieceSite = radialUnderThreat.steps()[1].id(); final boolean isThreat = radialUnderThreat.steps().length < 2 || friendPieceSite == from || isFriend(context, friendPieceSite); if (!isThreat) except++; final int whatFriend = context.containerState(context.containerId()[friendPieceSite]) .what(friendPieceSite, realType); if (withPiece == Constants.UNDEFINED || withPiece == whatFriend) withPieceOk = true; if (except > nbExcept) break; } if (except <= nbExcept && withPieceOk) { context.setBetween(locationUnderThreat); betweenSites.add(locationUnderThreat); MoveUtilities.chainRuleCrossProduct(context, moves, effect, null, false); moves.moves().get(moves.moves().size() - 1).setBetweenNonDecision(new FastTIntArrayList(betweenSites)); } } context.setBetween(betweenOrig); context.setFrom(fromOrig); context.setTo(toOrig); // Store the Moves in the computed moves. for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).setMovesLudeme(this); return moves; } private boolean isFriend( final Context context, final int location ) { context.setTo(location); return friendRule.eval(context); } private boolean isTarget( final Context context, final int location ) { context.setBetween(location); return targetRule.eval(context); } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = startLocationFn.gameFlags(game) | targetRule.gameFlags(game) | friendRule.gameFlags(game) | effect.gameFlags(game) | exception.gameFlags(game) | super.gameFlags(game); if (withAtLeastPiece != null) gameFlags |= withAtLeastPiece.gameFlags(game); gameFlags |= SiteType.gameFlags(type); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(SiteType.concepts(type)); concepts.or(super.concepts(game)); concepts.or(startLocationFn.concepts(game)); concepts.or(targetRule.concepts(game)); concepts.or(friendRule.concepts(game)); concepts.or(effect.concepts(game)); concepts.or(exception.concepts(game)); if (withAtLeastPiece != null) concepts.or(withAtLeastPiece.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); // We check if that's effectively a capture (remove or fromTo). if (effect.concepts(game).get(Concept.RemoveEffect.id()) || effect.concepts(game).get(Concept.FromToEffect.id())) concepts.set(Concept.SurroundCapture.id(), true); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(startLocationFn.writesEvalContextRecursive()); writeEvalContext.or(targetRule.writesEvalContextRecursive()); writeEvalContext.or(friendRule.writesEvalContextRecursive()); writeEvalContext.or(effect.writesEvalContextRecursive()); writeEvalContext.or(exception.writesEvalContextRecursive()); if (withAtLeastPiece != null) writeEvalContext.or(withAtLeastPiece.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.To.id(), true); writeEvalContext.set(EvalContextData.From.id(), true); writeEvalContext.set(EvalContextData.Between.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(startLocationFn.readsEvalContextRecursive()); readEvalContext.or(targetRule.readsEvalContextRecursive()); readEvalContext.or(friendRule.readsEvalContextRecursive()); readEvalContext.or(effect.readsEvalContextRecursive()); readEvalContext.or(exception.readsEvalContextRecursive()); if (withAtLeastPiece != null) readEvalContext.or(withAtLeastPiece.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= startLocationFn.missingRequirement(game); missingRequirement |= targetRule.missingRequirement(game); missingRequirement |= friendRule.missingRequirement(game); missingRequirement |= effect.missingRequirement(game); missingRequirement |= exception.missingRequirement(game); if (withAtLeastPiece != null) missingRequirement |= withAtLeastPiece.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= startLocationFn.willCrash(game); willCrash |= targetRule.willCrash(game); willCrash |= friendRule.willCrash(game); willCrash |= effect.willCrash(game); willCrash |= exception.willCrash(game); if (withAtLeastPiece != null) willCrash |= withAtLeastPiece.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { type = SiteType.use(type, game); super.preprocess(game); startLocationFn.preprocess(game); targetRule.preprocess(game); friendRule.preprocess(game); effect.preprocess(game); exception.preprocess(game); if (withAtLeastPiece != null) withAtLeastPiece.preprocess(game); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String targetString = ""; if (targetRule != null) targetString = " if the target is " + targetRule.toEnglish(game); String friendString = ""; if (friendRule != null) friendString = " if the friend is " + friendRule.toEnglish(game); String exceptString = ""; if (exception != null) exceptString = " except if " + exception.toEnglish(game); String directionString = ""; if (dirnChoice != null) directionString += " with "+ dirnChoice.name()+ " direction"; String fromString = ""; if (startLocationFn != null) fromString = " starting from " + startLocationFn.toEnglish(game); String limitString = ""; if (withAtLeastPiece != null) limitString = " with at least " + withAtLeastPiece.toEnglish(game) + " pieces"; String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "for all surrounded pieces on " + type.name() + StringRoutines.getPlural(type.name()) + fromString + directionString + limitString + targetString + friendString + exceptString + effect.toEnglish(game) + thenString; } //------------------------------------------------------------------------- }
12,950
29.909308
223
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Then.java
package game.rules.play.moves.nonDecision.effect; import java.io.Serializable; import java.util.BitSet; import annotations.Name; import annotations.Opt; import game.Game; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.NonDecision; import other.BaseLudeme; import other.concept.Concept; /** * Defines the subsequents of a move, to be applied after the move. * * @author Eric.Piette and cambolbro * * @remarks This is used to define subsequent moves by the same player in a * turn after a move is made. */ public class Then extends BaseLudeme implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- private final Moves moves; //------------------------------------------------------------------------- /** * @param moves The moves to apply afterwards. * @param applyAfterAllMoves For simultaneous game, to apply the subsequents * when all the moves of all the players are applied. * * @example (then (moveAgain)) */ public Then ( final NonDecision moves, @Opt @Name final Boolean applyAfterAllMoves ) { this.moves = moves; this.moves.setApplyAfterAllMoves((applyAfterAllMoves == null) ? false : applyAfterAllMoves.booleanValue()); } //------------------------------------------------------------------------- // Ludeme overrides @Override public String toString() { return "[Then: " + moves + "]"; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((moves == null) ? 0 : moves.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof Then)) return false; final Then other = (Then) obj; if (moves == null) if (other.moves != null) return false; else if (!moves.equals(other.moves)) return false; return true; } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { return moves.toEnglish(game); } //------------------------------------------------------------------------- /** * @return Moves in the consequence. */ public Moves moves() { return moves; } /** * @param game * @return gameFlags of the csq. */ public long gameFlags(final Game game) { long gameFlags = 0; if (moves != null) gameFlags |= moves.gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.set(Concept.Then.id(), true); if (moves != null) concepts.or(moves.concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); if (moves != null) writeEvalContext.or(moves.writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); if (moves != null) readEvalContext.or(moves.readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; if (moves != null) missingRequirement |= moves.missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; if (moves != null) willCrash |= moves.willCrash(game); return willCrash; } }
3,707
21.472727
109
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Trigger.java
package game.rules.play.moves.nonDecision.effect; import java.util.BitSet; import annotations.Opt; import annotations.Or; import game.Game; import game.functions.ints.IntConstant; import game.functions.ints.IntFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.play.RoleType; import other.concept.Concept; import other.context.Context; import other.move.Move; /** * Sets the 'triggered' value for a player for a specific event. * * @author cambolbro and Eric.Piette */ public final class Trigger extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the player. */ private final IntFunction playerFunction; /** The event to trigger. */ private final String event; //------------------------------------------------------------------------- /** * @param event The event to trigger. * @param indexPlayer The index of the player. * @param role The roleType of the player. * @param then The moves applied after that move is applied. * * @example (trigger "FlagCaptured" Next) */ public Trigger ( final String event, @Or final IntFunction indexPlayer, @Or final RoleType role, @Opt final Then then ) { super(then); int numNonNull = 0; if (indexPlayer != null) numNonNull++; if (role != null) numNonNull++; if (numNonNull != 1) throw new IllegalArgumentException("Exactly one Or parameter must be non-null."); if (indexPlayer != null) playerFunction = indexPlayer; else playerFunction = RoleType.toIntFunction(role); this.event = event; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final int victim = playerFunction.eval(context); final Moves moves = new BaseMoves(super.then()); moves.moves().add(new Move(new other.action.state.ActionTrigger(event, victim))); return moves; } //------------------------------------------------------------------------- @Override public boolean canMoveTo(final Context context, final int target) { return false; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = playerFunction.gameFlags(game) | super.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(playerFunction.concepts(game)); concepts.set(Concept.Trigger.id(), true); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(playerFunction.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(playerFunction.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= playerFunction.missingRequirement(game); if (playerFunction instanceof IntConstant) { final int playerValue = ((IntConstant) playerFunction).eval(null); if (playerValue < 1 || playerValue > game.players().size()) { game.addRequirementToReport("A wrong player index is used in (trigger ...)."); missingRequirement = true; } } if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= playerFunction.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return playerFunction.isStatic(); } @Override public void preprocess(final Game game) { super.preprocess(game); playerFunction.preprocess(game); } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "trigger " + event + " for Player " + playerFunction.toEnglish(game) + thenString; } //------------------------------------------------------------------------- }
5,066
23.597087
91
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/Vote.java
package game.rules.play.moves.nonDecision.effect; import java.util.Arrays; import java.util.BitSet; import annotations.Opt; import annotations.Or; import game.Game; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.state.GameType; import main.Constants; import other.action.Action; import other.action.others.ActionVote; import other.concept.Concept; import other.context.Context; import other.move.Move; //----------------------------------------------------------------------------- /** * Is used to propose something to the other players. * * @author Eric.Piette and cambolbro */ public final class Vote extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** All the votes. */ private final String[] votes; /** The int representations of all the votes */ private final int[] voteInts; //------------------------------------------------------------------------- /** * @param vote The vote. * @param votes The votes. * @param then The moves applied after that move is applied. * * @example (vote "End") */ public Vote ( @Or final String vote, @Or final String[] votes, @Opt final Then then ) { super(then); int numNonNull = 0; if (vote != null) numNonNull++; if (votes != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException("Only one Or parameter can be non-null."); if (votes != null) { this.votes = votes; } else { this.votes = new String[1]; this.votes[0] = vote; } voteInts = new int[this.votes.length]; Arrays.fill(voteInts, Constants.UNDEFINED); } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final BaseMoves moves = new BaseMoves(super.then()); for (final int vote : voteInts) { // NOTE: if we have a -1 here, that means that preprocess() was not called! final Action action = new ActionVote(context.game().voteString(vote), vote); if (isDecision()) action.setDecision(true); final Move move = new Move(action); move.setFromNonDecision(Constants.OFF); move.setToNonDecision(Constants.OFF); move.setMover(context.state().mover()); moves.moves().add(move); } if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); return moves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = super.gameFlags(game) | GameType.Vote; if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); if (isDecision()) concepts.set(Concept.VoteDecision.id(), true); else concepts.set(Concept.VoteEffect.id(), true); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { final boolean isStatic = false; return isStatic; } @Override public void preprocess(final Game game) { super.preprocess(game); for (int i = 0; i < votes.length; ++i) { voteInts[i] = game.registerVoteString(votes[i]); } } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "cast a vote with possible vote options " + Arrays.toString(votes) + thenString; } //------------------------------------------------------------------------- }
4,877
22.009434
89
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/package-info.java
/** * Effect moves are those moves that are applied as the result of a player decision. */ package game.rules.play.moves.nonDecision.effect;
143
27.8
84
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/requirement/AvoidStoredState.java
package game.rules.play.moves.nonDecision.effect.requirement; import java.util.BitSet; import annotations.Opt; import game.Game; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.effect.Effect; import game.rules.play.moves.nonDecision.effect.Then; import other.concept.Concept; import other.context.Context; import other.context.TempContext; import other.move.Move; /** * Filters the legal moves to avoid reaching a specific state. * * @author Eric.Piette * * @remarks Example: Arimaa. */ public final class AvoidStoredState extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The possible moves. */ private final Moves moves; /** * @param moves The moves to filter. * @param then The moves applied after that move is applied. * @example (avoidStoredState (forEach Piece)) */ public AvoidStoredState ( final Moves moves, @Opt final Then then ) { super(then); this.moves = moves; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves returnMoves = new BaseMoves(super.then()); final Moves movesToEval = moves.eval(context); final long stateToCompare = context.state().storedState(); for (int i = 0; i < movesToEval.moves().size(); i++) { final Move m = movesToEval.moves().get(i); final Context newContext = new TempContext(context); m.apply(newContext, true); if (newContext.state().stateHash() != stateToCompare) returnMoves.moves().add(m); } // Store the Moves in the computed moves. for (int j = 0; j < returnMoves.moves().size(); j++) returnMoves.moves().get(j).setMovesLudeme(this); // Store the Moves in the computed moves. for (int j = 0; j < returnMoves.moves().size(); j++) returnMoves.moves().get(j).setMovesLudeme(this); return returnMoves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = moves.gameFlags(game) | super.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.set(Concept.CopyContext.id(), true); concepts.set(Concept.PositionalSuperko.id(), true); concepts.or(moves.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(moves.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(moves.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= moves.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= moves.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { final boolean isStatic = moves.isStatic(); return isStatic; } @Override public void preprocess(final Game game) { moves.preprocess(game); } @Override public String toEnglish(final Game game) { String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return "Filter the legal moves to avoid reaching a specific state" + thenString; } }
4,346
23.15
82
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/requirement/Do.java
package game.rules.play.moves.nonDecision.effect.requirement; import java.util.BitSet; import java.util.Iterator; import java.util.function.BiPredicate; import annotations.Name; import annotations.Opt; import game.Game; import game.functions.booleans.BooleanFunction; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.effect.Effect; import game.rules.play.moves.nonDecision.effect.Then; import game.types.play.RepetitionType; import main.collections.FastArrayList; import other.MetaRules; import other.concept.Concept; import other.context.Context; import other.context.TempContext; import other.move.Move; import other.move.MovesIterator; /** * Applies two moves in order, according to given conditions. * * @author Eric.Piette * * @remarks Use ifAfterwards to filter out moves that do not satisfy some * required condition after they are applied. */ public final class Do extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The pre-condition moves. */ final Moves prior; /** The moves applied next to the prior moves. */ final Moves next; /** The conditions to check after these moves. */ final BooleanFunction ifAfterwards; //------------------------------------------------------------------------- /** * @param prior Moves to be applied first. * @param next Follow-up moves computed after the first set of moves. * The prior moves are not returned if that set of moves is * empty. * @param ifAfterwards Moves must satisfy this condition afterwards to be legal. * @param then The moves applied after that move is applied. * * @example (do (roll) next:(if (!= (count Pips) 0) (forEach Piece))) * * @example (do (fromTo (from (sites Occupied by:All container:(mover))) (to * (sites LineOfPlay))) ifAfterwards:(is PipsMatch) ) */ public Do ( final Moves prior, @Opt @Name final Moves next, @Opt @Name final BooleanFunction ifAfterwards, @Opt final Then then ) { super(then); this.next = next; this.prior = prior; this.ifAfterwards = ifAfterwards; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { // Return intersected list of moves final Moves result = new BaseMoves(super.then()); // Code of the previous prior code if (next != null) { // WARNING: if any additional code for prior / premoves is required, do it // in helper methods like the two we're already calling below! That allows // for easy reproduction of the same functionality in FilterPlayout final Context newContext = new TempContext(context); final Moves preMoves = generateAndApplyPreMoves(context, newContext); result.moves().addAll(next.eval(newContext).moves()); prependPreMoves(preMoves, result, context); } // Code of the previous filter if (ifAfterwards != null) { final Moves movesAfterIf = new BaseMoves(super.then()); final FastArrayList<Move> toCheck = (next == null) ? prior.eval(context).moves() : result.moves(); if (ifAfterwards.autoSucceeds()) { movesAfterIf.moves().addAll(toCheck); } else { for (final Move m : toCheck) if (movePassesCond(m, context, false)) movesAfterIf.moves().add(m); } if (then() != null) for (int j = 0; j < movesAfterIf.moves().size(); j++) movesAfterIf.moves().get(j).then().add(then().moves()); return movesAfterIf; } // End result of the previous prior code if (then() != null) for (int j = 0; j < result.moves().size(); j++) result.moves().get(j).then().add(then().moves()); return result; } /** * Helper method to generate pre-moves from one context, and apply them to * another context, and return the generated pre-moves. * * @param genContext * @param applyContext * @return Generated pre-moves (already applied to given context) */ public final Moves generateAndApplyPreMoves(final Context genContext, final Context applyContext) { final Moves preMoves = new BaseMoves(null); for (final Move m : prior.eval(genContext).moves()) { final Move appliedMove = (Move) m.apply(applyContext, false); preMoves.moves().add(appliedMove); } return preMoves; } /** * Processes the given result moves by prepending the given preMoves. * * @param preMoves * @param result * @param context */ public static void prependPreMoves(final Moves preMoves, final Moves result, final Context context) { // We insert the pre elements at the beginning. int insertIndex = 0; for (final Move preM : preMoves.moves()) { for (final Move move : result.moves()) { move.actions().addAll(insertIndex, preM.actions()); } insertIndex = preM.actions().size(); } if (result.moves().isEmpty() && context.game().hasHandDice()) { final Move passMove = Game.createPassMove(context,true); for (final Move preM : preMoves.moves()) passMove.actions().addAll(0, preM.actions()); result.moves().add(passMove); } } //------------------------------------------------------------------------- @Override public MovesIterator movesIterator(final Context context) { if (next == null && ifAfterwards != null) { return new MovesIterator() { protected Iterator<Move> itr = prior.movesIterator(context); protected Move nextMove = computeNextMove(); @Override public boolean hasNext() { return (nextMove != null); } @Override public Move next() { final Move ret = nextMove; nextMove = computeNextMove(); if (then() != null) ret.then().add(then().moves()); return ret; } /** * Computes the move to return for the subsequent next() call * * @return */ private Move computeNextMove() { while (itr.hasNext()) { final Move nextC = itr.next(); if (ifAfterwards.autoSucceeds() || movePassesCond(nextC, context, false)) return nextC; } return null; } @Override public boolean canMoveConditionally(final BiPredicate<Context, Move> predicate) { while (nextMove != null) { if (then() != null) nextMove.then().add(then().moves()); if (predicate.test(context, nextMove)) return true; else nextMove = computeNextMove(); } return false; } }; } else { // TODO see if we can also provide optimised implementation for this case return super.movesIterator(context); } } //------------------------------------------------------------------------- /** * Helper method to check if a move passes our condition in a given context * * @param m * @param context * @param includeRepetitionTests If true, we'll also immediately perform any state * repetition tests that the game may require. * @return True if move passes condition */ public boolean movePassesCond ( final Move m, final Context context, final boolean includeRepetitionTests ) { final Context newContext = new TempContext(context); // System.out.println("Owner of " + m.getTo() + ": " + // newContext.state().containerStates()[0].who(m.getTo())); m.apply(newContext, true); // DONE TO AVOID ANY REPLAY MOVE (e.g. Bug in Chess found by Wijnand :) ) if (newContext.state().mover() == newContext.state().next()) newContext.state().setNext(newContext.state().prev()); if (includeRepetitionTests && !m.isPass()) { final Game game = context.game(); final MetaRules metaRules = game.metaRules(); final RepetitionType type = metaRules.repetitionType(); if(type != null) { switch (type) { case PositionalInTurn: if (context.trial().previousStateWithinATurn().contains(newContext.state().stateHash())) return false; break; case SituationalInTurn: if (context.trial().previousStateWithinATurn().contains(newContext.state().fullHash())) return false; break; case Positional: if (context.trial().previousState().contains(newContext.state().stateHash())) return false; break; case Situational: if (context.trial().previousState().contains(newContext.state().fullHash())) return false; break; default: break; } } } return ifAfterwards.eval(newContext); } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = prior.gameFlags(game) | super.gameFlags(game); if (next != null) gameFlags |= next.gameFlags(game); if (ifAfterwards != null) gameFlags |= ifAfterwards.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(prior.concepts(game)); concepts.set(Concept.CopyContext.id(), true); concepts.set(Concept.DoLudeme.id(), true); if (next != null) concepts.or(next.concepts(game)); if (ifAfterwards != null) concepts.or(ifAfterwards.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.or(super.writesEvalContextRecursive()); writeEvalContext.or(prior.writesEvalContextRecursive()); if (next != null) writeEvalContext.or(next.writesEvalContextRecursive()); if (ifAfterwards != null) writeEvalContext.or(ifAfterwards.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(prior.readsEvalContextRecursive()); if (next != null) readEvalContext.or(next.readsEvalContextRecursive()); if (ifAfterwards != null) readEvalContext.or(ifAfterwards.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; missingRequirement |= super.missingRequirement(game); missingRequirement |= prior.missingRequirement(game); if (next != null) missingRequirement |= next.missingRequirement(game); if (ifAfterwards != null) missingRequirement |= ifAfterwards.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= prior.willCrash(game); if (next != null) willCrash |= next.willCrash(game); if (ifAfterwards != null) willCrash |= ifAfterwards.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { return false; } @Override public void preprocess(final Game game) { super.preprocess(game); prior.preprocess(game); if (next != null) next.preprocess(game); if (ifAfterwards != null) ifAfterwards.preprocess(game); } //------------------------------------------------------------------------- /** * @return Prior moves generator (or main moves generator if there is no "then") */ public Moves prior() { return prior; } /** * @return Main moves generator after prior (may be null, then prior becomes main * moves generator) */ public Moves after() { return next; } /** * @return The condition that must hold in game state after executing moves for * those moves to be considered legal. */ public BooleanFunction ifAfter() { return ifAfterwards; } //------------------------------------------------------------------------- @Override public boolean canMoveTo(final Context context, final int target) { if (next != null) return next.canMoveTo(context, target); if (ifAfterwards != null) { if (ifAfterwards.autoSucceeds()) return prior.canMoveTo(context, target); final Iterator<Move> movesIterator = movesIterator(context); while (movesIterator.hasNext()) { final Move m = movesIterator.next(); if (m.toNonDecision() == target) return true; } return false; } return false; } //------------------------------------------------------------------------- @Override public String toEnglish(final Game game) { String nextString = ""; if (next != null) nextString = " and afterwards " + next.toEnglish(game); String thenString = ""; if (then() != null) thenString = " then " + then().toEnglish(game); return prior.toEnglish(game) + nextString + thenString; } //------------------------------------------------------------------------- }
13,355
24.933981
101
java
Ludii
Ludii-master/Core/src/game/rules/play/moves/nonDecision/effect/requirement/FirstMoveOnTrack.java
package game.rules.play.moves.nonDecision.effect.requirement; import java.util.BitSet; import annotations.Opt; import game.Game; import game.equipment.container.board.Track; import game.functions.ints.board.Id; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.rules.play.moves.nonDecision.effect.Effect; import game.rules.play.moves.nonDecision.effect.Then; import game.types.play.RoleType; import main.Constants; import other.context.Context; import other.context.EvalContextData; /** * Returns the first legal move on the track. * * @author Eric.Piette * * @remarks Example Backgammon. */ public final class FirstMoveOnTrack extends Effect { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The moves to check. */ private final Moves moves; /** The name of the track. */ private final String trackName; /** The owner of the track. */ private final RoleType owner; /** * @param trackName The name of the track. * @param owner The owner of the track. * @param moves The moves to check. * @param then The moves applied after that move is applied. * * @example (firstMoveOnTrack (forEach Piece)) */ public FirstMoveOnTrack ( @Opt final String trackName, @Opt final RoleType owner, final Moves moves, @Opt final Then then ) { super(then); this.moves = moves; this.trackName = trackName; this.owner = owner; } //------------------------------------------------------------------------- @Override public Moves eval(final Context context) { final Moves returnMoves = new BaseMoves(super.then()); final int who = (owner == null) ? Constants.UNDEFINED : new Id(null, owner).eval(context); Track track = null; for (final Track t : context.tracks()) { if (trackName == null || (who == Constants.OFF && t.name().equals(trackName) || (who != Constants.OFF && t.owner() == who && t.name().contains(trackName)))) { track = t; break; } } // If the track does exist we return an empty list of moves. if (track == null) return moves; final int originSiteValue = context.site(); for (int i = 0; i < track.elems().length; i++) { final int site = track.elems()[i].site; if (site < 0) continue; context.setSite(site); final Moves movesComputed = moves.eval(context); if (!movesComputed.moves().isEmpty()) { returnMoves.moves().addAll(movesComputed.moves()); break; } } context.setSite(originSiteValue); // The subsequents to add to the moves if (then() != null) for (int j = 0; j < moves.moves().size(); j++) moves.moves().get(j).then().add(then().moves()); // Store the Moves in the computed moves. for (int j = 0; j < returnMoves.moves().size(); j++) returnMoves.moves().get(j).setMovesLudeme(this); return returnMoves; } //------------------------------------------------------------------------- @Override public long gameFlags(final Game game) { long gameFlags = moves.gameFlags(game) | super.gameFlags(game); if (then() != null) gameFlags |= then().gameFlags(game); return gameFlags; } @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); concepts.or(super.concepts(game)); concepts.or(moves.concepts(game)); if (then() != null) concepts.or(then().concepts(game)); return concepts; } @Override public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = writesEvalContextFlat(); writeEvalContext.or(moves.writesEvalContextRecursive()); if (then() != null) writeEvalContext.or(then().writesEvalContextRecursive()); return writeEvalContext; } @Override public BitSet writesEvalContextFlat() { final BitSet writeEvalContext = new BitSet(); writeEvalContext.set(EvalContextData.Site.id(), true); return writeEvalContext; } @Override public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); readEvalContext.or(super.readsEvalContextRecursive()); readEvalContext.or(moves.readsEvalContextRecursive()); if (then() != null) readEvalContext.or(then().readsEvalContextRecursive()); return readEvalContext; } @Override public boolean missingRequirement(final Game game) { boolean missingRequirement = false; if (!game.hasTrack()) { game.addRequirementToReport("The ludeme (firstMoveOnTrack ...) is used but the board has no tracks."); missingRequirement = true; } missingRequirement |= super.missingRequirement(game); missingRequirement |= moves.missingRequirement(game); if (then() != null) missingRequirement |= then().missingRequirement(game); return missingRequirement; } @Override public boolean willCrash(final Game game) { boolean willCrash = false; willCrash |= super.willCrash(game); willCrash |= moves.willCrash(game); if (then() != null) willCrash |= then().willCrash(game); return willCrash; } @Override public boolean isStatic() { final boolean isStatic = moves.isStatic(); return isStatic; } @Override public void preprocess(final Game game) { moves.preprocess(game); } }
5,223
23.297674
105
java