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/metadata/graphics/util/ScoreDisplayInfo.java
package metadata.graphics.util; import game.functions.ints.IntFunction; import game.types.play.RoleType; /** * Display information when drawing local states or values on a piece. * @author Matthew.Stephenson */ public class ScoreDisplayInfo { /** When the score should be shown. */ private final WhenScoreType showScore; /** Player whose index is to be matched. */ private final RoleType roleType; /** Replacement value to display instead of score. */ private final IntFunction scoreReplacement; /** Extra string to append to the score displayed. */ private final String scoreSuffix; /** * Default constructor */ public ScoreDisplayInfo() { showScore = WhenScoreType.Always; roleType = RoleType.All; scoreReplacement = null; scoreSuffix = ""; } /** * @param showScore * @param roleType * @param scoreReplacement * @param scoreSuffix */ public ScoreDisplayInfo(final WhenScoreType showScore, final RoleType roleType, final IntFunction scoreReplacement, final String scoreSuffix) { this.showScore = showScore; this.roleType = roleType; this.scoreReplacement = scoreReplacement; this.scoreSuffix = scoreSuffix; } /** * @return When the score should be shown. */ public WhenScoreType showScore() { return showScore; } /** * @return Player whose index is to be matched. */ public RoleType roleType() { return roleType; } /** * @return Replacement value to display instead of score. */ public IntFunction scoreReplacement() { return scoreReplacement; } /** * @return Extra string to append to the score displayed. */ public String scoreSuffix() { return scoreSuffix; } }
1,676
19.45122
142
java
Ludii
Ludii-master/Core/src/metadata/graphics/util/StackPropertyType.java
package metadata.graphics.util; import java.util.BitSet; import game.Game; import metadata.graphics.GraphicsItem; /** * Defines different aspects of a stack. * * @author matthew.stephenson */ public enum StackPropertyType implements GraphicsItem { /** Stack scale. */ Scale(1), /** Stack maximum number of pieces (used by some stack types). */ Limit(2), /** Stack design. */ Type(3), ; //------------------------------------------------------------------------- private final int number; private StackPropertyType(final int number) { this.number = number; } /** * @return The number. */ public int number() { return number; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); return concepts; } @Override public long gameFlags(final Game game) { final long gameFlags = 0l; return gameFlags; } @Override public boolean needRedraw() { return false; } }
1,051
15.184615
76
java
Ludii
Ludii-master/Core/src/metadata/graphics/util/ValueDisplayInfo.java
package metadata.graphics.util; /** * Display information when drawing local states or values on a piece. * @author Matthew.Stephenson */ public class ValueDisplayInfo { /** The location to draw the value. */ private ValueLocationType locationType = ValueLocationType.None; /** Offset the image by the size of the displayed value. */ private boolean offsetImage = false; /** Draw outline around the displayed value. */ private boolean valueOutline = false; /** Scale of drawn value. */ private float scale = 1.f; /** Offset right for drawn value. */ private float offsetX = 0; /** Offset down for drawn value. */ private float offsetY = 0; //------------------------------------------------------------------------- /** * Default constructor */ public ValueDisplayInfo() { // Default constructor } //------------------------------------------------------------------------- /** * @param locationType * @param offsetImage * @param valueOutline * @param scale * @param offsetX * @param offsetY */ public ValueDisplayInfo ( final ValueLocationType locationType, final boolean offsetImage, final boolean valueOutline, final float scale, final float offsetX, final float offsetY ) { this.locationType = locationType; this.offsetImage = offsetImage; this.valueOutline = valueOutline; this.scale = scale; this.offsetX = offsetX; this.offsetY = offsetY; } //------------------------------------------------------------------------- /** * @return locationType */ public ValueLocationType getLocationType() { return locationType; } //------------------------------------------------------------------------- /** * @return offsetImage */ public boolean isOffsetImage() { return offsetImage; } //------------------------------------------------------------------------- /** * @return valueOutline */ public boolean isValueOutline() { return valueOutline; } //------------------------------------------------------------------------- /** * @return Scale of drawn image along x-axis. */ public float scale() { return scale; } //------------------------------------------------------------------------- /** * @return Offset right for drawn image. */ public float offsetX() { return offsetX; } //------------------------------------------------------------------------- /** * @return Offset down for drawn image. */ public float offsetY() { return offsetY; } //------------------------------------------------------------------------- }
2,621
19.484375
76
java
Ludii
Ludii-master/Core/src/metadata/graphics/util/ValueLocationType.java
package metadata.graphics.util; import java.util.BitSet; import game.Game; import metadata.graphics.GraphicsItem; /** * Specified where to draw state of an item in the interface, relative to its position. * * @author matthew.stephenson and cambolbro */ public enum ValueLocationType implements GraphicsItem { /** No location. */ None, /** At the top left corner of the item's location. */ CornerLeft, /** At the top left corner of the item's location. */ CornerRight, /** At the top of the item's location. */ Top, /** Centred on the item's location. */ Middle, ; //------------------------------------------------------------------------------- @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); return concepts; } @Override public long gameFlags(final Game game) { final long gameFlags = 0l; return gameFlags; } @Override public boolean needRedraw() { return false; } }
968
16.944444
87
java
Ludii
Ludii-master/Core/src/metadata/graphics/util/WhenScoreType.java
package metadata.graphics.util; import java.util.BitSet; import game.Game; import metadata.graphics.GraphicsItem; /** * Specifies when to show player scores to the user. * * @author matthew.stephenson and cambolbro */ public enum WhenScoreType implements GraphicsItem { /** Always show player scores. */ Always, /** Never show player scores. */ Never, /** Only show player scores at end of game. */ AtEnd, ; //------------------------------------------------------------------------------- @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); return concepts; } @Override public long gameFlags(final Game game) { final long gameFlags = 0l; return gameFlags; } @Override public boolean needRedraw() { return false; } }
804
15.770833
82
java
Ludii
Ludii-master/Core/src/metadata/graphics/util/package-info.java
/** * The ``util'' metadata items are used for setting miscellaneous properties of the current game. */ package metadata.graphics.util;
138
26.8
97
java
Ludii
Ludii-master/Core/src/metadata/graphics/util/colour/Colour.java
package metadata.graphics.util.colour; import java.awt.Color; import java.util.BitSet; import game.Game; import metadata.graphics.GraphicsItem; /** * Defines a colour for use in metadata items. * * @author cambolbro * * @remarks: Support formats: RGB, RGBA, HSV, Hex code and UserColourType. */ public class Colour implements GraphicsItem { private final Color colour; //----------------------------------------------------------------------- /** * For defining a colour with the Red Green Blue values. * * @param r Red component [0..255]. * @param g Green component [0..255]. * @param b Blue component [0..255]. * * @example (colour 255 0 0) */ public Colour(final Integer r, final Integer g, final Integer b) { colour = new Color(r.intValue(), g.intValue(), b.intValue()); } /** * For defining a colour with the Red Green Blue values and an alpha value. * * @param r Red component [0..255]. * @param g Green component [0..255]. * @param b Blue component [0..255]. * @param a Alpha component [0..255]. * * @example (colour 255 0 0 127) */ public Colour(final Integer r, final Integer g, final Integer b, final Integer a) { colour = new Color(r.intValue(), g.intValue(), b.intValue(), a.intValue()); } // /** // * @param h Hue component [0..1]. // * @param s Saturation component [0..1]. // * @param v Value component [0..1]. // * // * @example (colour 0.5 0.5 0.2) // */ // public Colour(final Float h, final Float s, final Float v) // { // this.colour = HSVtoColor(h, s, v); // } /** * For defining a colour with the hex code. * * @param hexCode Six digit hexadecimal code. * * @example (colour "#00ff1a") */ public Colour(final String hexCode) { colour = interpretHexCode(hexCode); } /** * For defining a predefined colour. * * @param type Predefined user colour type. * * @example (colour DarkBlue) */ public Colour(final UserColourType type) { colour = type.colour(); } // /** // * For defining a colour with a player roletype. // * Only works for real players, not shared or neutral. // * // * @param roletype Roletype of the player colour. // * // * @example (colour P2) // */ // public Colour(final RoleType roletype) // { // try // { // colour = graphics.settingsColour().playerColour(roletype.owner(), Constants.MAX_PLAYERS); // } // catch (final Exception e) // { // System.out.println("Invalid roletype colour specified: " + roletype.owner()); // colour = Color.BLACK; // } // } //----------------------------------------------------------------------- /** * @return The color. */ public Color colour() { return colour; } //------------------------------------------------------------------------- /** * Converts HSV to RGB. From Foley & Van Dam. * @param hue Hue (0..360). * @param saturation Saturation (0..1). * @param value Value (0..1). * @return Java Color object corresponding to HSV colour. */ public static Color HSVtoColor ( final double hue, final double saturation, final double value ) { double r, g, b; double h = hue; if (saturation == 0.0) { if (h >= 0.0) { //throw new IllegalArgumentException("Bad HSV colour combination."); System.out.println("** Colour.HSVtoColor(): Bad HSV colour combination."); return Color.black; } r = value; g = value; b = value; } else { while (h > 360) h -= 360.0; while (h < 0.0) h += 360.0; h /= 60.0; final int i = (int)h; final double f = h - i; final double p = value * (1.0 - saturation); final double q = value * (1.0 - (saturation * f)); final double t = value * (1.0 - (saturation * (1.0 - f))); switch (i) { case 0: r = value; g = t; b = p; break; case 1: r = q; g = value; b = p; break; case 2: r = p; g = value; b = t; break; case 3: r = p; g = q; b = value; break; case 4: r = t; g = p; b = value; break; case 5: r = value; g = p; b = q; break; default: //throw new IllegalArgumentException("Invalid HSV case, i=" + i + "."); System.out.println("** Colour.HSVtoColor(): Invalid HSV case, i=" + i + "."); return Color.black; } } return new Color ( Math.max(0, Math.min(255, (int)(r * 255 + 0.5))), Math.max(0, Math.min(255, (int)(g * 255 + 0.5))), Math.max(0, Math.min(255, (int)(b * 255 + 0.5))) ); } //------------------------------------------------------------------------- /** * @param code The hex code. * @return The colour from a hex code. */ public static Color interpretHexCode(final String code) { return Color.decode(code); } /** * @param value The integer corresponding to the hex code. * @return The color from a hex code. */ public static Color interpretHexCode(final int value) { return new Color ( ((value >> 16) & 0xff), ((value >> 8) & 0xff), ( value & 0xff) ); } //------------------------------------------------------------------------- @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); return concepts; } @Override public long gameFlags(final Game game) { final long gameFlags = 0l; return gameFlags; } @Override public boolean needRedraw() { return false; } }
5,595
22.611814
94
java
Ludii
Ludii-master/Core/src/metadata/graphics/util/colour/ColourRoutines.java
package metadata.graphics.util.colour; import java.awt.Color; /** * General routine to convert String into a colour. * @author anonymous */ public class ColourRoutines { /** * Used by other metadata function to determine the colour that has been specified * @param value * @return Specified colour. */ public static Color getSpecifiedColour(final String value) { Color colour; if (value == null || value.length() == 0) { return null; } else if (value.substring(0, 1).equals("#")) { try { colour = Color.decode(value); } catch (final Exception e) { colour = new Color(255, 255, 255); } } else if (value.length() > 4 && value.substring(0, 4).equals("RGBA")) { try { colour = new Color( Integer.valueOf(value.split(",")[0].replaceAll("RGBA", "").replaceAll("\\(", "").replaceAll("\\)", "")).intValue(), Integer.valueOf(value.split(",")[1].replaceAll("RGBA", "").replaceAll("\\(", "").replaceAll("\\)", "")).intValue(), Integer.valueOf(value.split(",")[2].replaceAll("RGBA", "").replaceAll("\\(", "").replaceAll("\\)", "")).intValue(), Integer.valueOf(value.split(",")[3].replaceAll("RGBA", "").replaceAll("\\(", "").replaceAll("\\)", "")).intValue()); } catch (final Exception e) { colour = new Color(255, 255, 255); } } else if (value.length() > 3 && value.substring(0, 3).equals("RGB")) { try { colour = new Color( Integer.valueOf(value.split(",")[0].replaceAll("RGB", "").replaceAll("\\(", "").replaceAll("\\)", "")).intValue(), Integer.valueOf(value.split(",")[1].replaceAll("RGB", "").replaceAll("\\(", "").replaceAll("\\)", "")).intValue(), Integer.valueOf(value.split(",")[2].replaceAll("RGB", "").replaceAll("\\(", "").replaceAll("\\)", "")).intValue()); } catch (final Exception e) { colour = new Color(255, 255, 255); } } else { final UserColourType userColour = UserColourType.find(value); colour = (userColour == null) ? new Color(255, 255, 255) : new Color(userColour.r(), userColour.g(), userColour.b()); } return colour; } //----------------------------------------------------------------------------- /** * @param color * @return The contrast colour (black of white) for a given colour, favouring white. */ public static Color getContrastColorFavourLight(final Color color) { if (color == null) return Color.white; final double y = (299 * color.getRed() + 587 * color.getGreen() + 114 * color.getBlue()) / 1000; return y >= 128 ? Color.black : Color.white; } /** * @param color * @return The contrast colour (black of white) for a given colour, favouring black. */ public static Color getContrastColorFavourDark(final Color color) { if (color == null) return Color.black; final double y = color.getRed() + color.getGreen() + color.getBlue() / 3; return y >= 128 ? Color.black : Color.white; } }
3,026
28.38835
123
java
Ludii
Ludii-master/Core/src/metadata/graphics/util/colour/UserColourType.java
package metadata.graphics.util.colour; import java.awt.Color; import java.util.BitSet; import game.Game; import metadata.graphics.GraphicsItem; /** * Specifies the colour of the user. */ public enum UserColourType implements GraphicsItem { //------------------------------------------------------------------------- /** Plain white. */ White("White", 255, 255, 255), /** Plain black. */ Black("Black", 0, 0, 0), /** Medium grey. */ Grey("Grey", 150, 150, 150), /** Light grey. */ LightGrey("Light Grey", 200, 200, 200), /** Very light grey. */ VeryLightGrey("Very Light Grey", 230, 230, 230), /** Dark grey. */ DarkGrey("Dark Grey", 100, 100, 100), /** Very dark grey. */ VeryDarkGrey("Very Dark Grey", 50, 50, 50), /** Almost black. */ Dark("Dark", 30, 30, 30), /** Plain red. */ Red("Red", 255, 0, 0), /** Plain green. */ Green("Green", 0, 200, 0), /** Blue. */ Blue("Blue", 0, 127, 255), /** Yellow. */ Yellow("Yellow", 255, 245, 0), /** Pink. */ Pink("Pink", 255, 0, 255), /** Cyan. */ Cyan("Cyan", 0, 255, 255), /** Medium brown. */ Brown("Brown", 139, 69, 19), /** Dark brown. */ DarkBrown("Dark Brown", 101, 67, 33), /** Very dark brown. */ VeryDarkBrown("Very Dark Brown", 50, 33, 16), /** Purple. */ Purple("Purple", 127, 0, 127), /** Magenta. */ Magenta("Magenta", 255, 0, 255), /** Turquoise. */ Turquoise("Turquoise", 0, 127, 127), /** Orange. */ Orange("Orange", 255, 127, 0), /** Light orange. */ LightOrange("Light Orange", 255, 191, 0), /** Light red. */ LightRed("Light Red", 255, 127, 127), /** Dark red. */ DarkRed("Dark Red", 127, 0, 0), /** Burgundy. */ Burgundy("Burgundy", 63, 0, 0), /** Light green. */ LightGreen("Light Green", 127, 255, 127), /** Dark green. */ DarkGreen("Dark Green", 0, 127, 0), /** Light blue. */ LightBlue("Light Blue", 127, 191, 255), /** Very light blue. */ VeryLightBlue("Very Light Blue", 205, 234, 237), /** Dark blue. */ DarkBlue("Dark Blue", 0, 0, 127), /** Light icy blue. */ IceBlue("Ice Blue", 183, 226, 228), /** Gold. */ Gold("Gold", 212, 175, 55), /** Silver. */ Silver("Silver", 192, 192, 192), /** Bronze. */ Bronze("Bronze", 205, 127, 50), /** Gun metal blue. */ GunMetal("GunMetal", 44, 53, 57), /** Light human skin tone. */ HumanLight("Human Light", 204, 182, 140), /** Dark human skin tone. */ HumanDark("Human Dark", 108, 86, 60), /** Cream. */ Cream("Cream", 255, 255, 230), /** Deep purple. */ DeepPurple("Deep Purple", 127, 0, 127), /** Pink. */ PinkFloyd("Pink Floyd", 255, 75, 150), /** Very dark bluish black. */ BlackSabbath("Black Sabbath", 0, 0, 32), /** King of the crimsons. */ KingCrimson("King Crimson", 220, 20, 60), /** Tangerine. */ TangerineDream("Tangerine Dream", 242, 133, 0), /** Baby Blue. */ BabyBlue("Baby Blue", 127, 191, 255), /** Light tan (as per Tafl boards). */ LightTan("Light Tan", 250, 200, 100), /** Invisible. */ Hidden("Hidden", 0, 0, 0, 0), ; //------------------------------------------------------------------------- private final String label; private final int r; private final int g; private final int b; private final int a; //------------------------------------------------------------------------- UserColourType(final String label, final int r, final int g, final int b) { this.label = label; this.r = r; this.g = g; this.b = b; a = 255; } UserColourType(final String label, final int r, final int g, final int b, final int a) { this.label = label; this.r = r; this.g = g; this.b = b; this.a = a; } //------------------------------------------------------------------------- /** * @return The label of the colour. */ public String label() { return label; } /** * @return The red part of the colour. */ public int r() { return r; } /** * @return The Green part of the colour. */ public int g() { return g; } /** * @return The Blue part of the colour. */ public int b() { return b; } /** * @return The Alpha part of the colour. */ public int a() { return a; } /** * @return the colour */ public Color colour() { return new Color(r, g, b, a); } //------------------------------------------------------------------------- /** * @param key The key of the colour. * @return The UserColourType. */ public static UserColourType find(final String key) { for (final UserColourType uc : values()) if (uc.label.equals(key)) return uc; return null; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); return concepts; } @Override public long gameFlags(final Game game) { final long gameFlags = 0l; return gameFlags; } @Override public boolean needRedraw() { return false; } }
4,943
17.311111
87
java
Ludii
Ludii-master/Core/src/metadata/graphics/util/colour/package-info.java
/** * The ``colour'' metadata items allow the user to specify preferred colours for use in other metadata items. */ package metadata.graphics.util.colour;
157
30.6
109
java
Ludii
Ludii-master/Core/src/metadata/info/Info.java
package metadata.info; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import annotations.Or; import metadata.MetadataItem; import metadata.info.database.Aliases; import metadata.info.database.Author; import metadata.info.database.Classification; import metadata.info.database.Credit; import metadata.info.database.Date; import metadata.info.database.Description; import metadata.info.database.Id; import metadata.info.database.Origin; import metadata.info.database.Publisher; import metadata.info.database.Rules; import metadata.info.database.Source; import metadata.info.database.Version; /** * General information about the game. * * @author Matthew.Stephenson and cambolbro */ public class Info implements MetadataItem, Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- final List<InfoItem> items = new ArrayList<InfoItem>(); //------------------------------------------------------------------------- /** * @param item The info item of the game. * @param items The info items of the game. * * @example (info { (description "Description of The game") (source "Source of * the game") (version "1.0.0") (classification * "board/space/territory") (origin "Origin of the game.") }) */ public Info ( @Or final InfoItem item, @Or final InfoItem[] items ) { int numNonNull = 0; if (item != null) numNonNull++; if (items != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException("Only one of @Or should be different to null"); if(items != null) for (final InfoItem i : items) this.items.add(i); else this.items.add(item); } //------------------------------------------------------------------------- /** * Add an element to the map. * * @param map The map. */ public void addToMap(final Map<String, MetadataItem> map) { for (final InfoItem item : items) map.put(item.getClass().getSimpleName(), item); } //------------------------------------------------------------------------- /** * * @return All the items. */ public List<InfoItem> getItem() { return Collections.unmodifiableList(items); } //------------------------------------------------------------------------- /** * @return The Source of the game's rules. */ public ArrayList<String> getSource() { final ArrayList<String> sources = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Source) sources.add(((Source) infoItem).source()); return sources; } //------------------------------------------------------------------------- /** * @return The ruleset database table Id. */ public ArrayList<String> getId() { final ArrayList<String> ids = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Id) ids.add(((Id) infoItem).id()); return ids; } //------------------------------------------------------------------------- /** * @return The English description of the rules. */ public ArrayList<String> getRules() { final ArrayList<String> rules = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Rules) rules.add(((Rules) infoItem).rules()); return rules; } //------------------------------------------------------------------------- /** * @return The author of the game. */ public ArrayList<String> getAuthor() { final ArrayList<String> authors = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Author) authors.add(((Author) infoItem).author()); return authors; } //------------------------------------------------------------------------- /** * @return The date that the game was created. */ public ArrayList<String> getDate() { final ArrayList<String> dates = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Date) dates.add(((Date) infoItem).date()); return dates; } //------------------------------------------------------------------------- /** * @return The publisher of the game. */ public ArrayList<String> getPublisher() { final ArrayList<String> publishers = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Publisher) publishers.add(((Publisher) infoItem).publisher()); return publishers; } //------------------------------------------------------------------------- /** * @return The credit of the game. */ public ArrayList<String> getCredit() { final ArrayList<String> credits = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Credit) credits.add(((Credit) infoItem).credit()); return credits; } //------------------------------------------------------------------------- /** * @return The English description of the game. */ public ArrayList<String> getDescription() { final ArrayList<String> descriptions = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Description) descriptions.add(((Description) infoItem).description()); return descriptions; } //------------------------------------------------------------------------- /** * @return The Origin of the game. */ public ArrayList<String> getOrigin() { final ArrayList<String> origins = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Origin) origins.add(((Origin) infoItem).origin()); return origins; } //------------------------------------------------------------------------- /** * @return The Classification of the game. */ public ArrayList<String> getClassification() { final ArrayList<String> classifications = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Classification) classifications.add(((Classification) infoItem).classification()); return classifications; } //------------------------------------------------------------------------- /** * @return The Version of the game. */ public ArrayList<String> getVersion() { final ArrayList<String> versions = new ArrayList<>(); for (final InfoItem infoItem : items) if (infoItem instanceof Version) versions.add(((Version) infoItem).version()); return versions; } //------------------------------------------------------------------------- /** * @return The aliases of the game. */ public String[] getAliases() { for (final InfoItem infoItem : items) if (infoItem instanceof Aliases) return ((Aliases) infoItem).aliases(); return new String[0]; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); final String open = (items.size() <= 1) ? "" : "{"; final String close = (items.size() <= 1) ? "" : "}"; sb.append(" (info " + open + "\n"); for (final InfoItem item : items) if (item != null) sb.append(" " + item.toString()); sb.append(" " + close + ")\n"); return sb.toString(); } //------------------------------------------------------------------------- }
7,353
25.078014
85
java
Ludii
Ludii-master/Core/src/metadata/info/InfoItem.java
package metadata.info; import metadata.MetadataItem; //----------------------------------------------------------------------------- /** * Metadata containing some specific type of information about the game (author, date, rules, etc.). * @author Matthew.Stephenson and cambolbro */ public interface InfoItem extends MetadataItem { // Nothing to add, this interface is just for grouping metadata items. }
413
26.6
100
java
Ludii
Ludii-master/Core/src/metadata/info/package-info.java
/** * The {\tt info} metadata items. */ package metadata.info;
65
12.2
33
java
Ludii
Ludii-master/Core/src/metadata/info/database/Aliases.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies a list of additional aliases for the game's name. * * @author Matthew.Stephenson */ public class Aliases implements InfoItem { /** Array of aliases. */ private final String[] aliases; //------------------------------------------------------------------------- /** * @param aliases Set of additional aliases for the name of this game. * * @example (aliases {"Caturanga" "Catur"}) */ public Aliases(final String[] aliases) { this.aliases = aliases; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (aliases \"" + aliases + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return Additional aliases. */ public String[] aliases() { return aliases; } //------------------------------------------------------------------------- }
1,148
19.890909
79
java
Ludii
Ludii-master/Core/src/metadata/info/database/Author.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies the author of the game or ruleset. * * @author Matthew.Stephenson */ public class Author implements InfoItem { /** Game author. */ private final String author; //------------------------------------------------------------------------- /** * @param author The author of the game. * * @example (author "John Doe") */ public Author(final String author) { this.author = author; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (author \"" + author + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return Game author. */ public String author() { return author; } //------------------------------------------------------------------------- }
1,061
18.309091
79
java
Ludii
Ludii-master/Core/src/metadata/info/database/Classification.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies the location of this game within the Ludii classification scheme. * * @author cambolbro * * @remarks The Ludii classification is a combination of the schemes used in * H. J. R. Murray's {\it A History of Board Games other than * Chess} and David Parlett's {\it The Oxford History of Board Games}, * with additional categories to reflect the wider range of games * supported by Ludii. */ public class Classification implements InfoItem { private final String classification; //------------------------------------------------------------------------- /** * @param classification The game's location within the Ludii classification scheme. * * @example (classification "games/board/war/chess") */ public Classification(final String classification) { this.classification = classification; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (classification \"" + classification + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return The classification. */ public String classification() { return classification; } //------------------------------------------------------------------------- }
1,555
25.372881
85
java
Ludii
Ludii-master/Core/src/metadata/info/database/Credit.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies the author of the .lud file and any relevant credit information. * * @author cambolbro * * @remarks The is *not* for the author of the game or ruleset. * The "author" info item should be used for that. */ public class Credit implements InfoItem { /** .lud author, date, publication details, etc. */ private final String credit; //------------------------------------------------------------------------- /** * @param credit The author of the .lud file. * * @example (credit "A. Fool, April Fool Games, 1/4/2020") */ public Credit(final String credit) { this.credit = credit; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (credit \"" + credit + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return .lud author. */ public String credit() { return credit; } //------------------------------------------------------------------------- }
1,272
21.333333
79
java
Ludii
Ludii-master/Core/src/metadata/info/database/Date.java
package metadata.info.database; import metadata.info.InfoItem; /** * Specifies the (approximate) date that the game was created. * * @author Matthew.Stephenson * * @remarks Date is specified in the format (YYYY-MM-DD). */ public class Date implements InfoItem { /** The date the game was created. */ private final String date; //------------------------------------------------------------------------- /** * @param date The date the game was created. * * @example (date "2015-10-05") */ public Date(final String date) { this.date = date; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (date \"" + date + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return The date the game was created */ public String date() { return date; } }
999
17.867925
76
java
Ludii
Ludii-master/Core/src/metadata/info/database/Description.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies a description of the game. * * @author Matthew.Stephenson */ public class Description implements InfoItem { /** English description of the game. */ private final String description; //------------------------------------------------------------------------- /** * @param description An English description of the game. * * @example (description "A traditional game that comes from Egypt.") */ public Description(final String description) { this.description = description; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (description \"" + description + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return English description of the game. */ public String description() { return description; } //------------------------------------------------------------------------- }
1,199
20.818182
79
java
Ludii
Ludii-master/Core/src/metadata/info/database/Id.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies the database Id for the currently chosen ruleset. * * @author Matthew.Stephenson */ public class Id implements InfoItem { /** Ruleset Database Id. */ private final String id; //------------------------------------------------------------------------- /** * @param id The ruleset database table Id. * * @example (id "35") */ public Id(final String id) { this.id = id; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (id \"" + id + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return The ruleset database table Id. */ public String id() { return id; } //------------------------------------------------------------------------- }
1,055
18.2
79
java
Ludii
Ludii-master/Core/src/metadata/info/database/Origin.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies the location of the earliest known origin for this game. * * @author cambolbro */ public class Origin implements InfoItem { private final String origin; //------------------------------------------------------------------------- /** * @param origin Earliest known origin for this game. * * @example (origin "1953") */ public Origin(final String origin) { this.origin = origin; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (origin \"" + origin + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return The origin in a string. */ public String origin() { return origin; } //------------------------------------------------------------------------- }
1,072
19.245283
79
java
Ludii
Ludii-master/Core/src/metadata/info/database/Publisher.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies the publisher of the game. * * @author Matthew.Stephenson */ public class Publisher implements InfoItem { /** Game Publisher. */ private final String publisher; //------------------------------------------------------------------------- /** * @param publisher The publisher of the game. * * @example (publisher "Games Inc.") */ public Publisher(final String publisher) { this.publisher = publisher; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (publisher \"" + publisher + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return Game publisher. */ public String publisher() { return publisher; } //------------------------------------------------------------------------- }
1,101
19.036364
79
java
Ludii
Ludii-master/Core/src/metadata/info/database/Rules.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies an English description of the rules of a game. * * @author Matthew.Stephenson and cambolbro */ public class Rules implements InfoItem { private final String rules; //------------------------------------------------------------------------- /** * @param rules An English description of the game's rules. * * @example (rules "Try to make a line of four.") */ public Rules(final String rules) { this.rules = rules; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (rules \"" + rules + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return English description of the rules. */ public String rules() { return rules; } //------------------------------------------------------------------------- }
1,113
20.018868
79
java
Ludii
Ludii-master/Core/src/metadata/info/database/Source.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies the reference for the game, or its currently chosen ruleset. * * @author Matthew.Stephenson */ public class Source implements InfoItem { /** Rules source. */ private final String source; //------------------------------------------------------------------------- /** * @param source The source of the game's rules. * * @example (source "Murray 1969") */ public Source(final String source) { this.source = source; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (source \"" + source + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return The source of the game's rules. */ public String source() { return source; } //------------------------------------------------------------------------- }
1,118
19.345455
79
java
Ludii
Ludii-master/Core/src/metadata/info/database/Version.java
package metadata.info.database; import metadata.info.InfoItem; //----------------------------------------------------------------------------- /** * Specifies the latest Ludii version that this .lud is known to work for. * * @author cambolbro * * @remarks The version format is (Major version).(Minor version).(Build number). * For example, the first major version for public release is "1.0.0". */ public class Version implements InfoItem { private final String version; //------------------------------------------------------------------------- /** * @param version Ludii version in String form. * * @example (version "1.0.0") */ public Version(final String version) { this.version = version; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(" (version \"" + version + "\")\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return The version. */ public String version() { return version; } //------------------------------------------------------------------------- }
1,238
21.125
81
java
Ludii
Ludii-master/Core/src/metadata/info/database/package-info.java
/** * The ``database'' metadata items describe information about the game, which is automatically * synchronised from the Ludii game database at \\url{https://ludii.games/library.php}. * All of the types listed in this section may be used for \\texttt{<infoItem>} parameters * in metadata. */ package metadata.info.database;
331
40.5
95
java
Ludii
Ludii-master/Core/src/metadata/recon/Recon.java
package metadata.recon; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import annotations.Or; import metadata.MetadataItem; /** * Reconstruction metadata. * * @author Matthew.Stephenson and Eric.Piette */ public class Recon implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- final List<ReconItem> items = new ArrayList<ReconItem>(); //------------------------------------------------------------------------- /** * @param item The info item of the game. * @param items The info items of the game. * * @example (recon {(concept "Num Players" 3)}) */ public Recon ( @Or final ReconItem item, @Or final ReconItem[] items ) { int numNonNull = 0; if (item != null) numNonNull++; if (items != null) numNonNull++; if (numNonNull > 1) throw new IllegalArgumentException("Only one of @Or should be different to null"); if(items != null) for (final ReconItem i : items) this.items.add(i); else this.items.add(item); } //------------------------------------------------------------------------- /** * Add an element to the map. * * @param map The map. */ public void addToMap(final Map<String, MetadataItem> map) { for (final ReconItem item : items) map.put(item.getClass().getSimpleName(), item); } //------------------------------------------------------------------------- /** * * @return All the items. */ public List<ReconItem> getItem() { return Collections.unmodifiableList(items); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); final String open = (items.size() <= 1) ? "" : "{"; final String close = (items.size() <= 1) ? "" : "}"; sb.append(" (info " + open + "\n"); for (final ReconItem item : items) if (item != null) sb.append(" " + item.toString()); sb.append(" " + close + ")\n"); return sb.toString(); } //------------------------------------------------------------------------- }
2,248
21.267327
85
java
Ludii
Ludii-master/Core/src/metadata/recon/ReconItem.java
package metadata.recon; import metadata.MetadataItem; //----------------------------------------------------------------------------- /** * Metadata containing some specific reconstruction requirements. * @author Matthew.Stephenson and Eric.Piette */ public interface ReconItem extends MetadataItem { // Nothing to add, this interface is just for grouping metadata items. }
381
24.466667
79
java
Ludii
Ludii-master/Core/src/metadata/recon/package-info.java
/** * The {\tt info} metadata items. */ package metadata.recon;
66
12.4
33
java
Ludii
Ludii-master/Core/src/metadata/recon/concept/Concept.java
package metadata.recon.concept; import annotations.Name; import annotations.Or; import metadata.recon.ReconItem; //----------------------------------------------------------------------------- /** * Specifies the what concept values are required. * * @author Matthew.Stephenson and Eric.Piette */ public class Concept implements ReconItem { /** Concept name. */ private final String conceptName; /** Concept name. */ private other.concept.Concept concept; /** Concept minimal value. */ private double minValue; /** Concept maximal value. */ private double maxValue; //------------------------------------------------------------------------- /** * For defining an expected concept with a specific value. * * @param conceptName The name of the concept. * @param valueDouble The double value. * @param valueBoolean The boolean value. * * @example (concept "Num Players" 6) */ public Concept ( final String conceptName, @Or final Float valueDouble, @Or final Boolean valueBoolean ) { this.conceptName = conceptName; try{this.concept = other.concept.Concept.valueOf(conceptName);} catch(final Exception e) { this.concept = null; } minValue = ((valueDouble != null) ? valueDouble.doubleValue() : (valueBoolean.booleanValue() ? 1d : 0d) ); maxValue = minValue; } /** * For defining an expected concept within a range. * * @param conceptName The name of the concept. * @param minValue The minimum value. * @param maxValue The maximum value. * * @example (concept "Num Players" minValue:2 maxValue:4) */ public Concept ( final String conceptName, @Name final Float minValue, @Name final Float maxValue ) { this.conceptName = conceptName; try{this.concept = other.concept.Concept.valueOf(conceptName);} catch(final Exception e) { this.concept = null; } this.minValue = minValue.doubleValue(); this.maxValue = maxValue.doubleValue(); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); if(minValue == maxValue) sb.append(conceptName + " value = " + minValue + "\n"); else sb.append(conceptName + " min value = " + minValue + " " + " max value = " + maxValue +"\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * @return The name of the concept */ public String conceptName() { return conceptName; } //------------------------------------------------------------------------- /** * @return The name of the concept */ public other.concept.Concept concept() { return concept; } /** * @return The minimum value of the concept */ public double minValue() { return minValue; } /** * @return The maximum value of the concept */ public double maxValue() { return maxValue; } //------------------------------------------------------------------------- }
3,001
21.237037
108
java
Ludii
Ludii-master/Core/src/metadata/recon/concept/package-info.java
/** * The ``database'' metadata items describe information about the game, which is automatically * synchronised from the Ludii game database at \\url{https://ludii.games/library.php}. * All of the types listed in this section may be used for \\texttt{<infoItem>} parameters * in metadata. */ package metadata.recon.concept;
331
40.5
95
java
Ludii
Ludii-master/Core/src/other/AI.java
package other; import java.lang.ref.WeakReference; import game.Game; import main.collections.FVector; import main.collections.FastArrayList; import metadata.ai.heuristics.Heuristics; import other.context.Context; import other.move.Move; /** * Base abstract class for AI agents. * * @author Dennis Soemers and cambolbro */ @SuppressWarnings("static-method") public abstract class AI { //------------------------------------------------------------------------- /** A heuristic function */ protected Heuristics heuristicFunction = null; /** Easily-readable, human-friendly name for AI */ protected String friendlyName = "Unnamed"; /** Set to true if the Ludii app would like this AI to interrupt any thinking */ protected volatile boolean wantsInterrupt = false; /** Weak reference to the last game we've initialised the AI for */ private WeakReference<Game> lastInitGame = new WeakReference<>(null); /** How often was start() called on the game object the last time we initialised AI for it? */ private int lastInitGameStartCount = -1; /** Does our AI want to cheat with perfect knowledge of all RNG events? */ protected boolean wantsCheatRNG = false; /** Functor we can use to create copies of contexts */ protected ContextCopyInterface contextCopyer = STANDARD_CONTEXT_COPY; /** * Thinking time limit per move for this AI. Only used if no limit is * otherwise explicitly defined. By default 1 second, but can be modified. * Values below 0 mean no limit. */ protected double maxSecondsPerMove = 1.0; /** * Iteration count limit per move for this AI. Only used if no limit is * otherwise explicitly defined. Values below 0 mean no limit. Default -1 * (= no limit). The meaning of an "iteration" can be different for different * algorithms, and some may not even have a notion of iterations (which means * that they can just ignore this) */ protected int maxIterationsPerMove = -1; /** * Search depth limit per move for this AI. Only used if no limit is * otherwise explicitly defined. Values below 0 mean no limit. Default -1 * (= no limit). The meaning of "search depth" can be different for different * algorithms, and some may just ignore this */ protected int maxSearchDepthPerMove = -1; /** * Leniency factor in range 0..1: 0 = no effect, 1 = 100% leniency. * Used to make the AI more lenient (i.e. more likely to play suboptimal * moves) to dynamically adjust its playing strength. */ protected double leniency = 0; //------------------------------------------------------------------------- // Getters and setters /** * @return Leniency factor in range 0..1: 0 = no effect, 1 = 100% leniency. */ public double leniency() { return leniency; } /** * @param amount Leniency amount in range 0..1. */ public void setLeniency(final double amount) { leniency = amount; } /** * @return Thinking time limit per move for this AI. Only used if no limit is * otherwise explicitly defined. By default 1 second, but can be modified. * Values below 0 mean no limit. */ public double maxSecondsPerMove() { return maxSecondsPerMove; } /** * Sets this AI's default time limit per move in seconds (use negative for no limit) * @param newLimit */ public void setMaxSecondsPerMove(final double newLimit) { maxSecondsPerMove = newLimit; } /** * @return Iteration count limit per move for this AI. Only used if no limit is * otherwise explicitly defined. Values below 0 mean no limit. Default -1 * (= no limit). The meaning of an "iteration" can be different for different * algorithms, and some may not even have a notion of iterations (which means * that they can just ignore this) */ protected int maxIterationsPerMove() { return maxIterationsPerMove; } /** * Sets this AI's default iteration limit per move in seconds (use negative for no limit) * @param newLimit */ public void setMaxIterationsPerMove(final int newLimit) { maxIterationsPerMove = newLimit; } /** * @return Search depth limit per move for this AI. Only used if no limit is * otherwise explicitly defined. Values below 0 mean no limit. Default -1 * (= no limit). The meaning of "search depth" can be different for different * algorithms, and some may just ignore this */ protected int maxSearchDepthPerMove() { return maxSearchDepthPerMove; } /** * Sets this AI's default search depth limit per move in seconds (use negative for no limit) * @param newLimit */ public void setMaxSearchDepthPerMove(final int newLimit) { maxSearchDepthPerMove = newLimit; } /** * @return The friendly name. */ public String friendlyName() { return friendlyName; } /** * Set the friendly name. * @param fname The friendly name. */ public void setFriendlyName(final String fname) { friendlyName = new String(fname); } /** * Sets heuristics to be used by MCTS (for instance to mix with backpropagation result). * @param heuristics */ public void setHeuristics(final Heuristics heuristics) { heuristicFunction = heuristics; } //------------------------------------------------------------------------- /** * Should be implemented to select and return an action to play. * * @param game Reference to the game we're playing. * @param context Copy of the context containing the current state of the game * @param maxSeconds Max number of seconds before a move should be selected. * Values less than 0 mean there is no time limit. * @param maxIterations Max number of iterations before a move should be selected. * Values less than 0 mean there is no iteration limit. * @param maxDepth Max search depth before a move should be selected. * Values less than 0 mean there is no search depth limit. * @return Preferred move. */ public abstract Move selectAction ( final Game game, final Context context, final double maxSeconds, final int maxIterations, final int maxDepth ); /** * Requests the AI object to select a move, using the AI object's own internal limits for * search time, iterations, and/or search depth. * * @param game * @param context * @return Preferred move. */ public Move selectAction(final Game game, final Context context) { return selectAction(game, context, maxSecondsPerMove, maxIterationsPerMove, maxSearchDepthPerMove); } /** * Helper method to create copies of contexts. Changes behaviour depending * on whether or not the AI wants to be able to cheat with perfect knowledge * of RNG events. * * @param other * @return Copy of Context */ public final Context copyContext(final Context other) // IMPORTANT for this to be final, prevents more cheating :P { return contextCopyer.copy(other); } /** * @return Human-friendly name for this AI. */ public String name() { return friendlyName; } /** * Allows an agent to perform any desired initialisation before starting * to play a game. * * @param game The game that we'll be playing * @param playerID The player ID (or index) for the AI in this game */ public void initAI(final Game game, final int playerID) { // Do nothing by default } /** * Ludii may call this when it's fairly likely that this AI will no longer * have to continue playing the game it was currently playing. This can then * be used to free up any resources / memory if desired. * * Ludii will generally call this on an AI right before switching over to * a new type of AI, and also when restarting a game in the app or loading * a new game. Note that it's not 100% guaranteed to always be called in * between subsequent initAI() calls. */ public void closeAI() { // Do nothing by default } /** * Allows an agent to tell Ludii whether or not it can support playing * any given game. AIs which do not override this method will, by default, * tell Ludii that they support any game. * @param game * @return False if the AI cannot play the given game. */ public boolean supportsGame(final Game game) { return true; } /** * Can be overridden by AIs to return a general value estimate in [-1, 1]. * Used only for visualisation purposes (e.g. smiley faces) * * @return Value estimate in [-1, 1] */ public double estimateValue() { return 0.0; } /** * Can be overridden by AIs to return a string to print in the Analysis tab * of Ludii after making a move. * * Default implementation always returns null, which causes nothing to be printed. * * @return String to print after making move, or null for no print. */ public String generateAnalysisReport() { return null; } /** * Can be overridden by AIs to return data for visualisation of its * thinking process. * * @return Data for visualisations, null for no visualisations */ public AIVisualisationData aiVisualisationData() { return null; } //------------------------------------------------------------------------- /** * Sets whether the Ludii app wants this AI to interrupt any thinking * @param val */ public void setWantsInterrupt(final boolean val) { wantsInterrupt = val; } /** * Sets whether this AI wants to cheat with perfect knowledge of all RNG events * @param wantsCheat */ public void setWantsCheatRNG(final boolean wantsCheat) { wantsCheatRNG = wantsCheat; if (wantsCheatRNG) contextCopyer = RNG_CHEAT_COPY; else contextCopyer = STANDARD_CONTEXT_COPY; } /** * @return Does this AI want to cheat with perfect knowledge of all RNG events? */ public boolean wantsCheatRNG() { return wantsCheatRNG; } /** * @param game * @return Does this AI use spatial state-action features? */ public boolean usesFeatures(final Game game) { return false; } //------------------------------------------------------------------------- /** * Calls initAI() only if it is needed (if the AI wasn't previously initialised * for the same game + trial). * @param game * @param playerID */ public final void initIfNeeded(final Game game, final int playerID) { if ( lastInitGame.get() != null && lastInitGame.get() == game && lastInitGame.get().gameStartCount() == lastInitGameStartCount ) { // we do not need to init AI return; } initAI(game, playerID); lastInitGame = new WeakReference<>(game); lastInitGameStartCount = game.gameStartCount(); } //------------------------------------------------------------------------- /** * Wrapper for data that AIs can return if they want to facilitate visualisations * of their "thinking processes" in the Ludii app. * * @author Dennis Soemers */ public static class AIVisualisationData { /** * Vector containing measures of "search effort" per move. */ private final FVector searchEffort; /** * Vector containing value estimates per move (all expected * to lie in [-1, 1]). */ private final FVector valueEstimates; /** * List of moves for which we wish to draw visualisations, in * the order that matches the search effort and value estimate vectors. */ private final FastArrayList<Move> moves; /** * Constructor * * @param searchEffort * @param valueEstimates * @param moves */ public AIVisualisationData ( final FVector searchEffort, final FVector valueEstimates, final FastArrayList<Move> moves ) { this.searchEffort = searchEffort; this.valueEstimates = valueEstimates; this.moves = moves; } /** * @return Vector of "search effort" values */ public FVector searchEffort() { return searchEffort; } /** * @return Vector of value estimates for moves */ public FVector valueEstimates() { return valueEstimates; } /** * @return List of moves. */ public FastArrayList<Move> moves() { return moves; } } //------------------------------------------------------------------------- /** * Interface for a functor that can create copies of Context objects * * @author Dennis Soemers */ public interface ContextCopyInterface { /** * @param context * @return A copy of the given context */ public Context copy(final Context context); } /** Functor that creates normal copies of context for normal use */ public static final ContextCopyInterface STANDARD_CONTEXT_COPY = (final Context context) -> { return new Context(context); }; /** Functor that creates copies of contexts including seed copying, for RNG cheats */ public static final ContextCopyInterface RNG_CHEAT_COPY = (final Context context) -> { return Context.copyWithSeed(context); }; //------------------------------------------------------------------------- }
12,803
25.786611
128
java
Ludii
Ludii-master/Core/src/other/BaseCardImages.java
package other; //----------------------------------------------------------------------------- /** * Class for loading base card images ONCE per deck. * @author cambolbro */ public class BaseCardImages { //------------------------------------------------------------------------- // Playing card constants /** * A large suit. */ public static final int SUIT_LARGE = 0; /** * A small suit. */ public static final int SUIT_SMALL = 1; /** * A royal black card. */ public static final int BLACK_ROYAL = 2; /** * A red royal card. */ public static final int RED_ROYAL = 3; /** * Clubs suit. */ public static final int CLUBS = 1; /** * Spades suit. */ public static final int SPADES = 2; /** * Diamonds suit. */ public static final int DIAMONDS = 3; /** * Hearts suit. */ public static final int HEARTS = 4; /** * Joker card. */ public static final int JOKER = 0; /** * Ace card. */ public static final int ACE = 1; /** * Jack card. */ public static final int JACK = 11; /** * Queen card. */ public static final int QUEEN = 12; /** * King card. */ public static final int KING = 13; // Playing card images private String[][] baseCardImagePaths = null; private int cardSize; //------------------------------------------------------------------------- /** * @return The small size of the suit. */ public int getSuitSizeSmall() { return getSuitSizeSmall(cardSize); } /** * @param cardSizeInput The size of the card in input. * @return The small size of the suit. */ @SuppressWarnings("static-method") public int getSuitSizeSmall(final int cardSizeInput) { return (int)(0.100 * cardSizeInput); } /** * @return The big size of the suit. */ public int getSuitSizeBig() { return getSuitSizeBig(cardSize); } /** * @param cardSizeInput The size of the card in input. * @return The big size of the suit. */ @SuppressWarnings("static-method") public int getSuitSizeBig(final int cardSizeInput) { return (int)(0.160 * cardSizeInput); } //------------------------------------------------------------------------- /** * @param type The type of the card. * @param which The which of the card. * * @return The path to get the card file. */ public String getPath(final int type, final int which) { if (baseCardImagePaths == null || type >= baseCardImagePaths.length || which >= baseCardImagePaths[type].length) { System.out.println("** Failed to find base card image type " + type + " value " + which + "."); return null; } return baseCardImagePaths[type][which]; } //------------------------------------------------------------------------- /** * Clear. */ public void clear() { baseCardImagePaths = null; } /** * @return True if they are load. */ public boolean areLoaded() { return baseCardImagePaths != null; } //------------------------------------------------------------------------- /** * Load the images. * * @param cardSizeInput The card size in input. */ public void loadImages(final int cardSizeInput) { baseCardImagePaths = new String[4][15]; // Load the four suit images cardSize = cardSizeInput; // Load the relevant large suit image from file baseCardImagePaths[SUIT_LARGE][CLUBS] = "/svg/cards/card-suit-club.svg"; baseCardImagePaths[SUIT_LARGE][SPADES] = "/svg/cards/card-suit-spade.svg"; baseCardImagePaths[SUIT_LARGE][DIAMONDS] = "/svg/cards/card-suit-diamond.svg"; baseCardImagePaths[SUIT_LARGE][HEARTS] = "/svg/cards/card-suit-heart.svg"; baseCardImagePaths[SUIT_SMALL][CLUBS] = "/svg/cards/card-suit-club.svg"; baseCardImagePaths[SUIT_SMALL][SPADES] = "/svg/cards/card-suit-spade.svg"; baseCardImagePaths[SUIT_SMALL][DIAMONDS] = "/svg/cards/card-suit-diamond.svg"; baseCardImagePaths[SUIT_SMALL][HEARTS] = "/svg/cards/card-suit-heart.svg"; // Load the royal card figures baseCardImagePaths[BLACK_ROYAL][JACK] = "/svg/cards/card-jack.svg"; baseCardImagePaths[BLACK_ROYAL][QUEEN] = "/svg/cards/card-queen.svg"; baseCardImagePaths[BLACK_ROYAL][KING] = "/svg/cards/card-king.svg"; baseCardImagePaths[RED_ROYAL][JACK] = "/svg/cards/card-jack.svg"; baseCardImagePaths[RED_ROYAL][QUEEN] = "/svg/cards/card-queen.svg"; baseCardImagePaths[RED_ROYAL][KING] = "/svg/cards/card-king.svg"; } //------------------------------------------------------------------------- }
4,462
22.244792
114
java
Ludii
Ludii-master/Core/src/other/BaseLudeme.java
package other; import java.util.BitSet; import game.Game; /** * BaseLudeme abstract class for all ludemes. * * @author cambolbro and Eric.Piette */ public abstract class BaseLudeme implements Ludeme { /** * Default behaviour: English description not known for this ludeme. * General toEnglish principles: * - Every Ludeme should convert to an English description irrespective of its parent. * - Parents are responsible for adding spaces either side of their children. */ @Override public String toEnglish(final Game game) { return "<" + this.getClass().getName() + ">"; } @Override public BitSet concepts(final Game game) { return new BitSet(); } @Override public BitSet readsEvalContextRecursive() { return new BitSet(); } @Override public BitSet writesEvalContextRecursive() { return new BitSet(); } @Override public BitSet readsEvalContextFlat() { return new BitSet(); } @Override public BitSet writesEvalContextFlat() { return new BitSet(); } @Override public boolean missingRequirement(final Game game) { return false; } @Override public boolean willCrash(final Game game) { return false; } }
1,173
16.264706
87
java
Ludii
Ludii-master/Core/src/other/BaseLudemeWithGraphElement.java
package other; import game.Game; import game.types.board.SiteType; /** * Base ludeme class for ludemes with a GraphElementType. * * @author cambolbro */ public class BaseLudemeWithGraphElement extends BaseLudeme { private SiteType type = null; //------------------------------------------------------------------------- /** * @return The type of the element. */ public SiteType graphElementType() { return type; } //------------------------------------------------------------------------- /** * Set the graph element type. * * @param preferred The preferred graph type. * @param game The game. */ public void setGraphElementType(final SiteType preferred, final Game game) { if (preferred == null) type = game.board().defaultSite(); else type = preferred; } @Override public String toEnglish(final Game game) { return type.name(); } }
902
18.212766
76
java
Ludii
Ludii-master/Core/src/other/ContainerId.java
package other; import java.io.Serializable; import game.equipment.container.Container; import game.equipment.container.other.Hand; 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; //----------------------------------------------------------------------------- /** * Get index of a container from its index, name with or without (role type and * playerId) or with a site in a container. * * @author cambolbro and Eric Piette */ public final class ContainerId implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- protected final IntFunction index; protected final String name; protected final RoleType role; protected final IntFunction playerId; protected final IntFunction site; //------------------------------------------------------------------------- /** * Constructor. * * @param index The index of the container. * @param name The name of the container. * @param role The roleType of the owner of the container. * @param playerId The index of the owner of the container. * @param site The site. */ public ContainerId ( final IntFunction index, final String name, final RoleType role, final IntFunction playerId, final IntFunction site ) { if (index == null && name == null && role == null && playerId == null && site == null) { this.index = new IntConstant(0); this.name = null; this.role = null; this.playerId = null; this.site = null; } else if (index != null && name == null && role == null && playerId == null && site == null) { this.index = index; this.name = null; this.role = null; this.playerId = null; this.site = null; } else if (index == null && name != null && role == null && playerId == null && site == null) { this.index = null; this.name = name; this.role = null; this.playerId = null; this.site = null; } else if (index == null && name != null && role != null && playerId == null && site == null) { this.index = null; this.name = name; this.role = role; this.playerId = null; this.site = null; } else if (index == null && name != null && role == null && playerId != null && site == null) { this.index = null; this.name = name; this.role = null; this.playerId = playerId; this.site = null; } else if (index == null && name == null && role == null && playerId == null && site != null) { this.index = null; this.name = null; this.role = null; this.playerId = null; this.site = site; } else { throw new IllegalArgumentException("Unexpected parameter combination."); } } //------------------------------------------------------------------------- /** * @param context The context. * * @return The corresponding index of the container. */ public int eval(final Context context) { if (index != null) return index.eval(context); if (site != null) { final int indexSite = site.eval(context); if(indexSite == Constants.UNDEFINED) return 0; return context.containerId()[indexSite]; } if (role == null && playerId == null) return context.game().mapContainer().get(name).index(); final int pid = (role != null) ? new Id(null, role).eval(context) : playerId.eval(context); for (int cid = 0; cid < context.containers().length; cid++) { final Container container = context.containers()[cid]; if ( container.isHand() && container.name().contains(name) && ((Hand)container).owner() == pid ) return cid; } throw new RuntimeException("Could not find specified container."); } //------------------------------------------------------------------------- }
3,983
25.039216
93
java
Ludii
Ludii-master/Core/src/other/GameLoader.java
package other; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import compiler.Compiler; import game.Game; import game.match.Subgame; import main.FileHandling; import main.grammar.Description; import main.grammar.Report; import main.options.GameOptions; import main.options.Option; import main.options.Ruleset; import main.options.UserSelections; //----------------------------------------------------------------------------- /** * Utility class for game-loading. * @author Dennis Soemers and cambolbro */ public final class GameLoader { //------------------------------------------------------------------------- /** * Load game from name. * @param name Filename + .lud extension. * @return Loads game for the given name */ public static Game loadGameFromName(final String name) { return loadGameFromName(name, new ArrayList<String>()); } //------------------------------------------------------------------------- /** * Load game from name. * @param name Filename + .lud extension. * @param rulesetName Name of the ruleset to load. * @return Loads game for the given name */ public static Game loadGameFromName(final String name, final String rulesetName) { if (rulesetName.length() == 0) return loadGameFromName(name); final Game tempGame = GameLoader.loadGameFromName(name); final List<Ruleset> rulesets = tempGame.description().rulesets(); if (rulesets != null && !rulesets.isEmpty()) { for (int rs = 0; rs < rulesets.size(); rs++) if (rulesets.get(rs).heading().equals(rulesetName)) return loadGameFromName(name, rulesets.get(rs).optionSettings()); } System.err.println("ERROR: Ruleset name not found, loading default game options"); System.err.println("Game name = " + name); System.err.println("Ruleset name = " + rulesetName); return loadGameFromName(name); } //------------------------------------------------------------------------- /** * Load game from name. * @param name Filename + .lud extension. * @param options List of options to select * @return Loads game for the given name */ @SuppressWarnings("resource") public static Game loadGameFromName ( final String name, final List<String> options ) { InputStream in = GameLoader.class.getResourceAsStream(name.startsWith("/lud/") ? name : "/lud/" + name); // System.out.println("Loading game from name, options are: " + options); if (in == null) { // exact match with full filepath under /lud/ not found; let's try // to see if we can figure out which game the user intended final String[] allGameNames = FileHandling.listGames(); int shortestNonMatchLength = Integer.MAX_VALUE; String bestMatchFilepath = null; final String givenName = name.toLowerCase().replaceAll(Pattern.quote("\\"), "/"); for (final String gameName : allGameNames) { final String str = gameName.toLowerCase().replaceAll(Pattern.quote("\\"), "/"); if (str.endsWith(givenName)) { final int nonMatchLength = str.length() - givenName.length(); final String[] strSplit = str.split(Pattern.quote("/")); if (strSplit[strSplit.length - 1].equals(givenName)) { // This is an exact match bestMatchFilepath = "..\\Common\\res\\" + gameName; break; } else if (nonMatchLength < shortestNonMatchLength) { shortestNonMatchLength = nonMatchLength; bestMatchFilepath = "..\\Common\\res\\" + gameName; } } } String resourceStr = bestMatchFilepath.replaceAll(Pattern.quote("\\"), "/"); resourceStr = resourceStr.substring(resourceStr.indexOf("/lud/")); in = GameLoader.class.getResourceAsStream(resourceStr); } final StringBuilder sb = new StringBuilder(); try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in))) { String line; while ((line = rdr.readLine()) != null) sb.append(line + "\n"); } catch (final IOException e) { e.printStackTrace(); } final Game game = (Game)Compiler.compile ( new Description(sb.toString()), new UserSelections(options), new Report(), false ); if (game.hasSubgames()) { // Also need to compile instances for (final Subgame instance : game.instances()) { final ArrayList<String> option = new ArrayList<String>(); if (instance.optionName() != null) option.add(instance.optionName()); instance.setGame(GameLoader.loadGameFromName(instance.gameName() + ".lud", option)); } } //try { in.close(); } //catch (final IOException e) { e.printStackTrace(); } return game; } /** * @param file .lud file to load game from * @return Game loaded from file */ public static Game loadGameFromFile(final File file) { return loadGameFromFile(file, new ArrayList<String>()); } /** * @param file .lud file to load game from * @param options List of options to select * @return Game loaded from file */ public static Game loadGameFromFile ( final File file, final List<String> options ) { // System.out.println("Loading game from file, options are: " + options); // Get game description from resource final StringBuilder sb = new StringBuilder(); if (file != null) { try ( final BufferedReader rdr = new BufferedReader( new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) ) { String line; while ((line = rdr.readLine()) != null) sb.append(line + "\n"); } catch (final IOException e) { e.printStackTrace(); return null; } } final Game game = (Game)Compiler.compile ( new Description(sb.toString()), new UserSelections(options), new Report(), false ); if (game.hasSubgames()) { // Also need to compile instances for (final Subgame instance : game.instances()) { final ArrayList<String> option = new ArrayList<String>(); if (instance.optionName() != null) option.add(instance.optionName()); instance.setGame(GameLoader.loadGameFromName(instance.gameName() + ".lud", option)); } } return game; } //------------------------------------------------------------------------- /** * @param optionStrings * @param gameOptions * @return int array representation of selected options */ public static int[] convertStringsToOptions ( final List<String> optionStrings, final GameOptions gameOptions ) { final int[] optionSelections = new int[GameOptions.MAX_OPTION_CATEGORIES]; for (final String optionStr : optionStrings) { final String[] headings = optionStr.split(Pattern.quote("/")); boolean foundMatch = false; for (int cat = 0; cat < gameOptions.numCategories(); cat++) { final List<Option> optionsList = gameOptions.categories().get(cat).options(); for (int i = 0; i < optionsList.size(); ++i) { final Option option = optionsList.get(i); final List<String> optionHeadings = option.menuHeadings(); if (optionHeadings.size() != headings.length) continue; boolean allMatch = true; for (int j = 0; j < headings.length; ++j) { if (!headings[j].equalsIgnoreCase(optionHeadings.get(j))) { allMatch = false; break; } } if (allMatch) { foundMatch = true; optionSelections[cat] = i; break; } } if (foundMatch) break; } if (!foundMatch) System.err.println("Warning! GameLoader::convertStringToOptions() could not resolve option: " + optionStr); } return optionSelections; } //------------------------------------------------------------------------- /** * Returns the complete file path for a given lud name. * @param name The name of the game. * @return The file path. */ public static String getFilePath(final String name) { String inName = name.replaceAll(Pattern.quote("\\"), "/"); if (!inName.endsWith(".lud")) inName += ".lud"; if (inName.startsWith("../Common/res")) inName = inName.substring("../Common/res".length()); if (!inName.startsWith("/lud/")) inName = "/lud/" + inName; try (InputStream in = GameLoader.class.getResourceAsStream(inName)) { if (in == null) { // exact match with full filepath under /lud/ not found; let's try // to see if we can figure out which game the user intended final String[] allGameNames = FileHandling.listGames(); int shortestNonMatchLength = Integer.MAX_VALUE; String bestMatchFilepath = null; String givenName = inName.toLowerCase().replaceAll(Pattern.quote("\\"), "/"); if (givenName.startsWith("/lud/")) givenName = givenName.substring("/lud/".length()); else if (givenName.startsWith("lud/")) givenName = givenName.substring("lud/".length()); for (final String gameName : allGameNames) { final String str = gameName.toLowerCase().replaceAll(Pattern.quote("\\"), "/"); if (str.endsWith("/" + givenName)) { final int nonMatchLength = str.length() - givenName.length(); if (nonMatchLength < shortestNonMatchLength) { shortestNonMatchLength = nonMatchLength; bestMatchFilepath = "..\\Common\\res\\" + gameName; } } } if (bestMatchFilepath == null) { for (final String gameName : allGameNames) { final String str = gameName.toLowerCase().replaceAll(Pattern.quote("\\"), "/"); if (str.endsWith(givenName)) { final int nonMatchLength = str.length() - givenName.length(); if (nonMatchLength < shortestNonMatchLength) { shortestNonMatchLength = nonMatchLength; bestMatchFilepath = "..\\Common\\res\\" + gameName; } } } } if (bestMatchFilepath == null) { final String[] givenSplit = givenName.split(Pattern.quote("/")); if (givenSplit.length > 1) { final String givenEnd = givenSplit[givenSplit.length - 1]; for (final String gameName : allGameNames) { final String str = gameName.toLowerCase().replaceAll(Pattern.quote("\\"), "/"); if (str.endsWith(givenEnd)) { final int nonMatchLength = str.length() - givenName.length(); if (nonMatchLength < shortestNonMatchLength) { shortestNonMatchLength = nonMatchLength; bestMatchFilepath = "..\\Common\\res\\" + gameName; } } } } } // Probably loading an external .lud from filepath. if (bestMatchFilepath == null) return null; String resourceStr = bestMatchFilepath.replaceAll(Pattern.quote("\\"), "/"); resourceStr = resourceStr.substring(resourceStr.indexOf("/lud/")); return resourceStr; } return inName; } catch (final Exception e) { System.out.println("Did you change the name??"); } return null; } //------------------------------------------------------------------------- /** * To compile the game of an instance of a match. * * @param instance */ public static void compileInstance(final Subgame instance) { final ArrayList<String> option = new ArrayList<String>(); if (instance.optionName() != null) option.add(instance.optionName()); instance.setGame(GameLoader.loadGameFromName(instance.gameName() + ".lud", option)); if (instance.optionName() != null) { final GameOptions instanceObjectOptions = new GameOptions(); final Option optionInstance = new Option(); final List<String> headings = new ArrayList<String>(); headings.add(instance.optionName()); optionInstance.setHeadings(headings); @SuppressWarnings("unchecked") final List<Option>[] optionsAvailable = new ArrayList[1]; final ArrayList<Option> optionList = new ArrayList<Option>(); optionList.add(optionInstance); optionsAvailable[0] = optionList; instanceObjectOptions.setOptionCategories(optionsAvailable); } } //------------------------------------------------------------------------- /** * @return All the analysis. */ public static List<String[]> allAnalysisGameRulesetNames() { final List<String[]> allGameRulesetNames = new ArrayList<>(); final String[] choices = FileHandling.listGames(); for (final String s : choices) { // Temporary restriction to check smaller set of games // if (!s.contains("/chess/")) // continue; if (!FileHandling.shouldIgnoreLudAnalysis(s)) { final Game tempGame = GameLoader.loadGameFromName(s); final List<Ruleset> rulesets = tempGame.description().rulesets(); if (rulesets != null && !rulesets.isEmpty()) { for (int rs = 0; rs < rulesets.size(); rs++) if (!rulesets.get(rs).optionSettings().isEmpty()) allGameRulesetNames.add(new String[] {s, rulesets.get(rs).heading()}); } else { allGameRulesetNames.add(new String[] {s, ""}); } } } return allGameRulesetNames; } //------------------------------------------------------------------------- }
13,332
27.010504
111
java
Ludii
Ludii-master/Core/src/other/GraphUtilities.java
package other; import annotations.Hide; import game.types.board.SiteType; import other.topology.Cell; import other.topology.Edge; import other.topology.TopologyElement; import other.topology.Vertex; /** * Graph utilities methods. * * @author Eric.Piette */ @Hide public final class GraphUtilities { /** Utility class - do not construct */ private GraphUtilities() { // Nothing to do } /** * To add a neighbour element to a graph element. * * @param type The type of the graph element. * @param element The element. * @param neighbour The neighbour to add. */ public static void addNeighbour(final SiteType type, final TopologyElement element, final TopologyElement neighbour) { switch (type) { case Cell: ((Cell) element).neighbours().add((Cell) neighbour); break; case Vertex: ((Vertex) element).neighbours().add((Vertex) neighbour); break; case Edge: ((Edge) element).neighbours().add((Edge) neighbour); break; default: break; } } /** * To add an adjacent element to a graph element. * * @param type The type of the graph element. * @param element The element. * @param adjacent The adjacent element to add. */ public static void addAdjacent(final SiteType type, final TopologyElement element, final TopologyElement adjacent) { switch (type) { case Cell: ((Cell) element).adjacent().add((Cell) adjacent); break; case Vertex: ((Vertex) element).adjacent().add((Vertex) adjacent); break; case Edge: break; default: break; } } /** * To add an orthogonal element to a graph element. * * @param type The type of the graph element. * @param element The element. * @param orthogonal The orthogonal element to add. */ public static void addOrthogonal(final SiteType type, final TopologyElement element, final TopologyElement orthogonal) { switch (type) { case Cell: ((Cell) element).orthogonal().add((Cell) orthogonal); break; case Vertex: ((Vertex) element).orthogonal().add((Vertex) orthogonal); break; case Edge: break; default: break; } } /** * To add an diagonal element to a graph element. * * @param type The type of the graph element. * @param element The element. * @param diagonal The diagonal element to add. */ public static void addDiagonal(final SiteType type, final TopologyElement element, final TopologyElement diagonal) { switch (type) { case Cell: ((Cell) element).diagonal().add((Cell) diagonal); break; case Vertex: ((Vertex) element).diagonal().add((Vertex) diagonal); break; case Edge: break; default: break; } } /** * To add an off element to a graph element. * * @param type The type of the graph element. * @param element The element. * @param off The off element to add. */ public static void addOff(final SiteType type, final TopologyElement element, final TopologyElement off) { switch (type) { case Cell: ((Cell) element).off().add((Cell) off); break; case Vertex: ((Vertex) element).off().add((Vertex) off); break; case Edge: break; default: break; } } }
3,180
20.787671
119
java
Ludii
Ludii-master/Core/src/other/IncludeInGrammar.java
package other; /** * Decorator interface to indicate classes that are used in the grammar, * for cases where this is not obvious, e.g. GravityType. * @author cambolbro */ public interface IncludeInGrammar { // }
218
17.25
72
java
Ludii
Ludii-master/Core/src/other/IntArrayFromRegion.java
package other; import java.util.BitSet; import game.Game; import game.functions.ints.IntFunction; import game.functions.region.RegionFunction; import other.context.Context; /** * Optimised class to get an integer array of non negative values from an * IntFunction or a RegionFunction. * * @author Eric.Piette */ public class IntArrayFromRegion { /** The IntegerFunction. */ private final IntFunction intFunction; /** The RegionFunction. */ private final RegionFunction regionFunction; /** Precomputed int[]. */ private int[] precomputedArray; /** * @param intFunction The IntFunction. * @param regionFunction The RegionFunction. */ public IntArrayFromRegion ( final IntFunction intFunction, final RegionFunction regionFunction ) { this.intFunction = intFunction; this.regionFunction = regionFunction; } /** * @param context The context. * @return The result of the evaluation of the functions. */ public int[] eval(final Context context) { if (precomputedArray != null) return precomputedArray; if (intFunction != null) { final int value = intFunction.eval(context); if (value >= 0) return new int[] { value }; } else if (regionFunction != null) { return regionFunction.eval(context).sites(); } return new int[0]; } /** * @return True if static. */ public boolean isStatic() { if (intFunction != null && !intFunction.isStatic()) return false; if (regionFunction != null && !regionFunction.isStatic()) return false; return true; } /** * @param game The game. * @return The game flags. */ public long gameFlags(final Game game) { long gameFlags = 0l; if (intFunction != null) gameFlags |= intFunction.gameFlags(game); if (regionFunction != null) gameFlags |= regionFunction.gameFlags(game); return gameFlags; } /** * @param game The game. * @return The concepts. */ public BitSet concepts(final Game game) { final BitSet concepts = new BitSet(); if (intFunction != null) concepts.or(intFunction.concepts(game)); if (regionFunction != null) concepts.or(regionFunction.concepts(game)); return concepts; } /** * @return The bitset about writing EvalContext variables. */ public BitSet writesEvalContextRecursive() { final BitSet writeEvalContext = new BitSet(); if (intFunction != null) writeEvalContext.or(intFunction.writesEvalContextRecursive()); if (regionFunction != null) writeEvalContext.or(regionFunction.writesEvalContextRecursive()); return writeEvalContext; } /** * @return The bitset about reading EvalContext variables. */ public BitSet readsEvalContextRecursive() { final BitSet readEvalContext = new BitSet(); if (intFunction != null) readEvalContext.or(intFunction.readsEvalContextRecursive()); if (regionFunction != null) readEvalContext.or(regionFunction.readsEvalContextRecursive()); return readEvalContext; } /** * @param game The game. * @return The missing requirements. */ public boolean missingRequirement(final Game game) { boolean missingRequirement = false; if (intFunction != null) missingRequirement |= intFunction.missingRequirement(game); if (regionFunction != null) missingRequirement |= regionFunction.missingRequirement(game); return missingRequirement; } /** * @param game The game. * @return The will crash information. */ public boolean willCrash(final Game game) { boolean willCrash = false; if (intFunction != null) willCrash |= intFunction.willCrash(game); if (regionFunction != null) willCrash |= regionFunction.willCrash(game); return willCrash; } /** * Preprocess method. * * @param game The game. */ public void preprocess(final Game game) { if (intFunction != null) intFunction.preprocess(game); if (regionFunction != null) regionFunction.preprocess(game); if (isStatic()) precomputedArray = eval(new Context(game, null)); } @Override public String toString() { if (intFunction != null) return "[IntArrayFromRegion: " + intFunction + "]"; else if (regionFunction != null) return "[IntArrayFromRegion: " + regionFunction + "]"; else return "[Empty IntArrayFromRegion]"; } /** * @param game * @return English description of this region. */ public String toEnglish(final Game game) { if (intFunction != null) return intFunction.toEnglish(game); else if (regionFunction != null) return regionFunction.toEnglish(game); else return "unknown region"; } }
4,536
21.024272
73
java
Ludii
Ludii-master/Core/src/other/IsLoopAux.java
package other; /** * Helping file of the isLoop. * * @author tahmina * */ public final class IsLoopAux { // // /** Direction chosen. */ // private final AbsoluteDirection dirnChoice; // // /** // * @param dirnChoice The absolute direction. // */ // public IsLoopAux(@Opt final AbsoluteDirection dirnChoice) // { // this.dirnChoice = (dirnChoice == null) ? AbsoluteDirection.Adjacent : dirnChoice; // } // // /** // * It's a boolean function. // * // * Remarks This function execute before add the last move in Union-tree, which // * helps to set a flag( which is ringflag) at the isLoop.java file. // * // * @param context The context. // * @param siteId Site ID for which we want to check whether we created a loop. // * // * @return Are the neighbor's position of the last move is sufficient to create // * an Open ring? // * // */ // public boolean eval(final Context context, final int siteId) // { // final SiteType type; // // if (context.game().isEdgeGame()) type = SiteType.Edge; // else if (context.game().isCellGame()) type = SiteType.Cell; // else type = SiteType.Vertex; // // if (siteId == Constants.UNDEFINED) // return false; // final Topology topology = context.topology(); // // final ContainerState state = context.state().containerStates()[0]; // final int whoSiteId = state.who(siteId, type); // // final List<? extends TopologyElement> elements; // if (type == SiteType.Vertex) // elements = context.game().board().topology().vertices(); // else if (type == SiteType.Edge) // elements = context.game().board().topology().edges(); // else if (type == SiteType.Cell) // elements = context.game().board().topology().cells(); // else // elements = context.game().graphPlayElements(); // // if (dirnChoice == AbsoluteDirection.Adjacent) // { // final TIntArrayList adjacentItemsList = new TIntArrayList(); // final List<game.util.graph.Step> steps = topology.trajectories().steps(type, siteId, dirnChoice); // // for (final game.util.graph.Step step : steps) // if (step.from().siteType() == step.to().siteType()) // adjacentItemsList.add(step.to().id()); // // return loop(type, elements, siteId, state, adjacentItemsList, state.unionInfo(AbsoluteDirection.Adjacent)[whoSiteId]); // } // else // { // final TIntArrayList adjacentItemsList = new TIntArrayList(); // final List<game.util.graph.Step> steps = topology.trajectories().steps(type, siteId, type, dirnChoice); // // for (final game.util.graph.Step step : steps) // adjacentItemsList.add(step.to().id()); // // final TIntArrayList directionItemsList = new TIntArrayList(); // // final List<game.util.graph.Step> stepsDirectionsItemsList = topology.trajectories().steps(type, siteId, // type, // dirnChoice); // // for (final game.util.graph.Step step : stepsDirectionsItemsList) // directionItemsList.add(step.to().id()); // // int count = 0; // // for (int i = 0; i < directionItemsList.size(); i++) // { // final int ni = directionItemsList.get(i); // if (state.who(ni, type) == whoSiteId) // { // count++; // } // } // // if (count < 2) // return false; // // return loopOthers(context, siteId, state, adjacentItemsList, directionItemsList, dirnChoice, state.unionInfo(AbsoluteDirection.Orthogonal)[whoSiteId]); // } // } // // //------------------------------------------------------------------------- // // /** // * @param type The graph elements type. // * @param elements The list of graph elements. // * @param siteId The last move of the current game state. // * @param state The present state of the game board. // * @param nList The adjacent list of the last move. // * @param uf The object of the union-find. // * // * @return Is it loop or not? // */ // private static boolean loop // ( // final SiteType type, // final List<? extends TopologyElement> elements, // final int siteId, // final ContainerState state, // final TIntArrayList nList, // final UnionInfoD uf // ) // { // final int whoSiteId = state.who(siteId, type); // final int numNeighbours = nList.size(); // final int[] localParent = new int[numNeighbours]; // int adjacentSetsNumber = 0; // //// System.out.println(); //// System.out.println("siteId = " + siteId); //// System.out.println("nList = " + nList); //// System.out.println("whoSiteId = " + whoSiteId); //// System.out.println(); // // Arrays.fill(localParent, Constants.UNDEFINED); // // for (int i = 0; i < numNeighbours; i++) // { // final int ni = nList.getQuick(i); // if (state.who(ni, type) == whoSiteId) // { // if (localParent[i] == Constants.UNDEFINED) // { // localParent[i] = i; // } // // final TIntArrayList kList = elementsToIndices(elements.get(ni).adjacent()); // final TIntArrayList intersectionList = intersection(nList, kList); // // for (int j = 0; j < intersectionList.size(); j++) // { // final int nj = intersectionList.getQuick(j); // // if ((state.who(nj, type) == whoSiteId) && (ni != siteId)) // { // for (int m = 0; m < numNeighbours; m++) // { // if ((m != i) && (nj == nList.getQuick(m))) // { // if (localParent[m] == -1) // { // localParent[m] = i; // break; // } // else // { // int mRoot = m; // int iRoot = i; // // while (mRoot != localParent[mRoot]) // mRoot = localParent[mRoot]; // while (iRoot != localParent[iRoot]) // iRoot = localParent[iRoot]; // // localParent[iRoot] = localParent[mRoot]; // connect between two union trees // break; // } // } // } // } // } // } // } // // for (int k = 0; k < numNeighbours; k++) // { // if (localParent[k] == k) // { // adjacentSetsNumber++; // } // } // // // if the number sets of adjacency list more than one, only then it is required // // to check the open-ring // if (adjacentSetsNumber > 1) // { // for (int i = 0; i < numNeighbours; i++) // { // if (localParent[i] == i) // { // final int rootI = find(nList.getQuick(i), uf); // // for (int j = i + 1; j < numNeighbours; j++) // { // if (localParent[j] == j) // { // if (uf.isSameGroup(rootI, nList.getQuick(j))) // { // return true; // } // } // } // // } // } // } // // return false; // } // // //------------------------------------------------------------------------- // // /** // * @param context The context of present game state. // * @param siteId The last move of the current game state. // * @param state The present state of the game board. // * @param nList The adjacent list of the last move. // * @param directionItemsList The Adjacent position according to direction. // * @param dirnChoice The direction. // * @param uf The object of the union-find. // * // * // * @return Is it loop or not? // */ // private static boolean loopOthers // ( // final Context context, // final int siteId, // final ContainerState state, // final TIntArrayList nList, // final TIntArrayList directionItemsList, // final AbsoluteDirection dirnChoice, // final UnionInfoD uf // ) // { // // final SiteType type; // // if (context.game().isEdgeGame()) type = SiteType.Edge; // else if (context.game().isCellGame()) type = SiteType.Cell; // else type = SiteType.Vertex; // // final int whoSiteId = state.who(siteId, type); // final int numNeighbours = nList.size(); // final int[] localParent = new int[numNeighbours]; // int adjacentSetsNumber = 0; // // Arrays.fill(localParent, -1); // // for (int i = 0; i < numNeighbours; i++) // { // final int ni = nList.getQuick(i); // // if (state.who(ni, type) == whoSiteId) // { // boolean orthogonalPosition = false; // for (int k = 0; k < directionItemsList.size(); k++) // { // final int oi = directionItemsList.getQuick(k); // // if (ni == oi) // { // orthogonalPosition = true; // break; // } // } // // if (orthogonalPosition) // { // if (localParent[i] == -1) // { // localParent[i] = i; // } // // final TIntArrayList kList = new TIntArrayList(); // // final Topology topology = context.topology(); // final List<game.util.graph.Step> steps = topology.trajectories().steps(type, ni, type, dirnChoice); // // for (final game.util.graph.Step step : steps) // nList.add(step.to().id()); // // final TIntArrayList intersectionList = intersection(nList, kList); // // for (int j = 0; j < intersectionList.size(); j++) // { // final int nj = intersectionList.getQuick(j); // // if ((state.who(nj, type) == whoSiteId) && (ni != siteId)) // { // for (int m = 0; m < numNeighbours; m++) // { // if ((m != i) && (nj == nList.getQuick(m))) // { // if (localParent[m] == -1) // { // localParent[m] = i; // break; // } // else // { // int mRoot = m; // int iRoot = i; // // while (mRoot != localParent[mRoot]) // mRoot = localParent[mRoot]; // while (iRoot != localParent[iRoot]) // iRoot = localParent[iRoot]; // // localParent[iRoot] = localParent[mRoot]; // connect between two union trees // break; // } // } // } // } // } // } // } // } // // // for (int k = 0; k < numNeighbours; k++) // { // // if (localParent[k] == k) // { // adjacentSetsNumber++; // } // } // // if (adjacentSetsNumber > 1) // if the number sets of adjacency list more than one, only then it is required // // to check the open-ring // { // for (int i = 0; i < numNeighbours; i++) // { // if (localParent[i] == i) // { // // final int rootI = find(nList.getQuick(i), uf); // // for (int j = i + 1; j < numNeighbours; j++) // { // if (localParent[j] == j) // { // if (uf.isSameGroup(rootI, nList.getQuick(j))) // { // return true; // } // } // } // } // } // } // // return false; // } // // //-------------------------------------------------------------------------- // /** // * // * @param position A cell number. // * @param uf Object of union-find. // * // * @return The root of the position. // */ // private static int find(final int position, final UnionInfoD uf) // { // final int parentId = uf.getParent(position); // // if (parentId == position) // return position; // else // return find(uf.getParent(parentId), uf); // } // // //------------------------------------------------------------------------- // // /** // * @param elementsList A list of topology elements. // * // * @return List of indices of the given topology elements. // */ // public static TIntArrayList elementsToIndices // ( // final List<? extends TopologyElement> elementsList // ) // { // final int verticesListSz = elementsList.size(); // final TIntArrayList indicesList = new TIntArrayList(verticesListSz); // // for (int i = 0; i < verticesListSz; i++) // { // indicesList.add(elementsList.get(i).index()); // } // // return indicesList; // } // // //------------------------------------------------------------------------- // // /** // * @param verticesList The specific Adjacent vertices List. // * @param cell The index of the cell. // * // * @return Convert Vertex type to integer list type // */ // public static boolean validDirection // ( // final TIntArrayList verticesList, final int cell // ) // { // final int verticesListSz = verticesList.size(); // // for (int i = 0; i < verticesListSz; i++) // { // if (verticesList.getQuick(i) == cell) // return true; // } // return false; // } // // //------------------------------------------------------------------------- // // /** // * @param verticesList The specific Adjacent vertices List. // * @param cell The index of the cell. // * // * @return Convert Vertex type to integer list type // */ // public static boolean adjacentCells // ( // final TIntArrayList verticesList, final int cell // ) // { // final int verticesListSz = verticesList.size(); // // for (int i = 0; i < verticesListSz; i++) // { // if (verticesList.getQuick(i) == cell) // return true; // } // return false; // } // //------------------------------------------------------------------------- // // /** // * @param list1 First list of ints. // * @param list2 Second list ints. // * // * @return List containing all ints that appear in both given lists. // */ // public static TIntArrayList intersection // ( // final TIntArrayList list1, // final TIntArrayList list2 // ) // { // final TIntArrayList list = new TIntArrayList(); // // for (int i = 0; i < list1.size(); i++) // { // if (list2.contains(list1.getQuick(i))) // list.add(list1.getQuick(i)); // } // return list; // } // // //----------------------------------------------------------------------------- // // @Override // public String toString() // { // String str = ""; // str += "IsLoopAux( )"; // return str; // } // // //------------------------------------------------------------------------- // // }
13,667
26.501006
157
java
Ludii
Ludii-master/Core/src/other/ItemType.java
package other; /** * The item type of the equipment, ordered to be sorted in the list of Item in * Equipment.java * * Note: This is not a ludeme, just used internally. * * @author Eric.Piette */ public enum ItemType { /** * A container. */ Container, /** * A hand container. */ Hand, /** * A fan container. */ Fan, /** * A dice container. */ Dice, /** * The hints. */ Hints, /** * The regions. */ Regions, /** * A map. */ Map, /** * The dominoes. */ Dominoes, /** * A component. */ Component; /** * @param itemType * @return True if and only if the given item type is a type of container */ public static boolean isContainer(final ItemType itemType) { return itemType.ordinal() <= Dice.ordinal(); } /** * @param itemType * @return True if and only if the given item type is a type of component (Component or Dominoes) */ public static boolean isComponent(final ItemType itemType) { return itemType.ordinal() >= Dominoes.ordinal(); } /** * @param itemType * @return True if and only if the given item type is a Regions type */ public static boolean isRegion(final ItemType itemType) { return itemType == Regions; } /** * @param itemType * @return True if and only if the given item type is a Map type */ public static boolean isMap(final ItemType itemType) { return itemType == Map; } /** * @param itemType * @return True if and only if the given item type is a Hints type */ public static boolean isHints(final ItemType itemType) { return itemType == Hints; } }
1,606
14.451923
98
java
Ludii
Ludii-master/Core/src/other/Ludeme.java
package other; import java.util.BitSet; import game.Game; /** * Ludeme interface. * * @author cambolbro and Eric.Piette */ public interface Ludeme { /** * @param game The game. * @return English description of this ludeme. */ public String toEnglish(final Game game); /** * @param game The game. * @return Accumulated flags corresponding to the game concepts. */ public BitSet concepts(final Game game); /** * @return Recursively accumulated flags corresponding to read data in EvalContext. */ public BitSet readsEvalContextRecursive(); /** * @return Recursively accumulated flags corresponding to write data in EvalContext. */ public BitSet writesEvalContextRecursive(); /** * @return EvalContext properties read by this ludeme directly (not recursively) */ public BitSet readsEvalContextFlat(); /** * @return EvalContext properties writte by this ludeme directly (not recursively) */ public BitSet writesEvalContextFlat(); /** * @param game The game. * @return True if a required ludeme is missing. */ public boolean missingRequirement(final Game game); /** * @param game The game. * @return True if the ludeme can crash the game during its play. */ public boolean willCrash(final Game game); }
1,270
20.913793
85
java
Ludii
Ludii-master/Core/src/other/MetaRules.java
package other; import game.types.play.GravityType; import game.types.play.PinType; import game.types.play.RepetitionType; /** * To store which meta rule is activated or not. * * @author Eric.Piette */ public class MetaRules { /** To know if the metarule automove is activate for that game. */ private boolean automove = false; /** To know the gravityType to apply. */ private GravityType gravityType = null; /** To know the pinType to apply. */ private PinType pinType = null; /** To know if the metarule swap is activate for that game. */ private boolean usesSwapRule = false; /** To know if a metarule about repetition is activated. */ private RepetitionType repetitionType = null; /** To know if the metarule no suicide is on. */ private boolean usesNoSuicide = false; //------------------------------------------------------------------------- /** * @return True if the game uses automove. */ public boolean automove() { return automove; } /** * To set the automove value. * * @param automove The value to set. */ public void setAutomove(final boolean automove) { this.automove = automove; } //------------------------------------------------------------------------- /** * @return True if the game uses the swap rule. */ public boolean usesSwapRule() { return usesSwapRule; } /** * To set the flag indicating whether or not this game uses swap rule. * * @param swap The value to set. */ public void setUsesSwapRule(final boolean swap) { usesSwapRule = swap; } //------------------------------------------------------------------------- /** * To set the repetition meta rule. * * @param type The repetition type. */ public void setRepetitionType(final RepetitionType type) { repetitionType = type; } /** * @return The type of the repetition. */ public RepetitionType repetitionType() { return repetitionType; } //------------------------------------------------------------------------- /** * To set the gravity meta rule. * * @param type The gravity type. */ public void setGravityType(final GravityType type) { gravityType = type; } /** * @return The type of the gravity. */ public GravityType gravityType() { return gravityType; } //------------------------------------------------------------------------- /** * To set the pin meta rule. * * @param type The pin type. */ public void setPinType(final PinType type) { pinType = type; } /** * @return The type of the pin. */ public PinType pinType() { return pinType; } //------------------------------------------------------------------------- /** * To set the no suicide meta rule. * * @param value The no suicide value. */ public void setNoSuicide(final boolean value) { usesNoSuicide = value; } /** * @return The value of the no suicide meta rule. */ public boolean usesNoSuicide() { return usesNoSuicide; } }
2,970
18.546053
76
java
Ludii
Ludii-master/Core/src/other/PlayersIndices.java
package other; import game.types.play.RoleType; import gnu.trove.list.array.TIntArrayList; import other.context.Context; /** * Utility class to get the indices of players. * * @author Eric.Piette */ public class PlayersIndices { /** * @param context The context. * @param role The role of the player. * * @return The ids of the real players (between 1 and n) corresponding to the roleType. */ public static TIntArrayList getIdRealPlayers(final Context context, final RoleType role) { final TIntArrayList idPlayers = new TIntArrayList(); switch (role) { case All: for (int pid = 1; pid < context.game().players().size(); ++pid) idPlayers.add(pid); break; case Enemy: if (context.game().requiresTeams()) { final int teamMover = context.state().getTeam(context.state().mover()); for (int pid = 1; pid < context.game().players().size(); ++pid) if (pid != context.state().mover() && !context.state().playerInTeam(pid, teamMover)) idPlayers.add(pid); } else { for (int pid = 1; pid < context.game().players().size(); ++pid) if (pid != context.state().mover()) idPlayers.add(pid); } break; case Ally: if (context.game().requiresTeams()) { final int teamMover = context.state().getTeam(context.state().mover()); for (int pid = 1; pid < context.game().players().size(); ++pid) if (pid != context.state().mover() && context.state().playerInTeam(pid, teamMover)) idPlayers.add(pid); } break; case Friend: if (context.game().requiresTeams()) { final int teamMover = context.state().getTeam(context.state().mover()); for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, teamMover)) idPlayers.add(pid); } else idPlayers.add(context.state().mover()); break; case NonMover: for (int pid = 1; pid < context.game().players().size(); ++pid) if (pid != context.state().mover()) idPlayers.add(pid); break; case Mover: idPlayers.add(context.state().mover()); break; case Next: idPlayers.add(context.state().next()); break; case Prev: idPlayers.add(context.state().prev()); break; case P1: idPlayers.add(1); break; case P2: idPlayers.add(2); break; case P3: idPlayers.add(3); break; case P4: idPlayers.add(4); break; case P5: idPlayers.add(5); break; case P6: idPlayers.add(6); break; case P7: idPlayers.add(7); break; case P8: idPlayers.add(8); break; case P9: idPlayers.add(9); break; case P10: idPlayers.add(0); break; case P11: idPlayers.add(11); break; case P12: idPlayers.add(12); break; case P13: idPlayers.add(13); break; case P14: idPlayers.add(14); break; case P15: idPlayers.add(15); break; case P16: idPlayers.add(16); break; case Player: idPlayers.add(context.player()); break; case Team1: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 1)) idPlayers.add(pid); } else idPlayers.add(1); break; case Team2: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 2)) idPlayers.add(pid); } else idPlayers.add(2); break; case Team3: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 3)) idPlayers.add(pid); } else idPlayers.add(3); break; case Team4: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 4)) idPlayers.add(pid); } else idPlayers.add(4); break; case Team5: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 5)) idPlayers.add(pid); } else idPlayers.add(5); break; case Team6: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 6)) idPlayers.add(pid); } else idPlayers.add(6); break; case Team7: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 7)) idPlayers.add(pid); } else idPlayers.add(7); break; case Team8: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 8)) idPlayers.add(pid); } else idPlayers.add(8); break; case Team9: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 9)) idPlayers.add(pid); } else idPlayers.add(9); break; case Team10: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 10)) idPlayers.add(pid); } else idPlayers.add(10); break; case Team11: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 11)) idPlayers.add(pid); } else idPlayers.add(11); break; case Team12: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 12)) idPlayers.add(pid); } else idPlayers.add(12); break; case Team13: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 13)) idPlayers.add(pid); } else idPlayers.add(13); break; case Team14: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 14)) idPlayers.add(pid); } else idPlayers.add(14); break; case Team15: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 15)) idPlayers.add(pid); } else idPlayers.add(15); break; case Team16: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 16)) idPlayers.add(pid); } else idPlayers.add(16); break; case TeamMover: if (context.game().requiresTeams()) { final int teamMover = context.state().getTeam(context.state().mover()); for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, teamMover)) idPlayers.add(pid); } else idPlayers.add(context.state().mover()); break; default: break; } return idPlayers; } /** * @param context The context. * @param occupiedByRole The role of the player. * @param occupiedbyId The specific player in entry. * * @return The ids of the players corresponding to the roleTypes. */ public static TIntArrayList getIdPlayers(final Context context, final RoleType occupiedByRole, final int occupiedbyId) { final TIntArrayList idPlayers = new TIntArrayList(); if (occupiedByRole != null) { switch (occupiedByRole) { case All: for (int pid = 0; pid <= context.game().players().size(); ++pid) idPlayers.add(pid); break; case Enemy: if (context.game().requiresTeams()) { final int teamMover = context.state().getTeam(context.state().mover()); for (int pid = 1; pid < context.game().players().size(); ++pid) if (pid != context.state().mover() && !context.state().playerInTeam(pid, teamMover)) idPlayers.add(pid); } else { for (int pid = 1; pid < context.game().players().size(); ++pid) if (pid != context.state().mover()) idPlayers.add(pid); } break; case Ally: if (context.game().requiresTeams()) { final int teamMover = context.state().getTeam(context.state().mover()); for (int pid = 1; pid < context.game().players().size(); ++pid) if (pid != context.state().mover() && context.state().playerInTeam(pid, teamMover)) idPlayers.add(pid); } break; case Friend: if (context.game().requiresTeams()) { final int teamMover = context.state().getTeam(context.state().mover()); for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, teamMover)) idPlayers.add(pid); } else idPlayers.add(context.state().mover()); break; case Mover: idPlayers.add(context.state().mover()); break; case Next: idPlayers.add(context.state().next()); break; case Prev: idPlayers.add(context.state().prev()); break; case NonMover: for (int pid = 0; pid < context.game().players().size(); ++pid) if (pid != context.state().mover()) idPlayers.add(pid); break; case Team1: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 1)) idPlayers.add(pid); } else idPlayers.add(1); break; case Team2: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 2)) idPlayers.add(pid); } else idPlayers.add(2); break; case Team3: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 3)) idPlayers.add(pid); } else idPlayers.add(3); break; case Team4: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 4)) idPlayers.add(pid); } else idPlayers.add(4); break; case Team5: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 5)) idPlayers.add(pid); } else idPlayers.add(5); break; case Team6: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 6)) idPlayers.add(pid); } else idPlayers.add(6); break; case Team7: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 7)) idPlayers.add(pid); } else idPlayers.add(7); break; case Team8: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 8)) idPlayers.add(pid); } else idPlayers.add(8); break; case Team9: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 9)) idPlayers.add(pid); } else idPlayers.add(9); break; case Team10: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 10)) idPlayers.add(pid); } else idPlayers.add(10); break; case Team11: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 11)) idPlayers.add(pid); } else idPlayers.add(11); break; case Team12: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 12)) idPlayers.add(pid); } else idPlayers.add(12); break; case Team13: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 13)) idPlayers.add(pid); } else idPlayers.add(13); break; case Team14: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 14)) idPlayers.add(pid); } else idPlayers.add(14); break; case Team15: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 15)) idPlayers.add(pid); } else idPlayers.add(15); break; case Team16: if (context.game().requiresTeams()) { for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, 16)) idPlayers.add(pid); } else idPlayers.add(16); break; case TeamMover: if (context.game().requiresTeams()) { final int teamMover = context.state().getTeam(context.state().mover()); for (int pid = 1; pid < context.game().players().size(); ++pid) if (context.state().playerInTeam(pid, teamMover)) idPlayers.add(pid); } else idPlayers.add(context.state().mover()); break; default: idPlayers.add(occupiedbyId); break; } } else { idPlayers.add(occupiedbyId); } return idPlayers; } }
14,048
24.042781
119
java
Ludii
Ludii-master/Core/src/other/RankUtils.java
package other; import other.context.Context; /** * Some utility methods for working with rankings (and converting them to utilities) * * @author Dennis Soemers */ public class RankUtils { //------------------------------------------------------------------------- /** * Constructor */ private RankUtils() { // Do not instantiate } //------------------------------------------------------------------------- /** * Converts a rank >= 1 into a utility value in [-1, 1]. * * @param rank * @param numPlayers Total number of players in the game (active + inactive ones) * @return Utility for the given rank */ public static double rankToUtil(final double rank, final int numPlayers) { if (numPlayers == 1) { // a single-player game return 2.0 * rank - 1.0; } else { // two or more players return 1.0 - ((rank - 1.0) * (2.0 / (numPlayers - 1))); } } /** * Computes a vector of utility values for all players based on the player * rankings in the given context. * * For players who do not yet have an established ranking, a "draw" utility * will be returned. * * For players who do have an established ranking, the utility value will lie * in [-1, 1] based on the ranking; 1.0 for top ranking, -1.0 for bottom ranking, * 0.0 for middle ranking (e.g. second player out of three), etc. * * The returned array will have a length equal to the number of players plus one, * such that it can be indexed directly by player number. * * @param context * @return The utilities. */ public static double[] utilities(final Context context) { final double[] ranking = context.trial().ranking(); final double[] utilities = new double[ranking.length]; final int numPlayers = ranking.length - 1; //System.out.println("ranking = " + Arrays.toString(ranking)); for (int p = 1; p < ranking.length; ++p) { double rank = ranking[p]; if (numPlayers > 1 && rank == 0.0) { // looks like a playout didn't terminate yet; assign "draw" ranks rank = context.computeNextDrawRank(); } utilities[p] = rankToUtil(rank, numPlayers); assert (utilities[p] >= -1.0 && utilities[p] <= 1.0); } // System.out.println("ranking = " + Arrays.toString(ranking)); // System.out.println("utilities = " + Arrays.toString(utilities)); return utilities; } /** * Computes a vector of utilities, like above, but now for agents. In states * where a player-swap has occurred, the utilities will also be swapped, such * that the utility values can be indexed by original-agent-index rather than * role / colour / player index. * * @param context * @return The agent utilities. */ public static double[] agentUtilities(final Context context) { final double[] utils = utilities(context); final double[] agentUtils = new double[utils.length]; for (int p = 1; p < utils.length; ++p) { agentUtils[p] = utils[context.state().playerToAgent(p)]; } return agentUtils; } //------------------------------------------------------------------------- }
3,092
26.131579
84
java
Ludii
Ludii-master/Core/src/other/Sites.java
package other; import java.util.Arrays; /** * A collection of sites within a container. * * @author cambolbro */ public class Sites { private int count = 0; private final int[] sites; //------------------------------------------------------------------------- /** * Constructor. * * @param count */ public Sites(final int count) { this.count = count; this.sites = new int[count]; for (int n = 0; n < count; n++) this.sites[n] = n; } /** * Constructor. * * @param sites */ public Sites(final int[] sites) { this.count = sites.length; this.sites = new int[this.count]; // for (int n = 0; n < count; n++) // this.sites[n] = sites[n]; System.arraycopy(sites, 0, this.sites, 0, this.count); } /** * Copy constructor. * * @param other */ public Sites(final Sites other) { this.count = other.count; this.sites = new int[other.sites.length]; // for (int n = 0; n < count; n++) // this.sites[n] = other.sites[n]; System.arraycopy(other.sites, 0, this.sites, 0, this.sites.length); } //------------------------------------------------------------------------- /** * @return Number of sites. */ public int count() { return count; } /** * @return Collection of site values. */ public int[] sites() { return sites; } //------------------------------------------------------------------------- /** * Note: May be sparse! * * @param newCount */ public void set(final int newCount) { if (newCount > sites.length) { System.out.println("** Sites.set() A: Bad count " + newCount + " for " + sites.length + " entries."); try { throw new Exception("Exception."); } catch (final Exception e) { e.printStackTrace(); } return; } count = newCount; for (int n = 0; n < count; n++) sites[n] = n; for (int n = count; n < sites.length; ++n) sites[n] = -1; } /** * Note: May be sparse! * * @param other */ public void set(final Sites other) { if (other.count > sites.length) { System.out.println("** Sites.set() B: Bad count " + other.count + " for " + sites.length + " entries."); return; } count = other.count; // for (int n = 0; n < count; n++) // sites[n] = other.sites[n]; System.arraycopy(other.sites, 0, sites, 0, count); for (int n = count; n < sites.length; ++n) sites[n] = -1; } /** * @param n * @return Nth value. */ public int nthValue(final int n) { return sites[n]; } /** * @param val */ public void add(final int val) { if (count >= sites.length) { System.out.println("** Sites.add(): Trying to add " + val + " to full array."); return; } sites[count] = val; count++; } /** * Remove the specified value. * * @param val */ public void remove(final int val) { if (count < 1) { System.out.println("** Sites.remove(): Trying to remove " + val + " from " + count + " entries."); return; } // At start, sites[n]==n. // Once we use an entry, we swap always to a lower index, // So start at cell and work down... for (int n = Math.min(val, count - 1); n >= 0; n--) if (sites[n] == val) { // Move tail into slot n sites[n] = sites[count - 1]; sites[count - 1] = -1; count--; return; // n; } // ...unless we added a cell back in! for (int n = count - 1; n > Math.min(val, count - 1); n--) if (sites[n] == val) { // Move tail into slot n sites[n] = sites[count - 1]; sites[count - 1] = -1; count--; return; // n; } // Should be impossible // return -1; System.out.println("** Sites.remove(): Failed to find value " + val + "."); } /** * Remove the Nth entry. * * @param n * @return Value of Nth entry. */ public int removeNth(final int n) { if (count < 1) { System.out.println("** Sites.remove(): Trying to remove " + n + "th entry from " + count + " entries."); return -1; } // Move tail into slot n final int val = sites[n]; sites[n] = sites[count - 1]; sites[count - 1] = -1; count--; return val; } //------------------------------------------------------------------------- @Override public String toString() { return "Sites{" + Arrays.toString(sites) + " (count at:= " + count + ")}"; } }
4,285
17.881057
107
java
Ludii
Ludii-master/Core/src/other/ThinkingThread.java
package other; import game.Game; import other.context.Context; import other.move.Move; /** * This class can be used to let an AI player spend its thinking time * in a separate thread, and afterwards ask it what move it wants to * play. * * @author Dennis Soemers */ public class ThinkingThread extends Thread { //------------------------------------------------------------------------- /** Our runnable */ protected final ThinkingThreadRunnable runnable; //------------------------------------------------------------------------- /** * @param ai * @param game * @param context * @param maxSeconds * @param maxIterations * @param maxDepth * @param minSeconds * @param postThinking * @return Constructs a thread for AI to think in */ public static ThinkingThread construct ( final AI ai, final Game game, final Context context, final double maxSeconds, final int maxIterations, final int maxDepth, final double minSeconds, final Runnable postThinking ) { final ThinkingThreadRunnable runnable = new ThinkingThreadRunnable ( ai, game, context, maxSeconds, maxIterations, maxDepth, minSeconds, postThinking ); //System.out.println("constructing thread for " + ai); //Global.stackTrace(); return new ThinkingThread(runnable); } /** * Constructor * @param runnable */ protected ThinkingThread(final ThinkingThreadRunnable runnable) { super(runnable); this.runnable = runnable; } //------------------------------------------------------------------------- /** * @return Our AI object */ public AI ai() { return runnable.ai; } /** * @return The chosen move (or null if not chosen a move yet) */ public Move move() { return runnable.chosenMove; } /** * Tells the AI to interrupt its thinking process * @return Reference to our AI */ public AI interruptAI() { runnable.postThinking = null; // should not call the callback if we're interrupting runnable.ai.setWantsInterrupt(true); return runnable.ai; } //------------------------------------------------------------------------- /** * Runnable class for Thinking Thread * * @author Dennis Soemers */ private static class ThinkingThreadRunnable implements Runnable { //--------------------------------------------------------------------- /** AI */ protected final AI ai; /** Game */ protected final Game game; /** Context/state in which to think */ protected final Context context; /** Max seconds */ protected final double maxSeconds; /** Max iterations */ protected final int maxIterations; /** Max search depth */ protected final int maxDepth; /** Minimum number of seconds we should spend thinking */ protected final double minSeconds; /** Runnable to run when we've finished thinking */ protected Runnable postThinking; /** The move chosen by AI */ protected Move chosenMove = null; //--------------------------------------------------------------------- /** * Constructor * @param ai * @param game * @param context * @param maxSeconds * @param maxIterations * @param maxDepth * @param minSeconds * @param postThinking */ public ThinkingThreadRunnable ( final AI ai, final Game game, final Context context, final double maxSeconds, final int maxIterations, final int maxDepth, final double minSeconds, final Runnable postThinking ) { this.ai = ai; this.game = game; this.context = context; this.maxSeconds = maxSeconds; this.maxIterations = maxIterations; this.maxDepth = maxDepth; this.minSeconds = minSeconds; this.postThinking = postThinking; } //--------------------------------------------------------------------- @Override public void run() { final long startTime = System.currentTimeMillis(); chosenMove = ai.selectAction ( game, ai.copyContext(context), maxSeconds, maxIterations, maxDepth ); // make sure we don't play too fast if (System.currentTimeMillis() < startTime + 1000L * minSeconds) { try { Thread.sleep((long) (startTime + 1000L * minSeconds) - System.currentTimeMillis()); } catch (final InterruptedException e) { e.printStackTrace(); } } //System.out.println(Thread.currentThread() + " setting chosen move: " + chosenMove); if (postThinking != null) postThinking.run(); } } //------------------------------------------------------------------------- }
4,653
20.154545
88
java
Ludii
Ludii-master/Core/src/other/UndoData.java
package other; import java.util.Arrays; import java.util.BitSet; import gnu.trove.list.array.TIntArrayList; import gnu.trove.list.array.TLongArrayList; import gnu.trove.set.hash.TIntHashSet; import main.Status; import main.collections.FastTIntArrayList; import other.state.owned.Owned; import other.state.track.OnTrackIndices; /** * Undo Data necessary to be able to undo a move. * * @author Eric.Piette */ public class UndoData { //------------------------Data modified by end rules------------------------------------- /** Ranking of the players. */ private final double[] ranking; /** Result of game (null if game is still in progress). */ private final Status status; /** List of players who've already won */ private final TIntArrayList winners; /** List of players who've already lost */ private final TIntArrayList losers; /** For every player, a bit indicating whether they are active */ private int active = 0; /** Scores per player. Game scores if this is a trial for just a game, match scores if it's a trial for a Match */ private final int[] scores; /** * Payoffs per player. Game payoff if this is a trial for just a game, match * scores if it's a trial for a Match */ private final double[] payoffs; /** * Data used during the computation of the ranking in case of multi results in * the same turn. (we need a better name for that variable but I am too tired to * find one ^^) TODO officially I guess this should actually be in EvalContext? */ private int numLossesDecided = 0; /** Same as above, but for wins */ // TODO officially I guess this should actually be in EvalContext? private int numWinsDecided = 0; //-----------------------Data modified in game.apply()-------------------------------------- /** The current phase of each player. */ private final int[] phases; /** The pending values. */ private final TIntHashSet pendingValues; /** The counter. */ private final int counter; /** The previous state in the same turn. */ private final TLongArrayList previousStateWithinATurn; /** The previous state in case of no repetition rule. */ private final TLongArrayList previousState; /** The index of the previous player. */ private final int prev; /** The index of the mover. */ private final int mover; /** The index of the next player. */ private final int next; /** The number of times the mover has been switched to a different player. */ private final int numTurn; /** The number of turns played successively by the same player. */ private final int numTurnSamePlayer; /** Number of consecutive pass moves. */ private int numConsecutivePasses = 0; /** All the remaining dominoes. */ private FastTIntArrayList remainingDominoes; /** The decision after voting. */ private int isDecided; /** * BitSet used to store all the site already visited (from & to) by each move * done by the player in a sequence of turns played by the same player. */ private BitSet visited = null; /** In case of a sequence of capture to remove (e.g. some draughts games). */ private TIntArrayList sitesToRemove = null; /** To access where are each type of piece on each track. */ private OnTrackIndices onTrackIndices; /** To access where are each type of piece on each track. */ private Owned owned; //------------------------------------------------------------------------- /** * @param ranking The ranking of the players. * @param status The status of the game. * @param winners The players who've already won. * @param losers The players who've already lost. * @param active For every player, a bit indicating whether they are active. * @param scores Scores per player. * @param payoffs Payoffs per player. * @param numLossesDecided Number of losses decided. * @param numWinsDecided Number of wins decided. * @param phases The phases of each player. * @param pendingValues The pending values. * @param counter The counter of the state. * @param previousStateWithinATurn The previous state in the same turn. * @param previousState The previous state in case of no repetition rule. * @param prev The index of the previous player. * @param mover The index of the mover. * @param next The index of the next player. * @param numTurn The number of turns. * @param numTurnSamePlayer The number of moves played so far in the same turn. * @param numConsecutivePasses Number of consecutive pass moves. * @param remainingDominoes All the remainingDominoes. * @param visited Sites visited during the same turn. * @param sitesToRemove Sites to remove in case of a sequence of capture. * @param onTrackIndices To access where are each type of piece on each track. * @param owned Access to list of sites for each kind of component owned per player. * @param isDecided The decision after voting. */ public UndoData ( final double[] ranking, final Status status, final TIntArrayList winners, final TIntArrayList losers, final int active, final int[] scores, final double[] payoffs, final int numLossesDecided, final int numWinsDecided, final int[] phases, final TIntHashSet pendingValues, final int counter, final TLongArrayList previousStateWithinATurn, final TLongArrayList previousState, final int prev, final int mover, final int next, final int numTurn, final int numTurnSamePlayer, final int numConsecutivePasses, final FastTIntArrayList remainingDominoes, final BitSet visited, final TIntArrayList sitesToRemove, final OnTrackIndices onTrackIndices, final Owned owned, final int isDecided ) { this.ranking = Arrays.copyOf(ranking, ranking.length); this.status = status == null ? null : new Status(status); this.winners = new TIntArrayList(winners); this.losers = new TIntArrayList(losers); this.active = active; this.scores = scores == null ? null : Arrays.copyOf(scores, scores.length); this.payoffs = payoffs == null ? null : Arrays.copyOf(payoffs, payoffs.length); this.numLossesDecided = numLossesDecided; this.numWinsDecided = numWinsDecided; this.phases = phases == null ? null : Arrays.copyOf(phases, phases.length); this.pendingValues = pendingValues == null ? null : new TIntHashSet(pendingValues); this.counter = counter; this.previousStateWithinATurn = new TLongArrayList(previousStateWithinATurn); this.previousState = new TLongArrayList(previousState); this.prev = prev; this.mover = mover; this.next = next; this.numTurn = numTurn; this.numTurnSamePlayer = numTurnSamePlayer; this.numConsecutivePasses = numConsecutivePasses; this.remainingDominoes = remainingDominoes == null ? null : new FastTIntArrayList(remainingDominoes); this.visited = visited == null ? null : (BitSet) visited.clone(); this.sitesToRemove = sitesToRemove == null ? null : new TIntArrayList(sitesToRemove); this.onTrackIndices = onTrackIndices == null ? null : new OnTrackIndices(onTrackIndices); this.owned = owned == null ? null : owned.copy(); this.isDecided = isDecided; } //------------------------------------------------------------------------- /** * @return The ranking. */ public double[] ranking() { return ranking; } /** * @return The status. */ public Status status() { return status; } /** * @return The winners. */ public TIntArrayList winners() { return winners; } /** * @return The losers. */ public TIntArrayList losers() { return losers; } /** * @return For each player a bit to indicate each player is active. */ public int active() { return active; } /** * @return The scores of each player. */ public int[] scores() { return scores; } /** * @return The payoffs of each player. */ public double[] payoffs() { return payoffs; } /** * @return The number of losses decided. */ public int numLossesDecided() { return numLossesDecided; } /** * @return The number of wins decided. */ public int numWinsDecided() { return numWinsDecided; } /** * @return The phase of each player. */ public int[] phases() { return phases; } /** * @return The phase of each player. */ public TIntHashSet pendingValues() { return pendingValues; } /** * @return The counter. */ public int counter() { return counter; } /** * @return The previous state in the same turn. */ public TLongArrayList previousStateWithinATurn() { return previousStateWithinATurn; } /** * @return The previous state in case of no repetition rule. */ public TLongArrayList previousState() { return previousState; } /** * @return The index of the previous player. */ public int prev() { return prev; } /** * @return The index of the mover. */ public int mover() { return mover; } /** * @return The index of the next player. */ public int next() { return next; } /** * @return The number of times the mover has been switched to a different player. */ public int numTurn() { return numTurn; } /** * @return The number of turns played successively by the same player. */ public int numTurnSamePlayer() { return numTurnSamePlayer; } /** * @return Number of consecutive pass moves. */ public int numConsecutivePasses() { return numConsecutivePasses; } /** * @return All the remaining dominoes. */ public FastTIntArrayList remainingDominoes() { return remainingDominoes; } /** * @return Sites visited during the same turn. */ public BitSet visited() { return visited; } /** * @return Sites to remove in case of a sequence of capture. */ public TIntArrayList sitesToRemove() { return sitesToRemove; } /** * @return To access where are each type of piece on each track. */ public OnTrackIndices onTrackIndices() { return onTrackIndices; } /** * @return Owned sites per component */ public Owned owned() { return owned; } /** * @return The decision after voting. */ public int isDecided() { return isDecided; } }
10,368
24.22871
115
java
Ludii
Ludii-master/Core/src/other/WeaklyCachingGameLoader.java
package other; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; import game.Game; import main.collections.StringPair; /** * A game loader object that can be useful for situations with lots of multi-threading * and partial overlap in games used between threads. * * This game loader: * 1) Blocks; will only compile and return one game at a time * 2) Caches compiled game objects using weak references * * If multiple threads want to compile and use the same Game object simultaneously, * they will only actually compile once and share the same object. This can save a * lot of memory. However, when no thread uses a Game object anymore, it will not * remain stuck in cache * * @author Dennis Soemers */ public class WeaklyCachingGameLoader { //------------------------------------------------------------------------- /** Singleton instance */ public static final WeaklyCachingGameLoader SINGLETON = new WeaklyCachingGameLoader(); /** Our cache of weak references to compiled game objects */ private final Map<StringPair, WeakReference<Game>> gameCache = new HashMap<StringPair, WeakReference<Game>>(); //------------------------------------------------------------------------- /** * Constructor; private because we want singleton */ private WeaklyCachingGameLoader() { // Do nothing } //------------------------------------------------------------------------- /** * @param gameName * @param rulesetName * @return Game object for given game name and ruleset name */ public synchronized Game loadGameFromName(final String gameName, final String rulesetName) { Game returnGame = null; final StringPair key = new StringPair(gameName, rulesetName != null ? rulesetName : ""); final WeakReference<Game> gameRef = gameCache.get(key); if (gameRef == null) { returnGame = GameLoader.loadGameFromName(gameName, rulesetName); gameCache.put(key, new WeakReference<Game>(returnGame)); } else { returnGame = gameRef.get(); if (returnGame == null) { returnGame = GameLoader.loadGameFromName(gameName, rulesetName); gameCache.put(key, new WeakReference<Game>(returnGame)); } } return returnGame; } //------------------------------------------------------------------------- }
2,323
27.691358
111
java
Ludii
Ludii-master/Core/src/other/action/Action.java
package other.action; import java.io.Serializable; import java.util.BitSet; import annotations.Hide; import game.rules.play.moves.Moves; import game.types.board.SiteType; import other.context.Context; /** * Action (or actions) making up a player move. * * @author cambolbro and Eric.Piette */ @Hide public interface Action extends Serializable { /** * Apply this instruction to the specified state. * * @param context The context. * @param store To store directly the action in the trial. * @return Action as applied (possibly with additional Actions from consequents * in Moves) */ public Action apply(final Context context, final boolean store); /** * To undo an action. * * @param context The context. * @param discard To discard directly the action in the trial. * @return Action as applied to undo the corresponding action. */ public Action undo(final Context context, final boolean discard); /** * @return Whether this action is a pass. */ public boolean isPass(); /** * @return Whether this action is a forfeit. */ public boolean isForfeit(); /** * @return Whether this action is a swap. */ public boolean isSwap(); /** * @return Whether this action is a vote. */ public boolean isVote(); /** * @return Whether this action is forced. */ public boolean isForced(); /** * @return Whether this action is a propose. */ public boolean isPropose(); /** * @return Whether this action is always legal in the GUI. */ public boolean isAlwaysGUILegal(); /** * @return The player selected by the action. */ public int playerSelected(); /** * @return Whether this contains a NextInstance action */ public boolean containsNextInstance(); /** * @param siteA The site A. * @param levelA The level A. * @param graphElementTypeA The graph element type A. * @param siteB The site B. * @param levelB The site B. * @param graphElementTypeB The graph element type B. * @return Whether this action matches a user move in the GUI. */ public boolean matchesUserMove(final int siteA, final int levelA, final SiteType graphElementTypeA, final int siteB, final int levelB, final SiteType graphElementTypeB); //------------------------------------------------------------------------- /** * @return The from location of the action. For Move.java, the from location of * the first decision action in the list. */ public int from(); /** * @return The level of the from location of the action (typically 0). For * Move.java, the level of the from location of the first decision * action in the list. */ public int levelFrom(); /** * @return The to location of the action. For Move.java, the to location of the * first decision action in the list. */ public int to(); /** * @return The level of the to location of the action (typically 0). For * Move.java, the level of the to location of the first decision action * in the list. */ public int levelTo(); /** * @return The player index of the action. For Move.java, the player index of * the first decision action in the list. */ public int who(); /** * @return The piece index of the action. For Move.java, the piece index of the * first decision action in the list. */ public int what(); /** * @return The state value of the action. For Move.java, the state value of the * first decision action in the list. */ public int state(); /** * @return The rotation value of the action. For Move.java, the rotation value * of the first decision action in the list. */ public int rotation(); /** * @return The piece value of the action. For Move.java, the piece value of the * first decision action in the list. */ public int value(); /** * @return The count value of the action. For Move.java, the count value of the * first decision action in the list. */ public int count(); /** * @return The proposition of the action. For Move.java, the proposition of the * first decision action in the list. */ public String proposition(); /** * @return The vote of the action. For Move.java, the vote of the first decision * action in the list. */ public String vote(); /** * @return The message of the action. For Move.java, the message of the first * decision action in the list. */ public String message(); /** * @return Whether the action is in a stacking state. For Move.java, Whether the * first decision action in the list is in a stacking state. */ public boolean isStacking(); /** * @return Record of hidden information for the action. For Move.java, the * hidden information of the first decision action in the list. */ boolean[] hidden(); /** * @return True if this is a decision. */ public boolean isDecision(); /** * @return The action Type. */ public ActionType actionType(); /** * @return The type of kind of graph element involved in the action by the from. * In Move.java, the graph element type of the from location of the * first decision action in the list. */ public abstract SiteType fromType(); /** * @return The type of kind of graph element involved in the action by the to. * In Move.java, the graph element type of the to location of the first * decision action in the list. */ public abstract SiteType toType(); /** * Set whether this action is a decision. * * @param decision The decision to set. */ public void setDecision(final boolean decision); /** * Set whether this action is a decision, and return the action object. * * @param decision * @return The same action object we're calling the method on. */ public Action withDecision(final boolean decision); /** * @param context * @return A detailed string description of this action, with sufficient * detail to allow an equivalent reconstruction (in the given context, * with consequents already resolved for that context) */ public String toTrialFormat(final Context context); /** * @param context * @param useCoords Use coordinates for display. * @return A less detailed string description of the move for the move tab. */ public String toMoveFormat(final Context context, final boolean useCoords); /** * @return A short string name/description for this action. */ public String getDescription(); /** * Need the context in order to display the coordinates if needed. * * @param context The context. * @param useCoords Use coordinates for display. * @return The string. */ public String toTurnFormat(final Context context, final boolean useCoords); /** * To set the level of the from location of the action. * * @param levelA The level to set. */ public void setLevelFrom(final int levelA); /** * To set the level of the to location of the action. * * @param levelB The level to set. */ public void setLevelTo(final int levelB); /** * @return True if the move has to be used in the . . . in the GUI. */ public boolean isOtherMove(); /** * @param detailedString The full detailed string of the action * @param data The data to extract * @return The extracted data in a string. If not found, an empty String. */ public static String extractData(final String detailedString, final String data) { final int fromIndex = detailedString.indexOf(data + "="); if (fromIndex < 0) return ""; final String beginData = detailedString.substring(fromIndex); int toIndex = beginData.indexOf(","); // Special case for masked and invisible (which are array of data) if (data.equals("masked") || data.equals("invisible")) { final String afterData = beginData.substring(beginData.indexOf("=") + 1); int toSpecialIndex = afterData.indexOf("="); if (toSpecialIndex < 0) return afterData.substring(0, afterData.length() - 1); while (afterData.charAt(toSpecialIndex) != ',') toSpecialIndex--; return afterData.substring(0, toSpecialIndex); } if (toIndex < 0) toIndex = beginData.indexOf("]"); if (toIndex < 0) return ""; return beginData.substring(beginData.indexOf("=") + 1, toIndex); } /** * @param context The context. * @param movesLudeme The Moves ludeme where come from the move. * @return Accumulated flags corresponding to the action/move concepts. */ public BitSet concepts(final Context context, final Moves movesLudeme); }
8,642
25.758514
117
java
Ludii
Ludii-master/Core/src/other/action/ActionType.java
package other.action; /** * The different type of actions. * * @author Eric.Piette */ public enum ActionType { /** Action to add a piece. */ Add, /** To Pass the move. */ Pass, /** To go to the next instance of a match. */ NextInstance, /** Noop, a fake action. */ Noop, /** Forfeit action. */ Forfeit, /** To send a message to a player. */ Note, /** To propose something to vote. */ Propose, /** To vote on a proposition done previously. */ Vote, /** To set the value of a player. */ SetValueOfPlayer, /** To set the trump suit in a card game. */ SetTrumpSuit, /** To use a specific die to make another move. */ UseDie, /** To use a specific die to make another move. */ SetDiceAllEqual, /** To set the state site and update the die value. */ SetStateAndUpdateDice, /** To set the cost of a graph element. */ SetCost, /** To set the phase of a graph element. */ SetPhase, /** To set visible a site to a player. */ SetVisible, /** To set masked a site to a player. */ SetMasked, /** To set invisible a site to a player. */ SetInvisible, /** To remove component(s) from a site. */ Remove, /** To select the from/to sites. */ Select, /** To select the from/to sites. */ Insert, /** To promote a piece. */ Promote, /** Add a player to a team. */ AddPlayerToTeam, /** To bet a value. */ Bet, /** To set the pot. */ SetPot, /** To set the amount of a player. */ SetAmount, /** To set the count of a site. */ SetCount, /** To move a piece from a site to another. */ Move, /** To move n piece(s) from a site to another. */ MoveN, /** To move a stack of piece(s) from a site to another. */ StackMove, /** To copy a piece from a site to another. */ Copy, /** To set hidden a site to a player. */ SetHidden, /** To set hidden count a site to a player. */ SetHiddenCount, /** To set hidden rotation a site to a player. */ SetHiddenRotation, /** To set hidden state a site to a player. */ SetHiddenState, /** To set hidden value a site to a player. */ SetHiddenValue, /** To set hidden What a site to a player. */ SetHiddenWhat, /** To set hidden Who a site to a player. */ SetHiddenWho, /** To set the counter. */ SetCounter, /** To set the next player. */ SetNextPlayer, /** To set the pending value. */ SetPending, /** To swap two players. */ Swap, /** To reset the possible values in a deduction puzzle. */ Reset, /** To set a value to a variable in a deduction puzzle. */ SetValuePuzzle, /** To toggle a value to a variable in a deduction puzzle. */ Toggle, /** To forget a value. */ Forget, /** To remember a value. */ Remember, /** To set the rotation. */ SetRotation, /** To set the value. */ SetValue, /** To set the local state. */ SetState, /** To set the score. */ SetScore, /** To set the temp value. */ SetTemp, /** To set a var. */ SetVar, /** To store the state. */ StoreState, /** To trigger an event. */ Trigger, }
3,021
16.268571
62
java
Ludii
Ludii-master/Core/src/other/action/BaseAction.java
package other.action; import java.util.BitSet; import java.util.List; import annotations.Hide; import game.rules.play.moves.Moves; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import main.Constants; import other.context.Context; import other.state.container.ContainerState; import other.topology.Cell; import other.topology.Topology; /** * Action with default return values. * * @author cambolbro and Eric.Piette */ @Hide public abstract class BaseAction implements Action { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** decision action or not. */ public boolean decision = false; //------------------------------------------------------------------------- @Override public int from() { return Constants.UNDEFINED; } @Override public SiteType fromType() { return SiteType.Cell; } @Override public int levelFrom() { return Constants.GROUND_LEVEL; } //------------------------------------------------------------------------- @Override public int to() { return Constants.UNDEFINED; } @Override public SiteType toType() { return SiteType.Cell; } @Override public int levelTo() { return Constants.GROUND_LEVEL; } //------------------------------------------------------------------------- @Override public int what() { return Constants.NO_PIECE; } @Override public int state() { return Constants.DEFAULT_STATE; } @Override public int rotation() { return Constants.DEFAULT_ROTATION; } @Override public int value() { return Constants.DEFAULT_ROTATION; } @Override public int count() { return Constants.NO_PIECE; } @Override public boolean isStacking() { return false; } @Override public boolean[] hidden() { return null; } @Override public int who() { return Constants.NOBODY; } @Override public boolean isDecision() { return decision; } @Override public boolean isPass() { return false; } @Override public boolean isForfeit() { return false; } @Override public boolean isSwap() { return false; } @Override public boolean isVote() { return false; } @Override public boolean isPropose() { return false; } @Override public boolean isAlwaysGUILegal() { return false; } @Override public String proposition() { return null; } @Override public String vote() { return null; } @Override public String message() { return null; } @Override public void setDecision(final boolean decision) { this.decision = decision; } @Override public Action withDecision(final boolean dec) { decision = dec; return this; } @Override public ActionType actionType() // TEMPORARY UNTIL ALL THE SUPER ACTIONS ARE NOT DONE. { return null; } @Override public boolean matchesUserMove(final int siteA, final int levelA, final SiteType graphElementTypeA, final int siteB, final int levelB, final SiteType graphElementTypeB) { return (from() == siteA && levelFrom() == levelA && fromType() == graphElementTypeA && to() == siteB && levelTo() == levelB && toType() == graphElementTypeB); } //------------------------------------------------------------------------- /** * To update the playable site with the line of play of the dominoes. * * @param context * @param site * @param dirn */ protected static void lineOfPlayDominoes(final Context context, final int site1, final int site2, final AbsoluteDirection dirn, final boolean doubleDomino, final boolean leftOrientation) { final ContainerState cs = context.containerState(0); final Topology topology = context.topology(); final Cell c1 = context.topology().cells().get(site1); final Cell c2 = context.topology().cells().get(site2); final List<Radial> radialsC1 = topology.trajectories().radials(SiteType.Cell, c1.index(), dirn); final List<Radial> radialsC2 = topology.trajectories().radials(SiteType.Cell, c2.index(), dirn); if (radialsC1.size() > 0 && radialsC2.size() > 0) { final Radial radialC1 = radialsC1.get(0); final Radial radialC2 = radialsC2.get(0); if (radialC1.steps().length > 2 && radialC2.steps().length > 2 && cs.isEmpty(radialC1.steps()[1].id(), SiteType.Cell) && cs.isEmpty(radialC2.steps()[1].id(), SiteType.Cell)) { for (int i = 1; i < radialC1.steps().length && i < radialC2.steps().length && i < 5; i++) { final int to = radialC1.steps()[i].id(); final int to2 = radialC2.steps()[i].id(); if (cs.isEmpty(to, SiteType.Cell) && cs.isEmpty(to2, SiteType.Cell)) { cs.setPlayable(context.state(), to, true); cs.setPlayable(context.state(), to2, true); if (!doubleDomino && i < 3) { final DirectionFacing direction = AbsoluteDirection.convert(dirn); final DirectionFacing leftDirection = direction.left().left(); final AbsoluteDirection absoluteLeftDirection = leftDirection.toAbsolute(); final DirectionFacing rightDirection = direction.right().right(); final AbsoluteDirection absoluteRightDirection = rightDirection.toAbsolute(); if (leftOrientation) { final List<Radial> radialsC1Left = topology.trajectories().radials(SiteType.Cell, c1.index(), absoluteLeftDirection); final List<Radial> radialsC2Right = topology.trajectories().radials(SiteType.Cell, c2.index(), absoluteRightDirection); if (radialsC1Left.size() > 0 && radialsC1Left.get(0).steps().length > 1) { final int leftOfTo = radialsC1Left.get(0).steps()[1].id(); if (cs.isEmpty(leftOfTo, SiteType.Cell)) cs.setPlayable(context.state(), leftOfTo, true); } if (radialsC2Right.size() > 0 && radialsC2Right.get(0).steps().length > 1) { final int leftOfTo = radialsC2Right.get(0).steps()[1].id(); if (cs.isEmpty(leftOfTo, SiteType.Cell)) cs.setPlayable(context.state(), leftOfTo, true); } } else { final List<Radial> radialsC1Right = topology.trajectories().radials(SiteType.Cell, c1.index(), absoluteRightDirection); final List<Radial> radialsC2Left = topology.trajectories().radials(SiteType.Cell, c2.index(), absoluteLeftDirection); if (radialsC1Right.size() > 0 && radialsC1Right.get(0).steps().length > 1) { final int leftOfTo = radialsC1Right.get(0).steps()[1].id(); if (cs.isEmpty(leftOfTo, SiteType.Cell)) cs.setPlayable(context.state(), leftOfTo, true); } if (radialsC2Left.size() > 0 && radialsC2Left.get(0).steps().length > 1) { final int leftOfTo = radialsC2Left.get(0).steps()[1].id(); if (cs.isEmpty(leftOfTo, SiteType.Cell)) cs.setPlayable(context.state(), leftOfTo, true); } } } } else return; } } } } /** * @param side * @param state * @return The direction of the line of play according to the side and the state * of the domino. */ @SuppressWarnings("static-method") protected AbsoluteDirection getDirnDomino(final int side, final int state) { switch (side) { case 0: // WEST SIDE switch (state) { case 0: return AbsoluteDirection.W; case 1: return AbsoluteDirection.N; case 2: return AbsoluteDirection.E; case 3: return AbsoluteDirection.S; } break; case 1: // NORTH SIDE switch (state) { case 0: return AbsoluteDirection.N; case 1: return AbsoluteDirection.E; case 2: return AbsoluteDirection.S; case 3: return AbsoluteDirection.W; } break; case 2: // EAST SIDE switch (state) { case 0: return AbsoluteDirection.E; case 1: return AbsoluteDirection.S; case 2: return AbsoluteDirection.W; case 3: return AbsoluteDirection.N; } break; case 3: // SOUTH SIDE switch (state) { case 0: return AbsoluteDirection.S; case 1: return AbsoluteDirection.W; case 2: return AbsoluteDirection.N; case 3: return AbsoluteDirection.E; } break; default: return null; } return null; } @Override public void setLevelFrom(final int levelA) { // do nothing in general. } @Override public void setLevelTo(final int levelB) { // do nothing in general. } @Override public boolean isOtherMove() { return false; } @Override public boolean isForced() { return false; } @Override public boolean containsNextInstance() { return false; } @Override public int playerSelected() { return Constants.UNDEFINED; } @Override public String toString() { return toTrialFormat(null); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return toTrialFormat(context); } @Override public BitSet concepts(final Context context, final Moves movesLudeme) { return new BitSet(); } }
9,101
20.118329
117
java
Ludii
Ludii-master/Core/src/other/action/cards/ActionSetTrumpSuit.java
package other.action.cards; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.component.SuitType; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Sets the trump suit for card games. * * @author Eric.Piette */ public class ActionSetTrumpSuit extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The new trump suit. */ private final int trumpSuit; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous trump suit. */ private int previousTrumpSuit; //------------------------------------------------------------------------- /** * @param trumpSuit The trump suit. */ public ActionSetTrumpSuit ( final int trumpSuit ) { this.trumpSuit = trumpSuit; } /** * Reconstructs an ActionSetTrumpSuit object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionSetTrumpSuit(final String detailedString) { assert (detailedString.startsWith("[SetTrumpSuit:")); final String strTrumpSuit = Action.extractData(detailedString, "trumpSuit"); trumpSuit = Integer.parseInt(strTrumpSuit); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if(!alreadyApplied) { previousTrumpSuit = context.state().trumpSuit(); alreadyApplied = true; } context.state().setTrumpSuit(trumpSuit); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().setTrumpSuit(previousTrumpSuit); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetTrumpSuit:"); sb.append("trumpSuit=" + trumpSuit); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + trumpSuit; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetTrumpSuit)) return false; final ActionSetTrumpSuit other = (ActionSetTrumpSuit) obj; return (trumpSuit == other.trumpSuit && decision == other.decision); } //------------------------------------------------------------------------- @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("TrumpSuit = " + SuitType.values()[trumpSuit]); return sb.toString(); } @Override public String getDescription() { return "SetTrumpSuit"; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(TrumpSuit = " + SuitType.values()[trumpSuit] + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public boolean isOtherMove() { return true; } @Override public ActionType actionType() { return ActionType.SetTrumpSuit; } @Override public int what() { return trumpSuit; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); if(decision) concepts.set(Concept.ChooseTrumpSuitDecision.id(), true); else concepts.set(Concept.SetTrumpSuit.id(), true); return concepts; } }
4,348
22.010582
123
java
Ludii
Ludii-master/Core/src/other/action/die/ActionSetDiceAllEqual.java
package other.action.die; import game.equipment.container.other.Dice; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; /** * Specifies to the state that all the dice are equals. * * @author Eric.Piette */ public final class ActionSetDiceAllEqual extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The value to set. */ private final boolean value; //----------------------Undo Data--------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value of DiceAllEqual. */ private boolean previousValue; //------------------------------------------------------------------------- /** * @param value The value to set. */ public ActionSetDiceAllEqual ( final boolean value ) { this.value = value; } /** * Reconstructs an ActionSetDiceAllEqual object from a detailed String * (generated using toDetailedString()) * * @param detailedString */ public ActionSetDiceAllEqual(final String detailedString) { assert (detailedString.startsWith("[SetDiceAllEqual:")); final String strValue = Action.extractData(detailedString, "value"); value = Boolean.parseBoolean(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if(!alreadyApplied) { previousValue = context.state().isDiceAllEqual(); alreadyApplied = true; } context.state().setDiceAllEqual(value); // To update the sum of the dice container. for (int i = 0; i < context.handDice().size(); i++) { final Dice dice = context.handDice().get(i); final int siteFrom = context.sitesFrom()[dice.index()]; final int siteTo = context.sitesFrom()[dice.index()] + dice.numSites(); int sum = 0; for (int site = siteFrom; site < siteTo; site++) sum += context.state().currentDice()[i][site - siteFrom]; context.state().sumDice()[i] = sum; } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().setDiceAllEqual(previousValue); // To update the sum of the dice container. for (int i = 0; i < context.handDice().size(); i++) { final Dice dice = context.handDice().get(i); final int siteFrom = context.sitesFrom()[dice.index()]; final int siteTo = context.sitesFrom()[dice.index()] + dice.numSites(); int sum = 0; for (int site = siteFrom; site < siteTo; site++) sum += context.state().currentDice()[i][site - siteFrom]; context.state().sumDice()[i] = sum; } return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetDiceAllEqual:"); sb.append("value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + (value ? 1231 : 1237); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetDiceAllEqual)) return false; final ActionSetDiceAllEqual other = (ActionSetDiceAllEqual) obj; return (decision == other.decision && value == other.value); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetDiceAllEqual"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { if (value) return "Dice Equal"; return "Dice Not Equal"; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { if (value) return "(Dice Equal)"; return "(Dice Not Equal)"; } //------------------------------------------------------------------------- @Override public ActionType actionType() { return ActionType.SetDiceAllEqual; } }
4,604
24.027174
123
java
Ludii
Ludii-master/Core/src/other/action/die/ActionUpdateDice.java
package other.action.die; import java.util.BitSet; import game.equipment.container.other.Dice; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Sets the state of the site where is the die and update the value of the * die. * * @author Eric.Piette */ public final class ActionUpdateDice extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Site index. */ private final int site; /** The new state value. */ private final int newState; //----------------------Undo Data--------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyAppliedState = false; /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyAppliedValue = false; /** The previous state of the die. */ private int previousState; /** The previous value of the die. */ private int previousDieValue; //------------------------------------------------------------------------- /** * Constructor. * * @param site The index of the site. * @param newState The new state value. */ public ActionUpdateDice ( final int site, final int newState ) { this.site = site; this.newState = newState; } /** * Reconstructs an ActionSetStateAndUpdateDice object from a detailed String * (generated using toDetailedString()) * * @param detailedString */ public ActionUpdateDice(final String detailedString) { assert (detailedString.startsWith("[SetStateAndUpdateDice:")); final String strSite = Action.extractData(detailedString, "site"); site = Integer.parseInt(strSite); final String strState = Action.extractData(detailedString, "state"); newState = Integer.parseInt(strState); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if(newState < 0) return this; final int cid = context.containerId()[site]; final ContainerState cs = context.state().containerStates()[cid]; if(!alreadyAppliedState) { previousState = cs.state(site, SiteType.Cell); alreadyAppliedState = true; } cs.setSite(context.state(), site, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, newState, Constants.UNDEFINED, Constants.UNDEFINED, SiteType.Cell); if (context.containers()[cid].isDice()) { final Dice dice = (Dice) context.containers()[cid]; int indexDice = 0; for (int i = 0; i < context.handDice().size(); i++) { final Dice d = context.handDice().get(i); if (d.index() == dice.index()) { indexDice = i; break; } } final int from = context.sitesFrom()[cid]; final int what = cs.whatCell(site); final int dieIndex = site - from; if(!alreadyAppliedValue) { previousDieValue = context.state().currentDice()[indexDice][dieIndex]; alreadyAppliedValue = true; } context.state().currentDice()[indexDice][dieIndex] = context.components()[what].getFaces()[newState]; } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { if(newState < 0) return this; final int cid = context.containerId()[site]; final ContainerState cs = context.state().containerStates()[cid]; cs.setSite(context.state(), site, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, previousState, Constants.UNDEFINED, Constants.UNDEFINED, SiteType.Cell); if (context.containers()[cid].isDice()) { final Dice dice = (Dice) context.containers()[cid]; int indexDice = 0; for (int i = 0; i < context.handDice().size(); i++) { final Dice d = context.handDice().get(i); if (d.index() == dice.index()) { indexDice = i; break; } } final int from = context.sitesFrom()[cid]; final int dieIndex = site - from; context.state().currentDice()[indexDice][dieIndex] = previousDieValue; } return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + site; result = prime * result + newState; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionUpdateDice)) return false; final ActionUpdateDice other = (ActionUpdateDice) obj; return (decision == other.decision && site == other.site && newState == other.newState); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetStateAndUpdateDice:"); sb.append("site=" + site); sb.append(",state=" + newState); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetStateAndUpdateDice"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Die " + site + "=" + newState; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Die at " + site + " state=" + newState + ")"; } //------------------------------------------------------------------------- @Override public int from() { return site; } @Override public int to() { return site; } @Override public int state() { return newState; } @Override public int who() { return newState; } @Override public ActionType actionType() { return ActionType.SetStateAndUpdateDice; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.Roll.id(), true); return concepts; } }
6,776
23.290323
123
java
Ludii
Ludii-master/Core/src/other/action/die/ActionUseDie.java
package other.action.die; import java.util.BitSet; import game.rules.play.moves.Moves; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Uses a die and remove it from the current dice of the context. * * @author Eric.Piette */ public class ActionUseDie extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Hand Dice index. */ private final int indexHandDice; /** Index Die. */ private final int indexDie; /** Index of the site. */ private final int site; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous dice value. */ private int previousCurrentDieValue; //------------------------------------------------------------------------- /** * @param indexHandDice The index of the hand dice. * @param indexDie The index of the die in this hand. * @param toIndex The index of the die. */ public ActionUseDie ( final int indexHandDice, final int indexDie, final int toIndex ) { this.indexHandDice = indexHandDice; this.indexDie = indexDie; this.site = toIndex; } /** * Reconstructs an ActionUseDie object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionUseDie(final String detailedString) { assert (detailedString.startsWith("[UseDie:")); final String strIndexDie = Action.extractData(detailedString, "indexDie"); indexDie = Integer.parseInt(strIndexDie); final String strIndexHandDice = Action.extractData(detailedString, "indexHandDice"); indexHandDice = Integer.parseInt(strIndexHandDice); final String strSite = Action.extractData(detailedString, "site"); site = Integer.parseInt(strSite); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if(!alreadyApplied) { previousCurrentDieValue = context.state().currentDice()[indexHandDice][indexDie]; alreadyApplied = true; } context.state().updateCurrentDice(0, indexDie, indexHandDice); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().updateCurrentDice(previousCurrentDieValue, indexDie, indexHandDice); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[UseDie:"); sb.append("indexHandDice=" + indexHandDice); sb.append(",indexDie=" + indexDie); sb.append(",site=" + site); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + indexHandDice; result = prime * result + indexDie; result = prime * result + site; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionUseDie)) return false; final ActionUseDie other = (ActionUseDie) obj; return (indexHandDice == other.indexHandDice && indexDie == other.indexDie && site == other.site && decision == other.decision); } //------------------------------------------------------------------------- @Override public String getDescription() { return "UseDie"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Die " + site; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Die at " + site + " is used)"; } //------------------------------------------------------------------------- @Override public int from() { return site; } @Override public int to() { return site; } /** * @return The index of the hand of dice. */ public int indexHandDice() { return this.indexHandDice; } /** * @return The index of the die. */ public int indexDie() { return this.indexDie; } @Override public ActionType actionType() { return ActionType.UseDie; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.ByDieMove.id(), true); return concepts; } }
5,069
22.150685
123
java
Ludii
Ludii-master/Core/src/other/action/graph/ActionSetCost.java
package other.action.graph; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Sets the cost of a graph element. * * @author Eric.Piette */ public final class ActionSetCost extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the graph element. */ private final int to; /** The cost to set. */ private final int cost; /** The type of the graph element. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous cost. */ private int previousCost; //------------------------------------------------------------------------- /** * @param type The graph element. * @param to The index of the site. * @param cost The cost. */ public ActionSetCost ( final SiteType type, final int to, final int cost ) { this.type = type; this.to = to; this.cost = cost; } /** * Reconstructs an ActionSetCost object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionSetCost(final String detailedString) { assert (detailedString.startsWith("[SetCost:")); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strCost = Action.extractData(detailedString, "cost"); cost = Integer.parseInt(strCost); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; if(!alreadyApplied) { previousCost = context.topology().getGraphElements(type).get(to).cost(); alreadyApplied = true; } context.topology().getGraphElements(type).get(to).setCost(cost); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { type = (type == null) ? context.board().defaultSite() : type; context.topology().getGraphElements(type).get(to).setCost(previousCost); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetCost:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); sb.append(",cost=" + cost); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetCost)) return false; final ActionSetCost other = (ActionSetCost) obj; return (decision == other.decision && to == other.to && cost == other.cost && type.equals(other.type)); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetCost"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append("=$" + cost); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Cost at "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append(" = " + cost + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return to; } @Override public int to() { return to; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public ActionType actionType() { return ActionType.SetCost; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetCost.id(), true); return concepts; } }
6,206
22.334586
123
java
Ludii
Ludii-master/Core/src/other/action/graph/ActionSetPhase.java
package other.action.graph; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Sets the phase of a graph element. * * @author Eric.Piette */ public final class ActionSetPhase extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The site with the new phase. */ private final int to; /** The phase to set. */ private final int phase; /** The type of the graph element. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous phase. */ private int previousPhase; //------------------------------------------------------------------------- /** * @param type The graph element type. * @param to The site. * @param phase The number of the phase. */ public ActionSetPhase ( final SiteType type, final int to, final int phase ) { this.type = type; this.to = to; this.phase = phase; } /** * Reconstructs an ActionSetPhase object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionSetPhase(final String detailedString) { assert (detailedString.startsWith("[SetPhase:")); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strPhase = Action.extractData(detailedString, "phase"); phase = Integer.parseInt(strPhase); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; if(!alreadyApplied) { previousPhase = context.topology().getGraphElements(type).get(to).phase(); alreadyApplied = true; } context.topology().getGraphElements(type).get(to).setPhase(phase); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { type = (type == null) ? context.board().defaultSite() : type; context.topology().getGraphElements(type).get(to).setPhase(previousPhase); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetPhase:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); sb.append(",phase=" + phase); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetPhase)) return false; final ActionSetPhase other = (ActionSetPhase) obj; return (decision == other.decision && to == other.to && phase == other.phase); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetPhase"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append("=%" + phase); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Phase at "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append(" = " + phase + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public int from() { return to; } @Override public int to() { return to; } @Override public ActionType actionType() { return ActionType.SetPhase; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetPhase.id(), true); return concepts; } }
6,224
22.402256
123
java
Ludii
Ludii-master/Core/src/other/action/hidden/ActionSetHidden.java
package other.action.hidden; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Sets the hidden information to a graph element type at a specific level for a * specific player. * * @author Eric.Piette */ public final class ActionSetHidden extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the graph element. */ private final int to; /** The cost to set. */ private int level = Constants.UNDEFINED; /** The value to set */ private final boolean value; /** The id of the player */ private final int who; /** The type of the graph element. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private boolean previousValue; /** The previous site type. */ private SiteType previousType; //------------------------------------------------------------------------- /** * @param who The player index. * @param type The graph element. * @param to The index of the site. * @param level The level. * @param value The value to set. */ public ActionSetHidden ( final int who, final SiteType type, final int to, final int level, final boolean value ) { this.type = type; this.to = to; this.who = who; this.level = level; this.value = value; } /** * Reconstructs an ActionSetHidden object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionSetHidden(final String detailedString) { assert (detailedString.startsWith("[SetHidden:")); final String strWho = Action.extractData(detailedString, "who"); who = Integer.parseInt(strWho); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = (strLevel.isEmpty()) ? 0 : Integer.parseInt(strLevel); final String strValue = Action.extractData(detailedString, "value"); value = Boolean.parseBoolean(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; if(!alreadyApplied) { final int cid = to >= context.containerId().length ? 0 : context.containerId()[to]; final ContainerState cs = context.state().containerStates()[cid]; previousValue = cs.isHidden(who, to, level, type); previousType = type; alreadyApplied = true; } context.containerState(context.containerId()[to]).setHidden(context.state(), who, to, level, type, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.containerState(context.containerId()[to]).setHidden(context.state(), who, to, level, previousType, previousValue); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetHidden:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (level != Constants.UNDEFINED) sb.append(",level=" + level); sb.append(",who=" + who); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + (value ? 1231 : 1237); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + who; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetHidden)) return false; final ActionSetHidden other = (ActionSetHidden) obj; return (decision == other.decision && to == other.to && value == other.value && who == other.who && value == other.value && type.equals(other.type)); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetHidden"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append("P" + who); if (value) sb.append("=Hidden"); else sb.append("!=Hidden"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Hidden at "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append(" to P" + who); sb.append(" = " + value + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int levelTo() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public ActionType actionType() { return ActionType.SetHidden; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetInvisible.id(), true); return concepts; } }
7,943
23.747664
124
java
Ludii
Ludii-master/Core/src/other/action/hidden/ActionSetHiddenCount.java
package other.action.hidden; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Sets the count hidden information to a graph element type at a specific level * for a specific player. * * @author Eric.Piette */ public final class ActionSetHiddenCount extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the graph element. */ private final int to; /** The cost to set. */ private int level = Constants.UNDEFINED; /** The value to set */ private final boolean value; /** The id of the player */ private final int who; /** The type of the graph element. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private boolean previousValue; /** The previous site type. */ private SiteType previousType; //------------------------------------------------------------------------- /** * @param who The player index. * @param type The graph element. * @param to The index of the site. * @param level The level. * @param value The value to set. */ public ActionSetHiddenCount(final int who, final SiteType type, final int to, final int level, final boolean value) { this.type = type; this.to = to; this.who = who; this.level = level; this.value = value; } /** * Reconstructs an ActionSetHiddenCount object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionSetHiddenCount(final String detailedString) { assert (detailedString.startsWith("[SetHiddenCount:")); final String strWho = Action.extractData(detailedString, "who"); who = Integer.parseInt(strWho); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = (strLevel.isEmpty()) ? 0 : Integer.parseInt(strLevel); final String strValue = Action.extractData(detailedString, "value"); value = Boolean.parseBoolean(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; if(!alreadyApplied) { final int cid = to >= context.containerId().length ? 0 : context.containerId()[to]; final ContainerState cs = context.state().containerStates()[cid]; previousValue = cs.isHiddenCount(who, to, level, type); previousType = type; alreadyApplied = true; } context.containerState(context.containerId()[to]).setHiddenCount(context.state(), who, to, level, type, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.containerState(context.containerId()[to]).setHiddenCount(context.state(), who, to, level, previousType, previousValue); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetHiddenCount:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (level != Constants.UNDEFINED) sb.append(",level=" + level); sb.append(",who=" + who); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + (value ? 1231 : 1237); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + who; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetHiddenCount)) return false; final ActionSetHiddenCount other = (ActionSetHiddenCount) obj; return (decision == other.decision && to == other.to && value == other.value && who == other.who && value == other.value && type.equals(other.type)); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetHiddenCount"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append("P" + who); if (value) sb.append("=HiddenCount"); else sb.append("!=HiddenCount"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(HiddenCount at "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append(" to P" + who); sb.append(" = " + value + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int levelTo() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public ActionType actionType() { return ActionType.SetHiddenCount; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetHiddenCount.id(), true); return concepts; } }
8,021
24.466667
129
java
Ludii
Ludii-master/Core/src/other/action/hidden/ActionSetHiddenRotation.java
package other.action.hidden; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Sets the rotation hidden information to a graph element type at a specific * level for a specific player. * * @author Eric.Piette */ public final class ActionSetHiddenRotation extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the graph element. */ private final int to; /** The cost to set. */ private int level = Constants.UNDEFINED; /** The value to set */ private final boolean value; /** The id of the player */ private final int who; /** The type of the graph element. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private boolean previousValue; /** The previous site type. */ private SiteType previousType; //------------------------------------------------------------------------- /** * @param who The player index. * @param type The graph element. * @param to The index of the site. * @param level The level. * @param value The value to set. */ public ActionSetHiddenRotation(final int who, final SiteType type, final int to, final int level, final boolean value) { this.type = type; this.to = to; this.who = who; this.level = level; this.value = value; } /** * Reconstructs an ActionSetHiddenRotation object from a detailed String * (generated using toDetailedString()) * * @param detailedString */ public ActionSetHiddenRotation(final String detailedString) { assert (detailedString.startsWith("[SetHiddenRotation:")); final String strWho = Action.extractData(detailedString, "who"); who = Integer.parseInt(strWho); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = (strLevel.isEmpty()) ? 0 : Integer.parseInt(strLevel); final String strValue = Action.extractData(detailedString, "value"); value = Boolean.parseBoolean(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; if(!alreadyApplied) { final int cid = to >= context.containerId().length ? 0 : context.containerId()[to]; final ContainerState cs = context.state().containerStates()[cid]; previousValue = cs.isHiddenRotation(who, to, level, type); previousType = type; alreadyApplied = true; } context.containerState(context.containerId()[to]).setHiddenRotation(context.state(), who, to, level, type, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.containerState(context.containerId()[to]).setHiddenRotation(context.state(), who, to, level, previousType, previousValue); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetHiddenRotation:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (level != Constants.UNDEFINED) sb.append(",level=" + level); sb.append(",who=" + who); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + (value ? 1231 : 1237); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + who; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetHiddenRotation)) return false; final ActionSetHiddenRotation other = (ActionSetHiddenRotation) obj; return (decision == other.decision && to == other.to && value == other.value && who == other.who && value == other.value && type.equals(other.type)); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetHiddenRotation"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append("P" + who); if (value) sb.append("=HiddenRotation"); else sb.append("!=HiddenRotation"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(HiddenRotation at "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append(" to P" + who); sb.append(" = " + value + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int levelTo() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public ActionType actionType() { return ActionType.SetHiddenRotation; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetHiddenRotation.id(), true); return concepts; } }
8,080
24.572785
132
java
Ludii
Ludii-master/Core/src/other/action/hidden/ActionSetHiddenState.java
package other.action.hidden; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Sets the state hidden information to a graph element type at a specific * level for a specific player. * * @author Eric.Piette */ public final class ActionSetHiddenState extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the graph element. */ private final int to; /** The cost to set. */ private int level = Constants.UNDEFINED; /** The value to set */ private final boolean value; /** The id of the player */ private final int who; /** The type of the graph element. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private boolean previousValue; /** The previous site type. */ private SiteType previousType; //------------------------------------------------------------------------- /** * @param who The player index. * @param type The graph element. * @param to The index of the site. * @param level The level. * @param value The value to set. */ public ActionSetHiddenState(final int who, final SiteType type, final int to, final int level, final boolean value) { this.type = type; this.to = to; this.who = who; this.level = level; this.value = value; } /** * Reconstructs an ActionSetHiddenState object from a detailed String * (generated using toDetailedString()) * * @param detailedString */ public ActionSetHiddenState(final String detailedString) { assert (detailedString.startsWith("[SetHiddenState:")); final String strWho = Action.extractData(detailedString, "who"); who = Integer.parseInt(strWho); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = (strLevel.isEmpty()) ? 0 : Integer.parseInt(strLevel); final String strValue = Action.extractData(detailedString, "value"); value = Boolean.parseBoolean(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; if(!alreadyApplied) { final int cid = to >= context.containerId().length ? 0 : context.containerId()[to]; final ContainerState cs = context.state().containerStates()[cid]; previousValue = cs.isHiddenState(who, to, level, type); previousType = type; alreadyApplied = true; } context.containerState(context.containerId()[to]).setHiddenState(context.state(), who, to, level, type, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.containerState(context.containerId()[to]).setHiddenState(context.state(), who, to, level, previousType, previousValue); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetHiddenState:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (level != Constants.UNDEFINED) sb.append(",level=" + level); sb.append(",who=" + who); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + (value ? 1231 : 1237); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + who; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetHiddenState)) return false; final ActionSetHiddenState other = (ActionSetHiddenState) obj; return (decision == other.decision && to == other.to && value == other.value && who == other.who && value == other.value && type.equals(other.type)); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetHiddenState"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append("P" + who); if (value) sb.append("=HiddenState"); else sb.append("!=HiddenState"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(HiddenState at "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append(" to P" + who); sb.append(" = " + value + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int levelTo() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public ActionType actionType() { return ActionType.SetHiddenState; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetHiddenState.id(), true); return concepts; } }
8,022
24.389241
129
java
Ludii
Ludii-master/Core/src/other/action/hidden/ActionSetHiddenValue.java
package other.action.hidden; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Sets the value hidden information to a graph element type at a specific level * for a specific player. * * @author Eric.Piette */ public final class ActionSetHiddenValue extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the graph element. */ private final int to; /** The cost to set. */ private int level = Constants.UNDEFINED; /** The value to set */ private final boolean value; /** The id of the player */ private final int who; /** The type of the graph element. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private boolean previousValue; /** The previous site type. */ private SiteType previousType; //------------------------------------------------------------------------- /** * @param who The player index. * @param type The graph element. * @param to The index of the site. * @param level The level. * @param value The value to set. */ public ActionSetHiddenValue(final int who, final SiteType type, final int to, final int level, final boolean value) { this.type = type; this.to = to; this.who = who; this.level = level; this.value = value; } /** * Reconstructs an ActionSetHiddenValue object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionSetHiddenValue(final String detailedString) { assert (detailedString.startsWith("[SetHiddenValue:")); final String strWho = Action.extractData(detailedString, "who"); who = Integer.parseInt(strWho); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = (strLevel.isEmpty()) ? 0 : Integer.parseInt(strLevel); final String strValue = Action.extractData(detailedString, "value"); value = Boolean.parseBoolean(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; if(!alreadyApplied) { final int cid = to >= context.containerId().length ? 0 : context.containerId()[to]; final ContainerState cs = context.state().containerStates()[cid]; previousValue = cs.isHiddenValue(who, to, level, type); previousType = type; alreadyApplied = true; } context.containerState(context.containerId()[to]).setHiddenValue(context.state(), who, to, level, type, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.containerState(context.containerId()[to]).setHiddenValue(context.state(), who, to, level, previousType, previousValue); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetHiddenValue:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (level != Constants.UNDEFINED) sb.append(",level=" + level); sb.append(",who=" + who); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + (value ? 1231 : 1237); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + who; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetHiddenValue)) return false; final ActionSetHiddenValue other = (ActionSetHiddenValue) obj; return (decision == other.decision && to == other.to && value == other.value && who == other.who && value == other.value && type.equals(other.type)); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetHiddenValue"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append("P" + who); if (value) sb.append("=HiddenValue"); else sb.append("!=HiddenValue"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(HiddenValue at "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append(" to P" + who); sb.append(" = " + value + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int levelTo() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public ActionType actionType() { return ActionType.SetHiddenValue; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetHiddenValue.id(), true); return concepts; } }
8,019
24.460317
129
java
Ludii
Ludii-master/Core/src/other/action/hidden/ActionSetHiddenWhat.java
package other.action.hidden; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Sets the what hidden information to a graph element type at a specific level * for a specific player. * * @author Eric.Piette */ public final class ActionSetHiddenWhat extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the graph element. */ private final int to; /** The cost to set. */ private int level = Constants.UNDEFINED; /** The value to set */ private final boolean value; /** The id of the player */ private final int who; /** The type of the graph element. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private boolean previousValue; /** The previous site type. */ private SiteType previousType; //------------------------------------------------------------------------- /** * @param who The player index. * @param type The graph element. * @param to The index of the site. * @param level The level. * @param value The value to set. */ public ActionSetHiddenWhat(final int who, final SiteType type, final int to, final int level, final boolean value) { this.type = type; this.to = to; this.who = who; this.level = level; this.value = value; } /** * Reconstructs an ActionSetHiddenWhat object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionSetHiddenWhat(final String detailedString) { assert (detailedString.startsWith("[SetHiddenWhat:")); final String strWho = Action.extractData(detailedString, "who"); who = Integer.parseInt(strWho); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = (strLevel.isEmpty()) ? 0 : Integer.parseInt(strLevel); final String strValue = Action.extractData(detailedString, "value"); value = Boolean.parseBoolean(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; if(!alreadyApplied) { final int cid = to >= context.containerId().length ? 0 : context.containerId()[to]; final ContainerState cs = context.state().containerStates()[cid]; previousValue = cs.isHiddenWhat(who, to, level, type); previousType = type; alreadyApplied = true; } context.containerState(context.containerId()[to]).setHiddenWhat(context.state(), who, to, level, type, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.containerState(context.containerId()[to]).setHiddenWhat(context.state(), who, to, level, previousType, previousValue); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetHiddenWhat:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (level != Constants.UNDEFINED) sb.append(",level=" + level); sb.append(",who=" + who); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + (value ? 1231 : 1237); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + who; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetHiddenWhat)) return false; final ActionSetHiddenWhat other = (ActionSetHiddenWhat) obj; return (decision == other.decision && to == other.to && value == other.value && who == other.who && value == other.value && type.equals(other.type)); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetHiddenWhat"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append("P" + who); if (value) sb.append("=HiddenWhat"); else sb.append("!=HiddenWhat"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(HiddenWhat at "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append(" to P" + who); sb.append(" = " + value + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int levelTo() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public ActionType actionType() { return ActionType.SetHiddenWhat; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetHiddenWhat.id(), true); return concepts; } }
7,999
24.396825
128
java
Ludii
Ludii-master/Core/src/other/action/hidden/ActionSetHiddenWho.java
package other.action.hidden; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Sets the what hidden information to a graph element type at a specific level * for a specific player. * * @author Eric.Piette */ public final class ActionSetHiddenWho extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the graph element. */ private final int to; /** The cost to set. */ private int level = Constants.UNDEFINED; /** The value to set */ private final boolean value; /** The id of the player */ private final int who; /** The type of the graph element. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private boolean previousValue; /** The previous site type. */ private SiteType previousType; //------------------------------------------------------------------------- /** * @param who The player index. * @param type The graph element. * @param to The index of the site. * @param level The level. * @param value The value to set. */ public ActionSetHiddenWho(final int who, final SiteType type, final int to, final int level, final boolean value) { this.type = type; this.to = to; this.who = who; this.level = level; this.value = value; } /** * Reconstructs an ActionSetHiddenWho object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionSetHiddenWho(final String detailedString) { assert (detailedString.startsWith("[SetHiddenWho:")); final String strWho = Action.extractData(detailedString, "who"); who = Integer.parseInt(strWho); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = (strLevel.isEmpty()) ? 0 : Integer.parseInt(strLevel); final String strValue = Action.extractData(detailedString, "value"); value = Boolean.parseBoolean(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; if(!alreadyApplied) { final int cid = to >= context.containerId().length ? 0 : context.containerId()[to]; final ContainerState cs = context.state().containerStates()[cid]; previousValue = cs.isHiddenWho(who, to, level, type); previousType = type; alreadyApplied = true; } context.containerState(context.containerId()[to]).setHiddenWho(context.state(), who, to, level, type, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.containerState(context.containerId()[to]).setHiddenWho(context.state(), who, to, level, previousType, previousValue); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetHiddenWho:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (level != Constants.UNDEFINED) sb.append(",level=" + level); sb.append(",who=" + who); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + (value ? 1231 : 1237); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + who; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetHiddenWho)) return false; final ActionSetHiddenWho other = (ActionSetHiddenWho) obj; return (decision == other.decision && to == other.to && value == other.value && who == other.who && value == other.value && type.equals(other.type)); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetHiddenWho"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append("P" + who); if (value) sb.append("=HiddenWho"); else sb.append("!=HiddenWho"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(HiddenWho at "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append(" to P" + who); sb.append(" = " + value + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int levelTo() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public ActionType actionType() { return ActionType.SetHiddenWho; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetHiddenWho.id(), true); return concepts; } }
7,982
24.342857
127
java
Ludii
Ludii-master/Core/src/other/action/move/ActionAdd.java
package other.action.move; import java.util.BitSet; import game.Game; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.SiteType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; /** * Add one or more piece(s) to a site. * * @author Eric.Piette */ public final class ActionAdd extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The type of the graph element. */ private SiteType type; /** Location index. */ private final int to; /** Item index */ private final int what; /** Count. */ private final int count; /** The site state. */ private final int state; /** The rotation state. */ private final int rotation; /** The value of the piece. */ private final int value; /** True if the pieces have to be added in a stack. */ private final boolean onStack; /** The level to add the piece in case of a stack. */ private int level = Constants.UNDEFINED; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** Previous What value of the site. */ private int[] previousWhat; /** Previous Who value of the site. */ private int[] previousWho; /** Previous Site state value of the site. */ private int[] previousState; /** Previous Rotation value of the site. */ private int[] previousRotation; /** Previous Piece value of the site. */ private int[] previousValue; /** Previous Piece count of the site. */ private int previousCount; /** The previous hidden info values of the site before to be removed. */ private boolean[][] previousHidden; /** The previous hidden what info values of the site before to be removed. */ private boolean[][] previousHiddenWhat; /** The previous hidden who info values of the site before to be removed. */ private boolean[][] previousHiddenWho; /** The previous hidden count info values of the site before to be removed. */ private boolean[][] previousHiddenCount; /** The previous hidden rotation info values of the site before to be removed. */ private boolean[][] previousHiddenRotation; /** The previous hidden State info values of the site before to be removed. */ private boolean[][] previousHiddenState; /** The previous hidden Value info values of the site before to be removed. */ private boolean[][] previousHiddenValue; //------------------------------------------------------------------------- private boolean actionLargePiece = false; //------------------------------------------------------------------------- /** * @param type The type of the graph element. * @param to The site to add component to. * @param what The index of the item. * @param count The number of item to place. * @param state The state of the site to modify. * @param rotation The rotation state of the site. * @param value The piece value of the site. * @param onStacking True we add the pieces in a stack. */ public ActionAdd ( final SiteType type, final int to, final int what, final int count, final int state, final int rotation, final int value, final Boolean onStacking ) { this.to = to; this.what = what; this.count = count; this.state = state; this.rotation = rotation; this.onStack = (onStacking == null) ? false : onStacking.booleanValue(); this.type = type; this.value = value; } /** * Reconstructs an ActionAdd object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionAdd(final String detailedString) { assert (detailedString.startsWith("[Add:")); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = (strLevel.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevel); final String strWhat = Action.extractData(detailedString, "what"); what = Integer.parseInt(strWhat); final String strCount = Action.extractData(detailedString, "count"); count = (strCount.isEmpty()) ? 1 : Integer.parseInt(strCount); final String strState = Action.extractData(detailedString, "state"); state = (strState.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strState); final String strRotation = Action.extractData(detailedString, "rotation"); rotation = (strRotation.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strRotation); final String strValue = Action.extractData(detailedString, "value"); value = (strValue.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strValue); final String strStack = Action.extractData(detailedString, "stack"); onStack = (strStack.isEmpty()) ? false : Boolean.parseBoolean(strStack); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if (to < 0) return this; type = (type == null) ? context.board().defaultSite() : type; // If the site is not supported by the type, that's a cell of another container. if (to >= context.board().topology().getGraphElements(type).size()) type = SiteType.Cell; final Game game = context.game(); final int contID = (type == SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contID]; final int who = (what < 1) ? 0 : context.components()[what].owner(); final boolean requiresStack = game.isStacking(); final boolean hiddenInfoGame = game.hiddenInformation(); // Keep in memory the data of the site from and to (for undo method) if (!alreadyApplied) { if (!requiresStack) { previousCount = cs.count(to, type); previousWhat = new int[1]; previousWho = new int[1]; previousState = new int[1]; previousRotation = new int[1]; previousValue = new int[1]; previousWhat[0] = cs.what(to, 0, type); previousWho[0] = cs.who(to, 0, type); previousState[0] = cs.state(to, 0, type); previousRotation[0] = cs.rotation(to, 0, type); previousValue[0] = cs.value(to, 0, type); if (hiddenInfoGame) { previousHidden = new boolean[1][context.players().size()]; previousHiddenWhat = new boolean[1][context.players().size()]; previousHiddenWho = new boolean[1][context.players().size()]; previousHiddenCount = new boolean[1][context.players().size()]; previousHiddenRotation = new boolean[1][context.players().size()]; previousHiddenState = new boolean[1][context.players().size()]; previousHiddenValue = new boolean[1][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHidden[0][pid] = cs.isHidden(pid, to, 0, type); previousHiddenWhat[0][pid] = cs.isHiddenWhat(pid, to, 0, type); previousHiddenWho[0][pid] = cs.isHiddenWho(pid, to, 0, type); previousHiddenCount[0][pid] = cs.isHiddenCount(pid, to, 0, type); previousHiddenState[0][pid] = cs.isHiddenState(pid, to, 0, type); previousHiddenRotation[0][pid] = cs.isHiddenRotation(pid, to, 0, type); previousHiddenValue[0][pid] = cs.isHiddenValue(pid, to, 0, type); } } } else // Stacking game. { final int sizeStackTo = cs.sizeStack(to, type); previousWhat = new int[sizeStackTo]; previousWho = new int[sizeStackTo]; previousState = new int[sizeStackTo]; previousRotation = new int[sizeStackTo]; previousValue = new int[sizeStackTo]; for (int lvl = 0 ; lvl < sizeStackTo; lvl++) { previousWhat[lvl] = cs.what(to, lvl, type); previousWho[lvl] = cs.who(to, lvl, type); previousState[lvl] = cs.state(to, lvl, type); previousRotation[lvl] = cs.rotation(to, lvl, type); previousValue[lvl] = cs.value(to, lvl, type); if (hiddenInfoGame) { previousHidden = new boolean[sizeStackTo][context.players().size()]; previousHiddenWhat = new boolean[sizeStackTo][context.players().size()]; previousHiddenWho = new boolean[sizeStackTo][context.players().size()]; previousHiddenCount = new boolean[sizeStackTo][context.players().size()]; previousHiddenRotation = new boolean[sizeStackTo][context.players().size()]; previousHiddenState = new boolean[sizeStackTo][context.players().size()]; previousHiddenValue = new boolean[sizeStackTo][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHidden[lvl][pid] = cs.isHidden(pid, to, lvl, type); previousHiddenWhat[lvl][pid] = cs.isHiddenWhat(pid, to, lvl, type); previousHiddenWho[lvl][pid] = cs.isHiddenWho(pid, to, lvl, type); previousHiddenCount[lvl][pid] = cs.isHiddenCount(pid, to, lvl, type); previousHiddenState[lvl][pid] = cs.isHiddenState(pid, to, lvl, type); previousHiddenRotation[lvl][pid] = cs.isHiddenRotation(pid, to, lvl, type); previousHiddenValue[lvl][pid] = cs.isHiddenValue(pid, to, lvl, type); } } } } alreadyApplied = true; } if (requiresStack) applyStack(context, cs); int currentWhat = 0; currentWhat = cs.what(to, type); if (currentWhat == 0) { cs.setSite(context.state(), to, who, what, count, state, rotation, (game.hasDominoes() ? 1 : value), type); Component piece = null; // to keep the site of the item in cache for each player if (what != 0) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, type); if (piece.isDomino()) context.state().remainingDominoes().remove(piece.index()); } // If large piece we need to update the other sites used by the large piece. applyLargePiece(context, piece, cs); } else { final int oldCount = cs.count(to, type); cs.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, (game.requiresCount() ? oldCount + count : 1), state, rotation, value,type); } updateTrackIndices(context); return this; } /** * Add a piece to a stack. * * @param context The context. * @param cs The container state. */ public void applyStack(final Context context, final ContainerState cs) { final int who = (what < 1) ? 0 : context.components()[what].owner(); level = cs.sizeStack(to, type); Component piece = null; if (state != Constants.UNDEFINED || rotation != Constants.UNDEFINED || value != Constants.UNDEFINED) { cs.addItemGeneric(context.state(), to, what, who, (state == Constants.UNDEFINED) ? 0 : state, (rotation == Constants.UNDEFINED) ? 0 : rotation, (value == Constants.UNDEFINED) ? 0 : value, context.game(), type); } else { cs.addItemGeneric(context.state(), to, what, who, context.game(), type); } cs.removeFromEmpty(to, type); if (what != 0) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, cs.sizeStack(to, type) - 1, type); } updateTrackIndices(context); } /** * We update the state in case of a large piece. * * @param context The context. * @param piece The piece. * @param cs The container state. */ public void applyLargePiece(final Context context, final Component piece, final ContainerState cs) { actionLargePiece = true; if (piece != null && piece.isLargePiece() && to < context.containers()[0].numSites()) { final Component largePiece = piece; final TIntArrayList locs = largePiece.locs(context, to, state, context.topology()); for (int i = 0; i < locs.size(); i++) { cs.removeFromEmpty(locs.getQuick(i), SiteType.Cell); cs.setCount(context.state(), locs.getQuick(i), 1); } if (largePiece.isDomino()) { for (int i = 0; i < 4; i++) { cs.setValueCell(context.state(), locs.getQuick(i), largePiece.getValue()); cs.setPlayable(context.state(), locs.getQuick(i), false); } for (int i = 4; i < 8; i++) { cs.setValueCell(context.state(), locs.getQuick(i), largePiece.getValue2()); cs.setPlayable(context.state(), locs.getQuick(i), false); } } } } /** * To update the track indices. * * @param context The context. */ public void updateTrackIndices(final Context context) { final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); if (onTrackIndices != null) { for (final Track track : context.board().tracks()) { final int trackIdx = track.trackIdx(); final TIntArrayList indices = onTrackIndices.locToIndex(trackIdx, to); if (indices.size() > 0) onTrackIndices.add(trackIdx, what, count, indices.getQuick(0)); } } } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final Game game = context.game(); final int contIdTo = type.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csTo = context.state().containerStates()[contIdTo]; final State gameState = context.state(); final boolean hiddenInfoGame = game.hiddenInformation(); if (actionLargePiece) { int pieceIdx = 0; pieceIdx = csTo.remove(context.state(), to, type); Component piece = context.components()[pieceIdx]; undoLargePiece(context, piece, csTo); } else { final boolean requiresStack = context.currentInstanceContext().game().isStacking(); final int sizeStackTo = csTo.sizeStack(to, type); if (requiresStack) // Stacking undo. { // We restore the to site for (int lvl = sizeStackTo -1 ; lvl >= 0; lvl--) csTo.remove(context.state(), to, lvl, type); for (int lvl = 0 ; lvl < previousWhat.length; lvl++) { csTo.addItemGeneric(gameState, to, previousWhat[lvl], previousWho[lvl], previousState[lvl], previousRotation[lvl], previousValue[lvl], game, type); if (hiddenInfoGame) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, lvl, type, previousHidden[lvl][pid]); csTo.setHiddenWhat(gameState, pid, to, lvl, type, previousHiddenWhat[lvl][pid]); csTo.setHiddenWho(gameState, pid, to, lvl, type, previousHiddenWho[lvl][pid]); csTo.setHiddenCount(gameState, pid, to, lvl, type, previousHiddenCount[lvl][pid]); csTo.setHiddenState(gameState, pid, to, lvl, type, previousHiddenState[lvl][pid]); csTo.setHiddenRotation(gameState, pid, to, lvl, type, previousHiddenRotation[lvl][pid]); csTo.setHiddenValue(gameState, pid, to, lvl, type, previousHiddenValue[lvl][pid]); } } } } else // Non stacking undo. { csTo.remove(context.state(), to, type); csTo.setSite(context.state(), to, previousWho[0], previousWhat[0], previousCount, previousState[0], previousRotation[0], previousValue[0], type); if (hiddenInfoGame) { if (previousHidden.length > 0) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, 0, type, previousHidden[0][pid]); csTo.setHiddenWhat(gameState, pid, to, 0, type, previousHiddenWhat[0][pid]); csTo.setHiddenWho(gameState, pid, to, 0, type, previousHiddenWho[0][pid]); csTo.setHiddenCount(gameState, pid, to, 0, type, previousHiddenCount[0][pid]); csTo.setHiddenState(gameState, pid, to, 0, type, previousHiddenState[0][pid]); csTo.setHiddenRotation(gameState, pid, to, 0, type, previousHiddenRotation[0][pid]); csTo.setHiddenValue(gameState, pid, to, 0, type, previousHiddenValue[0][pid]); } } } } } if (csTo.sizeStack(to, type) == 0) csTo.addToEmpty(to, type); return this; } /** * We undo the state in case of a large piece. * * @param context The context. * @param piece The piece. * @param cs The container state. */ public void undoLargePiece(final Context context, final Component piece, final ContainerState cs) { if (piece != null && piece.isLargePiece() && to < context.containers()[0].numSites()) { final Component largePiece = piece; final TIntArrayList locs = largePiece.locs(context, to, state, context.topology()); for (int i = 0; i < locs.size(); i++) { cs.addToEmpty(locs.getQuick(i), SiteType.Cell); cs.setCount(context.state(), locs.getQuick(i), 0); } if (largePiece.isDomino()) { for (int i = 0; i < 4; i++) { cs.setValueCell(context.state(), locs.getQuick(i), 0); //cs.setPlayable(context.state(), locs.getQuick(i), false); } for (int i = 4; i < 8; i++) { cs.setValueCell(context.state(), locs.getQuick(i), 0); //cs.setPlayable(context.state(), locs.getQuick(i), false); } } } } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Add:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (level != Constants.UNDEFINED) sb.append(",level=" + level); sb.append(",what=" + what); if (count > 1) sb.append(",count=" + count); if (state != Constants.UNDEFINED) sb.append(",state=" + state); if (rotation != Constants.UNDEFINED) sb.append(",rotation=" + rotation); if (value != Constants.UNDEFINED) sb.append(",value=" + value); if (onStack) sb.append(",stack=" + onStack); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + count; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + (onStack ? 1231 : 1237); result = prime * result + state; result = prime * result + rotation; result = prime * result + value; result = prime * result + what; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionAdd)) return false; final ActionAdd other = (ActionAdd) obj; return (count == other.count && decision == other.decision && to == other.to && onStack == other.onStack && state == other.state && rotation == other.rotation && value == other.value && what == other.what && type == other.type); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Add"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); if (onStack) sb.append("^"); else sb.append("+"); if (what > 0 && what < context.components().length) { sb.append(context.components()[what].name()); if (count > 1) sb.append("x" + count); } if (state != Constants.UNDEFINED) sb.append("=" + state); if (rotation != Constants.UNDEFINED) sb.append(" r" + rotation); if (value != Constants.UNDEFINED) sb.append(" v" + value); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Add "); if (what > 0 && what < context.components().length) { sb.append(context.components()[what].name()); if (count > 1) sb.append("x" + count); } String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(" to " + type + " " + newTo); else sb.append(" to " + newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); if (state != Constants.UNDEFINED) sb.append(" state=" + state); if (rotation != Constants.UNDEFINED) sb.append(" rotation=" + rotation); if (value != Constants.UNDEFINED) sb.append(" value=" + value); if (onStack) sb.append(" on stack"); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int levelTo() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int what() { return what; } @Override public int state() { if (state == Constants.UNDEFINED) return Constants.DEFAULT_STATE; return state; } @Override public int rotation() { if (rotation == Constants.UNDEFINED) return Constants.DEFAULT_ROTATION; return rotation; } @Override public int value() { if (value == Constants.UNDEFINED) return Constants.DEFAULT_VALUE; return value; } @Override public int count() { return count; } @Override public ActionType actionType() { return ActionType.Add; } @Override public boolean isStacking() { return onStack; } @Override public void setLevelFrom(final int level) { this.level = level; } @Override public void setLevelTo(final int level) { this.level = level; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final BitSet concepts = new BitSet(); // ---- Shoot concepts if (ludemeConcept.get(Concept.ShootDecision.id())) concepts.set(Concept.ShootDecision.id(), true); if (ludemeConcept.get(Concept.ShootEffect.id())) concepts.set(Concept.ShootEffect.id(), true); // ---- Take Control concepts if (ludemeConcept.get(Concept.TakeControl.id())) concepts.set(Concept.TakeControl.id(), true); // ---- Push concepts if (ludemeConcept.get(Concept.PushEffect.id())) concepts.set(Concept.PushEffect.id(), true); // ---- Add concepts if (concepts.isEmpty()) { if (decision) concepts.set(Concept.AddDecision.id(), true); else concepts.set(Concept.AddEffect.id(), true); } return concepts; } }
24,475
27.460465
153
java
Ludii
Ludii-master/Core/src/other/action/move/ActionCopy.java
package other.action.move; import java.util.BitSet; import java.util.List; import game.Game; import game.rules.play.moves.Moves; import game.types.board.RelationType; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.action.move.move.ActionMove; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; import other.topology.Topology; import other.topology.TopologyElement; /** * Copies a component from a site to another. * * @author Eric.Piette */ public final class ActionCopy extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type of the from site. */ private final SiteType typeFrom; /** From site index. */ private final int from; /** From level index (e.g. stacking game). */ private int levelFrom; /** The graph element type of the to site. */ private SiteType typeTo; /** To site index. */ private final int to; /** To level index (e.g. stacking game). */ private final int levelTo; /** Site state value of the to site. */ private final int state; /** Rotation value of the to site. */ private final int rotation; /** piece value of the to site. */ private final int value; /** Stacking game or not. */ private final boolean onStacking; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous state value of the piece before to be removed. */ private int previousState; /** The previous rotation value of the piece before to be removed. */ private int previousRotation; /** The previous value of the piece before to be removed. */ private int previousValue; //------------------------------------------------------------------------- /** * @param typeFrom The graph element type of the from site. * @param from From site index. * @param levelFrom From level index. * @param typeTo The graph element type of the to site. * @param to To site index. * @param levelTo To level index. * @param state The state site of the to site. * @param rotation The rotation value of the to site. * @param value The piece value of the to site. * @param onStacking True if we move a full stack. */ public ActionCopy ( final SiteType typeFrom, final int from, final int levelFrom, final SiteType typeTo, final int to, final int levelTo, final int state, final int rotation, final int value, final boolean onStacking ) { this.typeFrom = typeFrom; this.from = from; this.levelFrom = levelFrom; this.typeTo = typeTo; this.to = to; this.levelTo = levelTo; this.state = state; this.rotation = rotation; this.value = value; this.onStacking = onStacking; } /** * Reconstructs an ActionCopy object from a detailed String * (generated using toDetailedString()) * @param detailedString */ public ActionCopy(final String detailedString) { assert (detailedString.startsWith("[Copy:")); final String strTypeFrom = Action.extractData(detailedString, "typeFrom"); typeFrom = (strTypeFrom.isEmpty()) ? null : SiteType.valueOf(strTypeFrom); final String strFrom = Action.extractData(detailedString, "from"); from = Integer.parseInt(strFrom); final String strLevelFrom = Action.extractData(detailedString, "levelFrom"); levelFrom = (strLevelFrom.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevelFrom); final String strTypeTo = Action.extractData(detailedString, "typeTo"); typeTo = (strTypeTo.isEmpty()) ? null : SiteType.valueOf(strTypeTo); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevelTo = Action.extractData(detailedString, "levelTo"); levelTo = (strLevelTo.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevelTo); final String strState = Action.extractData(detailedString, "state"); state = (strState.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strState); final String strRotation = Action.extractData(detailedString, "rotation"); rotation = (strRotation.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strRotation); final String strValue = Action.extractData(detailedString, "value"); value = (strValue.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strValue); final String strStack = Action.extractData(detailedString, "stack"); onStacking = (strStack.isEmpty()) ? false : Boolean.parseBoolean(strStack); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { final Game game = context.game(); final int contIdA = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final ContainerState csA = context.state().containerStates()[contIdA]; final int originalCount = csA.count(from, typeFrom); final int contIdB = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csB = context.state().containerStates()[contIdB]; if (alreadyApplied) { if (game.isStacking()) { final int levelCopyIn = (levelTo == Constants.UNDEFINED) ? csB.sizeStack(to, typeTo) : levelTo; previousState = csB.state(to, levelCopyIn, typeTo); previousRotation = csB.rotation(to, levelCopyIn, typeTo); previousValue = csB.value(to, levelCopyIn, typeTo); } else { previousState = csB.state(to, typeTo); previousRotation = csB.rotation(to, typeTo); previousValue = csB.value(to, typeTo); } alreadyApplied = true; } final Action actionMove = ActionMove.construct(typeFrom, from, levelFrom, typeTo, to, levelTo, state, rotation, value, onStacking); actionMove.apply(context, store); final boolean requiresStack = game.isStacking(); if (!requiresStack) { csA.setSite(context.state(), from, csB.who(to, typeTo), csB.what(to, typeTo), originalCount, csB.state(to, typeTo), csB.rotation(to, typeTo), csB.value(to, typeTo), typeFrom); context.state().owned().add(csB.who(to, typeTo), csB.what(to, typeTo), from, typeFrom); } else { final int what = csB.what(to, typeTo); final int who = csB.who(to, typeTo); final int sizeStack = csB.sizeStack(to, typeTo); if (levelFrom == Constants.UNDEFINED || sizeStack == levelFrom) { csA.addItemGeneric(context.state(), from, what, who, game, typeFrom); context.state().owned().add(who, what, from, csA.sizeStack(from, typeFrom) - 1, typeFrom); } else { csA.insert(context.state(), typeFrom, from, levelFrom, what, who, state, rotation, value, game); context.state().owned().add(who, what, from, levelFrom, typeFrom); } } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final Game game = context.game(); final int contID = to >= context.containerId().length ? 0 : context.containerId()[to]; final int site = to; typeTo = (typeTo == null) ? context.board().defaultSite() : typeTo; // If the site is not supported by the type, that's a cell of another container. if (to >= context.board().topology().getGraphElements(typeTo).size()) typeTo = SiteType.Cell; final ContainerState cs = context.state().containerStates()[contID]; if (game.isStacking()) { final int levelCopyIn = (levelTo == Constants.UNDEFINED) ? cs.sizeStack(to, typeTo) - 1 : levelTo; cs.remove(context.state(), site, levelCopyIn, typeTo); if (cs.sizeStack(site, typeTo) == 0) cs.addToEmpty(site, typeTo); } else { final int currentCount = cs.count(site, typeTo); if (currentCount <= 1) { cs.remove(context.state(), site, typeTo); } else // We update the count. { final int previousCount = (game.requiresCount() ? currentCount - 1 : 1); cs.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, previousCount, previousState, previousRotation, previousValue, typeTo); } } return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Copy:"); if (typeFrom != null || (context != null && typeFrom != context.board().defaultSite())) { sb.append("typeFrom=" + typeFrom); sb.append(",from=" + from); } else sb.append("from=" + from); if (levelFrom != Constants.UNDEFINED) sb.append(",levelFrom=" + levelFrom); if (typeTo != null || (context != null && typeTo != context.board().defaultSite())) sb.append(",typeTo=" + typeTo); sb.append(",to=" + to); if (levelTo != Constants.UNDEFINED) sb.append(",levelTo=" + levelTo); if (state != Constants.UNDEFINED) sb.append(",state=" + state); if (rotation != Constants.UNDEFINED) sb.append(",rotation=" + rotation); if (value != Constants.UNDEFINED) sb.append(",value=" + value); if (onStacking) sb.append(",stack=" + onStacking); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + from; result = prime * result + levelFrom; result = prime * result + to; result = prime * result + levelTo; result = prime * result + state; result = prime * result + rotation; result = prime * result + value; result = prime * result + (onStacking ? 1231 : 1237); result = prime * result + ((typeFrom == null) ? 0 : typeFrom.hashCode()); result = prime * result + ((typeTo == null) ? 0 : typeTo.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionCopy)) return false; final ActionCopy other = (ActionCopy) obj; return (decision == other.decision && from == other.from && levelFrom == other.levelFrom && to == other.to && levelTo == other.levelTo && state == other.state && rotation == other.rotation && value == other.value && onStacking == other.onStacking && typeFrom == other.typeFrom && typeTo == other.typeTo); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Copy"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && !typeFrom.equals(context.board().defaultSite())) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (levelFrom != Constants.UNDEFINED && context.game().isStacking()) sb.append("/" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeTo != null && !typeTo.equals(context.board().defaultSite())) sb.append("-" + typeTo + " " + newTo); else sb.append("-" + newTo); if (levelTo != Constants.UNDEFINED) sb.append("/" + levelTo); if (state != Constants.UNDEFINED) sb.append("=" + state); if (rotation != Constants.UNDEFINED) sb.append(" r" + rotation); if (value != Constants.UNDEFINED) sb.append(" v" + value); if (onStacking) sb.append(" ^"); sb.append(" (Copy)"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Copy "); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && typeTo != null && (!typeFrom.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (levelFrom != Constants.UNDEFINED) sb.append("/" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); if (to < context.game().equipment().containers()[cid].topology().getGraphElements(realType).size()) newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); else // The site is not existing. newTo = "??"; } } if (typeFrom != null && typeTo != null && (!typeTo.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(" - " + typeTo + " " + newTo); else sb.append("-" + newTo); if (levelTo != Constants.UNDEFINED) sb.append("/" + levelTo); if (state != Constants.UNDEFINED) sb.append(" state=" + state); if (rotation != Constants.UNDEFINED) sb.append(" rotation=" + rotation); if (state != Constants.UNDEFINED) sb.append(" state=" + state); if (onStacking) sb.append(" stack=" + onStacking); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return typeFrom; } @Override public SiteType toType() { return typeTo; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int levelFrom() { return (levelFrom == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : levelFrom; } @Override public int levelTo() { return (levelTo == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : levelTo; } @Override public int state() { return state; } @Override public int rotation() { return rotation; } @Override public int value() { return value; } @Override public int count() { return 1; } @Override public boolean isStacking() { return onStacking; } @Override public void setLevelFrom(final int levelA) { this.levelFrom = levelA; } @Override public ActionType actionType() { return ActionType.Copy; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final int contIdA = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdB = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csA = context.state().containerStates()[contIdA]; final ContainerState csB = context.state().containerStates()[contIdB]; final int whatA = csA.what(from, typeFrom); final int whatB = csB.what(to, typeTo); final int whoA = csA.who(from, typeFrom); final int whoB = csB.who(to, typeTo); final BitSet concepts = new BitSet(); // ---- Hop concepts if (ludemeConcept.get(Concept.HopDecision.id())) { concepts.set(Concept.HopDecision.id(), true); if (whatA != 0) { final Topology topology = context.topology(); final TopologyElement fromV = topology.getGraphElements(typeFrom).get(from); final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, typeFrom); AbsoluteDirection direction = null; int distance = Constants.UNDEFINED; for (final DirectionFacing facingDirection : directionsSupported) { final AbsoluteDirection absDirection = facingDirection.toAbsolute(); final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), absDirection); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int toRadial = radial.steps()[toIdx].id(); if (toRadial == to) { direction = absDirection; distance = toIdx; break; } } if (direction != null) break; } } if (direction != null) { final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), direction); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < distance; toIdx++) { final int between = radial.steps()[toIdx].id(); final int whatBetween = csA.what(between, typeFrom); final int whoBetween = csA.who(between, typeFrom); if (whatBetween != 0) { if (areEnemies(context, whoA, whoBetween)) { if (whatB == 0) concepts.set(Concept.HopDecisionEnemyToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionEnemyToEnemy.id(), true); else concepts.set(Concept.HopDecisionEnemyToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); concepts.set(Concept.HopCaptureMoreThanOne.id(), true); } } else { if (whatB == 0) concepts.set(Concept.HopDecisionFriendToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionFriendToEnemy.id(), true); else concepts.set(Concept.HopDecisionFriendToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } } } } } } } } if (ludemeConcept.get(Concept.HopEffect.id())) concepts.set(Concept.HopEffect.id(), true); // ---- Step concepts if (ludemeConcept.get(Concept.StepEffect.id())) concepts.set(Concept.StepEffect.id(), true); if (ludemeConcept.get(Concept.StepDecision.id())) { concepts.set(Concept.StepDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.StepDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.StepDecisionToEnemy.id(), true); else concepts.set(Concept.StepDecisionToFriend.id(), true); } } } // ---- Leap concepts if (ludemeConcept.get(Concept.LeapEffect.id())) concepts.set(Concept.LeapEffect.id(), true); if (ludemeConcept.get(Concept.LeapDecision.id())) { concepts.set(Concept.LeapDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.LeapDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.LeapDecisionToEnemy.id(), true); else concepts.set(Concept.LeapDecisionToFriend.id(), true); } } } // ---- Slide concepts if (ludemeConcept.get(Concept.SlideEffect.id())) concepts.set(Concept.SlideEffect.id(), true); if (ludemeConcept.get(Concept.SlideDecision.id())) { concepts.set(Concept.SlideDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.SlideDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.SlideDecisionToEnemy.id(), true); else concepts.set(Concept.SlideDecisionToFriend.id(), true); } } } // ---- FromTo concepts if (ludemeConcept.get(Concept.FromToDecision.id())) { concepts.set(Concept.FromToDecision.id(), true); if (contIdA == contIdB) concepts.set(Concept.FromToDecisionWithinBoard.id(), true); else concepts.set(Concept.FromToDecisionBetweenContainers.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.FromToDecisionEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.FromToDecisionEnemy.id(), true); else concepts.set(Concept.FromToDecisionFriend.id(), true); } } } if (ludemeConcept.get(Concept.FromToEffect.id())) concepts.set(Concept.FromToEffect.id(), true); // ---- Swap Pieces concepts if (ludemeConcept.get(Concept.SwapPiecesEffect.id())) concepts.set(Concept.SwapPiecesEffect.id(), true); if (ludemeConcept.get(Concept.SwapPiecesDecision.id())) concepts.set(Concept.SwapPiecesDecision.id(), true); // ---- Sow concepts if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.Sow.id())) concepts.set(Concept.Sow.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.SowBacktracking.id())) concepts.set(Concept.SowBacktracking.id(), true); return concepts; } /** * @param context The context. * @param who1 The id of a player. * @param who2 The id of a player. * @return True if these players are enemies. */ public static boolean areEnemies(final Context context, final int who1, final int who2) { if (who1 == 0 || who2 == 0 || who1 == who2) return false; if (context.game().requiresTeams()) { final TIntArrayList teamMembers = new TIntArrayList(); final int tid = context.state().getTeam(who1); for (int i = 1; i < context.game().players().size(); i++) if (context.state().getTeam(i) == tid) teamMembers.add(i); return !teamMembers.contains(who2); } return who1 != who2; } }
23,268
26.668252
149
java
Ludii
Ludii-master/Core/src/other/action/move/ActionInsert.java
package other.action.move; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.types.board.SiteType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; /** * Inserts a component inside a stack. * * @author Eric.Piette */ public final class ActionInsert extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type. */ private SiteType type; /** Site index. */ private final int to; /** Level index. */ private final int level; /** Component index. */ private final int what; /** State of the site. */ private final int state; //------------------------------------------------------------------------- /** * @param type The graph element type. * @param to The site to insert * @param level The level to insert. * @param what The index of the component. * @param state The state value. */ public ActionInsert ( final SiteType type, final int to, final int level, final int what, final int state ) { this.type = type; this.to = to; this.level = level; this.what = what; this.state = state; } /** * Reconstructs an ActionInsert object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionInsert(final String detailedString) { assert (detailedString.startsWith("[Insert:")); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = Integer.parseInt(strLevel); final String strWhat = Action.extractData(detailedString, "what"); what = Integer.parseInt(strWhat); final String strState = Action.extractData(detailedString, "state"); state = (strState.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strState); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; // If the site is not supported by the type, that's a cell of another container. if (to >= context.board().topology().getGraphElements(type).size()) type = SiteType.Cell; final int contID = (type == SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contID]; final int who = (what < 1) ? 0 : context.components()[what].owner(); final int sizeStack = cs.sizeStack(to, type); if (level == sizeStack) { // We insert the new piece. cs.insert(context.state(), type, to, level, what, who, state, Constants.UNDEFINED, Constants.UNDEFINED, context.game()); // we update the empty list cs.removeFromEmpty(to, type); // we update the own list with the new piece if (what != 0) { final Component piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, cs.sizeStack(to, type) - 1, type); } } else { // we update the own list of the pieces on the top of that piece inserted. for (int lvl = sizeStack - 1; lvl >= level; lvl--) { final int owner = cs.who(to, lvl, type); final int piece = cs.what(to, lvl, type); context.state().owned().removeNoUpdate(owner, piece, to, lvl, type); context.state().owned().add(owner, piece, to, lvl + 1, type); } // We insert the new piece. cs.insert(context.state(), type, to, level, what, who, state, Constants.UNDEFINED, Constants.UNDEFINED, context.game()); // we update the own list with the new piece final Component piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, level, type); } // We update the structure about track indices if the game uses track. final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); if (onTrackIndices != null) { for (final Track track : context.board().tracks()) { final int trackIdx = track.trackIdx(); final TIntArrayList indices = onTrackIndices.locToIndex(trackIdx, to); if (indices.size() > 0) onTrackIndices.add(trackIdx, what, 1, indices.getQuick(0)); } } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { type = (type == null) ? context.board().defaultSite() : type; // If the site is not supported by the type, that's a cell of another container. if (to >= context.board().topology().getGraphElements(type).size()) type = SiteType.Cell; final int contID = (type == SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contID]; if (level == Constants.UNDEFINED) cs.remove(context.state(), to, type); else cs.remove(context.state(), to, level, type); if (cs.sizeStack(to, type) == 0) cs.addToEmpty(to, type); return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + level; result = prime * result + state; result = prime * result + what; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionInsert)) return false; final ActionInsert other = (ActionInsert) obj; return (decision == other.decision && to == other.to && level == other.level && state == other.state && what == other.what && type.equals(other.type)); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Insert:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); sb.append(",level=" + level); sb.append(",what=" + what); if (state != Constants.UNDEFINED) sb.append(",state=" + state); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Insert"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); sb.append("^"); if (what > 0 && what < context.components().length) sb.append(context.components()[what].name()); if (state != Constants.UNDEFINED) sb.append("=" + state); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Insert "); if (what > 0 && what < context.components().length) sb.append(context.components()[what].name()); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(" to " + type + " " + newTo); else sb.append(" to " + newTo); sb.append("/" + level); if (state != Constants.UNDEFINED) sb.append(" state=" + state); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return level; } @Override public int levelTo() { return level; } @Override public int what() { return what; } @Override public int state() { return state; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public ActionType actionType() { return ActionType.Insert; } }
9,797
23.994898
123
java
Ludii
Ludii-master/Core/src/other/action/move/ActionMoveN.java
package other.action.move; import java.util.BitSet; import java.util.List; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.RelationType; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; import other.topology.Topology; import other.topology.TopologyElement; /** * Moves many pieces from a site to another (but not in a stack). * * @author Eric.Piette */ public final class ActionMoveN extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type of the from site. */ private final SiteType typeFrom; /** From site index. */ private final int from; /** The graph element type of the to site. */ private final SiteType typeTo; /** To site index. */ private final int to; /** The number of pieces to move. */ private final int count; //----------------------Undo Data--------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; //-- from data /** Previous What value of the from site. */ private int[] previousWhatFrom; /** Previous Who value of the from site. */ private int[] previousWhoFrom; /** Previous Site state value of the from site. */ private int[] previousStateFrom; /** Previous Rotation value of the from site. */ private int[] previousRotationFrom; /** Previous Piece value of the from site. */ private int[] previousValueFrom; /** Previous Piece count of the from site. */ private int previousCountFrom; /** The previous hidden info values of the from site before to be removed. */ private boolean[][] previousHiddenFrom; /** The previous hidden what info values of the from site before to be removed. */ private boolean[][] previousHiddenWhatFrom; /** The previous hidden who info values of the from site before to be removed. */ private boolean[][] previousHiddenWhoFrom; /** The previous hidden count info values of the from site before to be removed. */ private boolean[][] previousHiddenCountFrom; /** The previous hidden rotation info values of the from site before to be removed. */ private boolean[][] previousHiddenRotationFrom; /** The previous hidden State info values of the from site before to be removed. */ private boolean[][] previousHiddenStateFrom; /** The previous hidden Value info values of the from site before to be removed. */ private boolean[][] previousHiddenValueFrom; //--- to data /** Previous What of the to site. */ private int[] previousWhatTo; /** Previous Who of the to site. */ private int[] previousWhoTo; /** Previous Site state value of the to site. */ private int[] previousStateTo; /** Previous Rotation value of the to site. */ private int[] previousRotationTo; /** Previous Piece value of the to site. */ private int[] previousValueTo; /** Previous Piece count of the to site. */ private int previousCountTo; /** The previous hidden info values of the to site before to be removed. */ private boolean[][] previousHiddenTo; /** The previous hidden what info values of the to site before to be removed. */ private boolean[][] previousHiddenWhatTo; /** The previous hidden who info values of the to site before to be removed. */ private boolean[][] previousHiddenWhoTo; /** The previous hidden count info values of the to site before to be removed. */ private boolean[][] previousHiddenCountTo; /** The previous hidden rotation info values of the to site before to be removed. */ private boolean[][] previousHiddenRotationTo; /** The previous hidden State info values of the to site before to be removed. */ private boolean[][] previousHiddenStateTo; /** The previous hidden Value info values of the to site before to be removed. */ private boolean[][] previousHiddenValueTo; //------------------------------------------------------------------------- /** * @param typeFrom The graph element type of the origin. * @param from From site of the move. * @param typeTo The graph element type of the target. * @param to To site of the move. * @param count The number of pieces to move. */ public ActionMoveN ( final SiteType typeFrom, final int from, final SiteType typeTo, final int to, final int count ) { this.from = from; this.to = to; this.count = count; this.typeFrom = typeFrom; this.typeTo = typeTo; } /** * Reconstructs an ActionMoveN object from a detailed String * (generated using toDetailedString()) * @param detailedString */ public ActionMoveN(final String detailedString) { assert (detailedString.startsWith("[Move:")); final String strTypeFrom = Action.extractData(detailedString, "typeFrom"); typeFrom = (strTypeFrom.isEmpty()) ? null : SiteType.valueOf(strTypeFrom); final String strFrom = Action.extractData(detailedString, "from"); from = Integer.parseInt(strFrom); final String strTypeTo = Action.extractData(detailedString, "typeTo"); typeTo = (strTypeTo.isEmpty()) ? null : SiteType.valueOf(strTypeTo); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strCount = Action.extractData(detailedString, "count"); count = Integer.parseInt(strCount); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { final int cidFrom = context.containerId()[from]; final int cidTo = context.containerId()[to]; final ContainerState csFrom = context.state().containerStates()[cidFrom]; final ContainerState csTo = context.state().containerStates()[cidTo]; final int what = csFrom.what(from, typeFrom); final int who = (what < 1) ? 0 : context.components()[what].owner(); // Keep in memory the data of the site from and to (for undo method) if(!alreadyApplied) { previousCountFrom = csFrom.count(from, typeFrom); previousWhatFrom = new int[1]; previousWhoFrom = new int[1]; previousStateFrom = new int[1]; previousRotationFrom = new int[1]; previousValueFrom = new int[1]; previousWhatFrom[0] = csFrom.what(from, 0, typeFrom); previousWhoFrom[0] = csFrom.who(from, 0, typeFrom); previousStateFrom[0] = csFrom.state(from, 0, typeFrom); previousRotationFrom[0] = csFrom.rotation(from, 0, typeFrom); previousValueFrom[0] = csFrom.value(from, 0, typeFrom); previousCountTo = csTo.count(to, typeTo); previousWhatTo = new int[1]; previousWhoTo = new int[1]; previousStateTo = new int[1]; previousRotationTo = new int[1]; previousValueTo = new int[1]; previousWhatTo[0] = csTo.what(to, 0, typeTo); previousWhoTo[0] = csTo.who(to, 0, typeTo); previousStateTo[0] = csTo.state(to, 0, typeTo); previousRotationTo[0] = csTo.rotation(to, 0, typeTo); previousValueTo[0] = csTo.value(to, 0, typeTo); if(context.game().hiddenInformation()) { previousHiddenFrom = new boolean[1][context.players().size()]; previousHiddenWhatFrom = new boolean[1][context.players().size()]; previousHiddenWhoFrom = new boolean[1][context.players().size()]; previousHiddenCountFrom = new boolean[1][context.players().size()]; previousHiddenRotationFrom = new boolean[1][context.players().size()]; previousHiddenStateFrom = new boolean[1][context.players().size()]; previousHiddenValueFrom = new boolean[1][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenFrom[0][pid] = csFrom.isHidden(pid, from, 0, typeFrom); previousHiddenWhatFrom[0][pid] = csFrom.isHiddenWhat(pid, from, 0, typeFrom); previousHiddenWhoFrom[0][pid] = csFrom.isHiddenWho(pid, from, 0, typeFrom); previousHiddenCountFrom[0][pid] = csFrom.isHiddenCount(pid, from, 0, typeFrom); previousHiddenStateFrom[0][pid] = csFrom.isHiddenState(pid, from, 0, typeFrom); previousHiddenRotationFrom[0][pid] = csFrom.isHiddenRotation(pid, from, 0, typeFrom); previousHiddenValueFrom[0][pid] = csFrom.isHiddenValue(pid, from, 0, typeFrom); } previousHiddenTo = new boolean[1][context.players().size()]; previousHiddenWhatTo = new boolean[1][context.players().size()]; previousHiddenWhoTo = new boolean[1][context.players().size()]; previousHiddenCountTo = new boolean[1][context.players().size()]; previousHiddenRotationTo = new boolean[1][context.players().size()]; previousHiddenStateTo = new boolean[1][context.players().size()]; previousHiddenValueTo = new boolean[1][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenTo[0][pid] = csTo.isHidden(pid, to, 0, typeTo); previousHiddenWhatTo[0][pid] = csTo.isHiddenWhat(pid, to, 0, typeTo); previousHiddenWhoTo[0][pid] = csTo.isHiddenWho(pid, to, 0, typeTo); previousHiddenCountTo[0][pid] = csTo.isHiddenCount(pid, to, 0, typeTo); previousHiddenStateTo[0][pid] = csTo.isHiddenState(pid, to, 0, typeTo); previousHiddenRotationTo[0][pid] = csTo.isHiddenRotation(pid, to, 0, typeTo); previousHiddenValueTo[0][pid] = csTo.isHiddenValue(pid, to, 0, typeTo); } } alreadyApplied = true; } // modification on From if (csFrom.count(from, typeFrom) - count <= 0) csFrom.remove(context.state(), from, typeFrom); else csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, csFrom.count(from, typeFrom) - count, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, typeFrom); // modification on To if (csTo.count(to, typeTo) == 0) csTo.setSite(context.state(), to, who, what, count, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, typeTo); else if (csTo.what(to, typeTo) == what) if((csTo.count(to, typeTo) + count) <= context.game().maxCount()) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, csTo.count(to, typeTo) + count, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, typeTo); // Component piece = null; // to keep the site of the item in cache for each player if (what != 0 && who !=0) { if(csFrom.count(from, typeFrom) == 0) context.state().owned().remove(who, what, from, typeFrom); context.state().owned().add(who, what, to, typeTo); } final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); // We update the structure about track indices if the game uses track. if (what != 0 && onTrackIndices != null) { for (final Track track : context.board().tracks()) { final int trackIdx = track.trackIdx(); final TIntArrayList indicesLocFrom = onTrackIndices.locToIndex(trackIdx, from); for (int k = 0; k < indicesLocFrom.size(); k++) { final int indexA = indicesLocFrom.getQuick(k); final int countAtIndex = onTrackIndices.whats(trackIdx, what, indicesLocFrom.getQuick(k)); if (countAtIndex > 0) { onTrackIndices.remove(trackIdx, what, this.count, indexA); final TIntArrayList newWhatIndice = onTrackIndices.locToIndexFrom(trackIdx, to, indexA); if (newWhatIndice.size() > 0) { onTrackIndices.add(trackIdx, what, this.count, newWhatIndice.getQuick(0)); } else { final TIntArrayList newWhatIndiceIfNotAfter = onTrackIndices.locToIndex(trackIdx, to); if (newWhatIndiceIfNotAfter.size() > 0) onTrackIndices.add(trackIdx, what, this.count, newWhatIndiceIfNotAfter.getQuick(0)); } break; } } // If the piece was not in the track but enter on it, we update the structure // corresponding to that track. if (indicesLocFrom.size() == 0) { final TIntArrayList indicesLocTo = onTrackIndices.locToIndex(trackIdx, to); if (indicesLocTo.size() != 0) onTrackIndices.add(trackIdx, what, 1, indicesLocTo.getQuick(0)); } } } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; final State gameState = context.state(); csFrom.remove(context.state(), from, typeFrom); csTo.remove(context.state(), to, typeTo); csFrom.setSite(context.state(), from, previousWhoFrom[0], previousWhatFrom[0], previousCountFrom, previousStateFrom[0], previousRotationFrom[0], previousValueFrom[0], typeFrom); csTo.setSite(context.state(), to, previousWhoTo[0], previousWhatTo[0], previousCountTo, previousStateTo[0], previousRotationTo[0], previousValueTo[0], typeTo); if(context.game().hiddenInformation()) { if(previousHiddenFrom.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, 0, typeFrom, previousHiddenFrom[0][pid]); csFrom.setHiddenWhat(gameState, pid, from, 0, typeFrom, previousHiddenWhatFrom[0][pid]); csFrom.setHiddenWho(gameState, pid, from, 0, typeFrom, previousHiddenWhoFrom[0][pid]); csFrom.setHiddenCount(gameState, pid, from, 0, typeFrom, previousHiddenCountFrom[0][pid]); csFrom.setHiddenState(gameState, pid, from, 0, typeFrom, previousHiddenStateFrom[0][pid]); csFrom.setHiddenRotation(gameState, pid, from, 0, typeFrom, previousHiddenRotationFrom[0][pid]); csFrom.setHiddenValue(gameState, pid, from, 0, typeFrom, previousHiddenValueFrom[0][pid]); } if(previousHiddenTo.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, 0, typeTo, previousHiddenTo[0][pid]); csTo.setHiddenWhat(gameState, pid, to, 0, typeTo, previousHiddenWhatTo[0][pid]); csTo.setHiddenWho(gameState, pid, to, 0, typeTo, previousHiddenWhoTo[0][pid]); csTo.setHiddenCount(gameState, pid, to, 0, typeTo, previousHiddenCountTo[0][pid]); csTo.setHiddenState(gameState, pid, to, 0, typeTo, previousHiddenStateTo[0][pid]); csTo.setHiddenRotation(gameState, pid, to, 0, typeTo, previousHiddenRotationTo[0][pid]); csTo.setHiddenValue(gameState, pid, to, 0, typeTo, previousHiddenValueTo[0][pid]); } } if (csTo.sizeStack(to, typeTo) == 0) csTo.addToEmpty(to, typeTo); if (csFrom.sizeStack(from, typeFrom) != 0) csFrom.removeFromEmpty(from, typeFrom); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Move:"); if (typeFrom != null || (context != null && typeFrom != context.board().defaultSite())) { sb.append("typeFrom=" + typeFrom); sb.append(",from=" + from); } else sb.append("from=" + from); if (typeTo != null || (context != null && typeTo != context.board().defaultSite())) sb.append(",typeTo=" + typeTo); sb.append(",to=" + to); sb.append(",count=" + count); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + count; result = prime * result + (decision ? 1231 : 1237); result = prime * result + from; result = prime * result + to; result = prime * result + ((typeFrom == null) ? 0 : typeFrom.hashCode()); result = prime * result + ((typeTo == null) ? 0 : typeTo.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionMoveN)) return false; final ActionMoveN other = (ActionMoveN) obj; return (count == other.count && decision == other.decision && from == other.from && to == other.to && typeFrom == other.typeFrom && typeTo == other.typeTo); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Move"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && !typeFrom.equals(context.board().defaultSite())) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeTo != null && !typeTo.equals(context.board().defaultSite())) sb.append("-" + typeTo + " " + newTo); else sb.append("-" + newTo); if (count > 1) sb.append("x" + count); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Move "); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && typeTo != null && (!typeFrom.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeFrom != null && typeTo != null && (!typeTo.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(" - " + typeTo + " " + newTo); else sb.append("-" + newTo); if (count > 1) sb.append("x" + count); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return typeFrom; } @Override public SiteType toType() { return typeTo; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int count() { return count; } @Override public ActionType actionType() { return ActionType.MoveN; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final int contIdA = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdB = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csA = context.state().containerStates()[contIdA]; final ContainerState csB = context.state().containerStates()[contIdB]; final int whatA = csA.what(from, typeFrom); final int whatB = csB.what(to, typeTo); final int whoA = csA.who(from, typeFrom); final int whoB = csB.who(to, typeTo); final BitSet concepts = new BitSet(); // ---- Hop concepts if (ludemeConcept.get(Concept.HopDecision.id())) { concepts.set(Concept.HopDecision.id(), true); if (whatA != 0) { final Topology topology = context.topology(); final TopologyElement fromV = topology.getGraphElements(typeFrom).get(from); final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, typeFrom); AbsoluteDirection direction = null; int distance = Constants.UNDEFINED; for (final DirectionFacing facingDirection : directionsSupported) { final AbsoluteDirection absDirection = facingDirection.toAbsolute(); final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), absDirection); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int toRadial = radial.steps()[toIdx].id(); if (toRadial == to) { direction = absDirection; distance = toIdx; break; } } if (direction != null) break; } } if (direction != null) { final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), direction); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < distance; toIdx++) { final int between = radial.steps()[toIdx].id(); final int whatBetween = csA.what(between, typeFrom); final int whoBetween = csA.who(between, typeFrom); if (whatBetween != 0) { if (areEnemies(context, whoA, whoBetween)) { if (whatB == 0) concepts.set(Concept.HopDecisionEnemyToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionEnemyToEnemy.id(), true); else concepts.set(Concept.HopDecisionEnemyToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); concepts.set(Concept.HopCaptureMoreThanOne.id(), true); } } else { if (whatB == 0) concepts.set(Concept.HopDecisionFriendToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionFriendToEnemy.id(), true); else concepts.set(Concept.HopDecisionFriendToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } } } } } } } } if (ludemeConcept.get(Concept.HopEffect.id())) concepts.set(Concept.HopEffect.id(), true); // ---- Step concepts if (ludemeConcept.get(Concept.StepEffect.id())) concepts.set(Concept.StepEffect.id(), true); if (ludemeConcept.get(Concept.StepDecision.id())) { concepts.set(Concept.StepDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.StepDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.StepDecisionToEnemy.id(), true); else concepts.set(Concept.StepDecisionToFriend.id(), true); } } } // ---- Leap concepts if (ludemeConcept.get(Concept.LeapEffect.id())) concepts.set(Concept.LeapEffect.id(), true); if (ludemeConcept.get(Concept.LeapDecision.id())) { concepts.set(Concept.LeapDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.LeapDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.LeapDecisionToEnemy.id(), true); else concepts.set(Concept.LeapDecisionToFriend.id(), true); } } } // ---- Slide concepts if (ludemeConcept.get(Concept.SlideEffect.id())) concepts.set(Concept.SlideEffect.id(), true); if (ludemeConcept.get(Concept.SlideDecision.id())) { concepts.set(Concept.SlideDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.SlideDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.SlideDecisionToEnemy.id(), true); else concepts.set(Concept.SlideDecisionToFriend.id(), true); } } } // ---- FromTo concepts if (ludemeConcept.get(Concept.FromToDecision.id())) { if (contIdA == contIdB) concepts.set(Concept.FromToDecisionWithinBoard.id(), true); else concepts.set(Concept.FromToDecisionBetweenContainers.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.FromToDecisionEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.FromToDecisionEnemy.id(), true); else concepts.set(Concept.FromToDecisionFriend.id(), true); } } } if (ludemeConcept.get(Concept.FromToEffect.id())) concepts.set(Concept.FromToEffect.id(), true); // ---- Swap Pieces concepts if (ludemeConcept.get(Concept.SwapPiecesEffect.id())) concepts.set(Concept.SwapPiecesEffect.id(), true); if (ludemeConcept.get(Concept.SwapPiecesDecision.id())) concepts.set(Concept.SwapPiecesDecision.id(), true); // ---- Sow concepts if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.Sow.id())) concepts.set(Concept.Sow.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.SowBacktracking.id())) concepts.set(Concept.SowBacktracking.id(), true); return concepts; } /** * @param context The context. * @param who1 The id of a player. * @param who2 The id of a player. * @return True if these players are enemies. */ public static boolean areEnemies(final Context context, final int who1, final int who2) { if (who1 == 0 || who2 == 0 || who1 == who2) return false; if (context.game().requiresTeams()) { final TIntArrayList teamMembers = new TIntArrayList(); final int tid = context.state().getTeam(who1); for (int i = 1; i < context.game().players().size(); i++) if (context.state().getTeam(i) == tid) teamMembers.add(i); return !teamMembers.contains(who2); } return who1 != who2; } }
27,686
30.971132
194
java
Ludii
Ludii-master/Core/src/other/action/move/ActionPromote.java
package other.action.move; import java.util.BitSet; import game.Game; import game.equipment.component.Component; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Promotes a piece to another piece. * * @author Eric.Piette */ public final class ActionPromote extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Site index. */ private final int to; /** Level. */ private int level = Constants.UNDEFINED; /** New index of the piece after promotion. */ private final int newWhat; /** The graph element type. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous index of the piece before to be removed. */ private int previousWhat; /** The previous state value of the piece before to be removed. */ private int previousState; /** The previous rotation value of the piece before to be removed. */ private int previousRotation; /** The previous value of the piece before to be removed. */ private int previousValue; //------------------------------------------------------------------------- /** * @param type The graph element type. * @param to Location to promote the component. * @param what The new index of the piece. */ public ActionPromote ( final SiteType type, final int to, final int what ) { this.to = to; this.newWhat = what; this.type = type; } /** * Reconstructs an ActionPromote object from a detailed String * (generated using toDetailedString()) * @param detailedString */ public ActionPromote(final String detailedString) { assert (detailedString.startsWith("[Promote:")); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); level = (strLevel.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevel); final String strWhat = Action.extractData(detailedString, "what"); newWhat = Integer.parseInt(strWhat); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; final int contID = (type == SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contID]; final Game game = context.game(); final int oldWhat = (level == Constants.UNDEFINED) ? cs.what(to, type) : cs.what(to, level, type); if(!alreadyApplied) { previousWhat = oldWhat; previousState = cs.state(to, type); previousRotation = cs.rotation(to, type); previousValue = cs.value(to, type); alreadyApplied = true; } if (!game.isStacking()) { Component piece = null; // To keep the site of the item in cache for each player. if (oldWhat != 0) { piece = context.components()[oldWhat]; final int owner = piece.owner(); if (owner != 0) { context.state().owned().remove(owner, oldWhat, to, type); } } cs.remove(context.state(), to, type); final int who = (oldWhat < 1) ? 0 : context.components()[newWhat].owner(); cs.setSite(context.state(), to, who, newWhat, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, type); // to keep the site of the item in cache for each player if (newWhat != 0) { piece = context.components()[newWhat]; final int owner = piece.owner(); if (owner != 0) context.state().owned().add(owner, newWhat, to, type); } } else { Component piece = context.components()[oldWhat]; final int previousOwner = piece.owner(); if (level == Constants.UNDEFINED) // remove the item on the top of the stack cs.remove(context.state(), to, type); else cs.remove(context.state(), to, level); final int sizeStack = cs.sizeStack(to, type); if (cs.sizeStack(to, type) == 0) cs.addToEmptyCell(to); // To keep the site of the item in cache for each player. if (cs.sizeStack(to, type) != 0) { if (previousOwner != 0) { if (level == Constants.UNDEFINED) context.state().owned().remove(previousOwner, oldWhat, to, sizeStack, type); else context.state().owned().remove(previousOwner, oldWhat, to, level, type); } } final int who = (newWhat < 1) ? 0 : context.components()[newWhat].owner(); cs.addItemGeneric(context.state(), to, newWhat, who, context.game(), type); cs.removeFromEmptyCell(to); if (newWhat != 0) { piece = context.components()[newWhat]; final int owner = piece.owner(); if (owner != 0) { if (level == Constants.UNDEFINED) context.state().owned().add(owner, newWhat, to, sizeStack, type); else context.state().owned().add(owner, newWhat, to, level, type); } } } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { type = (type == null) ? context.board().defaultSite() : type; final int contID = (type == SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contID]; final Game game = context.game(); final int oldWhat = (level == Constants.UNDEFINED) ? cs.what(to, type) : cs.what(to, level, type); if (!game.isStacking()) { cs.remove(context.state(), to, type); final int who = (oldWhat < 1) ? 0 : context.components()[previousWhat].owner(); cs.setSite(context.state(), to, who, previousWhat, 1, previousState, previousRotation, previousValue, type); } else { if (level == Constants.UNDEFINED) // remove the item on the top of the stack cs.remove(context.state(), to, type); else cs.remove(context.state(), to, level); if (cs.sizeStack(to, type) == 0) cs.addToEmptyCell(to); final int who = (previousWhat < 1) ? 0 : context.components()[previousWhat].owner(); cs.addItemGeneric(context.state(), to, previousWhat, who, context.game(), type); cs.removeFromEmptyCell(to); } return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Promote:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (level != Constants.UNDEFINED) sb.append(",level=" + level); sb.append(",what=" + newWhat); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + level; result = prime * result + to; result = prime * result + newWhat; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionPromote)) return false; final ActionPromote other = (ActionPromote) obj; return (decision == other.decision && level == other.level && to == other.to && newWhat == other.newWhat && type == other.type); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Promote"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); if (newWhat > 0 && newWhat < context.components().length) sb.append(" => " + context.components()[newWhat].name()); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Promote "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); if (level != Constants.UNDEFINED) sb.append("/" + level); if (newWhat > 0 && newWhat < context.components().length) sb.append(" to " + context.components()[newWhat].name()); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public int count() { return 1; } @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int levelTo() { return (level == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : level; } @Override public int what() { return newWhat; } @Override public ActionType actionType() { return ActionType.Promote; } /** * To set the level in the JUnit test. To not use in other code ! * * @param level The new level. */ public void setLevel(final int level) { this.level = level; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); if(decision) concepts.set(Concept.PromotionDecision.id(), true); else concepts.set(Concept.PromotionEffect.id(), true); return concepts; } }
11,480
24.513333
123
java
Ludii
Ludii-master/Core/src/other/action/move/ActionSelect.java
package other.action.move; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Selects the from/to sites of the move. * * @author Eric.Piette */ public final class ActionSelect extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location From index. */ private final int from; /** Location To index. */ private final int to; /** Level From. */ private final int levelFrom; /** Level To. */ private final int levelTo; /** Add on Vertex/Edge/Face. */ private final SiteType typeFrom; /** Add on Vertex/Edge/Face. */ private final SiteType typeTo; //------------------------------------------------------------------------- /** * @param typeFrom The graph element type of the origin. * @param from The site of the origin. * @param levelFrom The level of the origin. * @param typeTo The graph element type of the target. * @param to The site of the target. * @param levelTo The level of the target. */ public ActionSelect ( final SiteType typeFrom, final int from, final int levelFrom, final SiteType typeTo, final int to, final int levelTo ) { this.from = from; this.to = to; this.typeFrom = typeFrom; this.typeTo = (typeTo != null) ? typeTo : typeFrom; this.levelFrom = levelFrom; this.levelTo = levelTo; } /** * Reconstructs an ActionSelect object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionSelect(final String detailedString) { assert (detailedString.startsWith("[Select:")); final String strTypeFrom = Action.extractData(detailedString, "typeFrom"); typeFrom = (strTypeFrom.isEmpty()) ? null : SiteType.valueOf(strTypeFrom); final String strFrom = Action.extractData(detailedString, "from"); from = (strFrom.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strFrom); final String strLevelFrom = Action.extractData(detailedString, "levelFrom"); levelFrom = (strLevelFrom.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevelFrom); final String strTypeTo = Action.extractData(detailedString, "typeTo"); typeTo = (strTypeTo.isEmpty()) ? typeFrom : SiteType.valueOf(strTypeTo); final String strTo = Action.extractData(detailedString, "to"); to = (strTo.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strTo); final String strLevelTo = Action.extractData(detailedString, "levelTo"); levelTo = (strLevelTo.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevelTo); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { // do nothing return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, final boolean discard) { return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + from; result = prime * result + to; result = prime * result + ((typeFrom == null) ? 0 : typeFrom.hashCode()); result = prime * result + ((typeTo == null) ? 0 : typeTo.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSelect)) return false; final ActionSelect other = (ActionSelect) obj; return (decision == other.decision && from == other.from && to == other.to && typeFrom == other.typeFrom && typeTo == other.typeTo); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Select:"); if (typeFrom != null || (context != null && typeFrom != context.board().defaultSite())) { sb.append("typeFrom=" + typeFrom); sb.append(",from=" + from); } else sb.append("from=" + from); if (levelFrom != Constants.UNDEFINED) sb.append(",levelFrom=" + levelFrom); if (to != Constants.UNDEFINED) { if (typeTo != null) sb.append(",typeTo=" + typeTo); sb.append(",to=" + to); if (levelTo != Constants.UNDEFINED) sb.append(",levelTo=" + levelTo); } if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Select"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("*"); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && !typeFrom.equals(context.board().defaultSite())) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (levelFrom != Constants.UNDEFINED) sb.append("/" + levelFrom); if (to != Constants.UNDEFINED) { String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeTo != null && !typeTo.equals(context.board().defaultSite())) sb.append("-" + typeTo + " " + newTo); else sb.append("-" + newTo); if (levelTo != Constants.UNDEFINED) sb.append("/" + levelTo); } return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Select "); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && typeTo != null && (!typeFrom.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (levelFrom != Constants.UNDEFINED) sb.append("/" + levelFrom); if (to != Constants.UNDEFINED) { String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeFrom != null && typeTo != null && (!typeTo.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(" - " + typeTo + " " + newTo); else sb.append("-" + newTo); if (levelTo != Constants.UNDEFINED) sb.append("/" + levelTo); } sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final BitSet concepts = new BitSet(); // ---- Swap Pieces concepts if (ludemeConcept.get(Concept.SwapPiecesEffect.id())) concepts.set(Concept.SwapPiecesEffect.id(), true); if (ludemeConcept.get(Concept.SwapPiecesDecision.id())) concepts.set(Concept.SwapPiecesDecision.id(), true); return concepts; } //------------------------------------------------------------------------- @Override public int from() { return from; } @Override public int to() { return (to == Constants.UNDEFINED) ? from : to; } @Override public int levelFrom() { return (levelFrom == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : levelFrom; } @Override public int levelTo() { return (levelTo == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : levelTo; } @Override public SiteType fromType() { return typeFrom; } @Override public SiteType toType() { return typeTo; } @Override public ActionType actionType() { return ActionType.Select; } }
9,659
24.76
107
java
Ludii
Ludii-master/Core/src/other/action/move/ActionSubStackMove.java
package other.action.move; import java.util.BitSet; import java.util.List; import game.Game; import game.rules.play.moves.Moves; import game.types.board.RelationType; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.topology.Topology; import other.topology.TopologyElement; /** * Moves a part of a stack. * * @author Eric.Piette */ public final class ActionSubStackMove extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type of the from site. */ private final SiteType typeFrom; /** From index. */ private final int from; /** The level of the origin. */ private int levelFrom = 0; /** The graph element type of the to site. */ private final SiteType typeTo; /** To index. */ private final int to; /** The level of the target. */ private int levelTo = 0; /** The number of level to move. */ private final int numLevel; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; //-- from data /** Previous What value of the from site. */ private int[] previousWhatFrom; /** Previous Who value of the from site. */ private int[] previousWhoFrom; /** Previous Site state value of the from site. */ private int[] previousStateFrom; /** Previous Rotation value of the from site. */ private int[] previousRotationFrom; /** Previous Piece value of the from site. */ private int[] previousValueFrom; /** The previous hidden info values of the from site before to be removed. */ private boolean[][] previousHiddenFrom; /** The previous hidden what info values of the from site before to be removed. */ private boolean[][] previousHiddenWhatFrom; /** The previous hidden who info values of the from site before to be removed. */ private boolean[][] previousHiddenWhoFrom; /** The previous hidden count info values of the from site before to be removed. */ private boolean[][] previousHiddenCountFrom; /** The previous hidden rotation info values of the from site before to be removed. */ private boolean[][] previousHiddenRotationFrom; /** The previous hidden State info values of the from site before to be removed. */ private boolean[][] previousHiddenStateFrom; /** The previous hidden Value info values of the from site before to be removed. */ private boolean[][] previousHiddenValueFrom; //--- to data /** Previous What of the to site. */ private int[] previousWhatTo; /** Previous Who of the to site. */ private int[] previousWhoTo; /** Previous Site state value of the to site. */ private int[] previousStateTo; /** Previous Rotation value of the to site. */ private int[] previousRotationTo; /** Previous Piece value of the to site. */ private int[] previousValueTo; /** The previous hidden info values of the to site before to be removed. */ private boolean[][] previousHiddenTo; /** The previous hidden what info values of the to site before to be removed. */ private boolean[][] previousHiddenWhatTo; /** The previous hidden who info values of the to site before to be removed. */ private boolean[][] previousHiddenWhoTo; /** The previous hidden count info values of the to site before to be removed. */ private boolean[][] previousHiddenCountTo; /** The previous hidden rotation info values of the to site before to be removed. */ private boolean[][] previousHiddenRotationTo; /** The previous hidden State info values of the to site before to be removed. */ private boolean[][] previousHiddenStateTo; /** The previous hidden Value info values of the to site before to be removed. */ private boolean[][] previousHiddenValueTo; //------------------------------------------------------------------------- /** * @param from The origin. * @param to The target. * @param numLevel The number of pieces in the stack. * @param typeFrom The type of the origin. * @param typeTo The type of the target. */ public ActionSubStackMove ( final SiteType typeFrom, final int from, final SiteType typeTo, final int to, final int numLevel ) { this.from = from; this.to = to; this.numLevel = numLevel; this.typeFrom = typeFrom; this.typeTo = typeTo; } /** * Reconstructs an ActionStackMove object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionSubStackMove(final String detailedString) { assert(detailedString.startsWith("[StackMove:")); final String strTypeFrom = Action.extractData(detailedString, "typeFrom"); typeFrom = (strTypeFrom.isEmpty()) ? null : SiteType.valueOf(strTypeFrom); final String strFrom = Action.extractData(detailedString, "from"); from = Integer.parseInt(strFrom); final String strTypeTo = Action.extractData(detailedString, "typeTo"); typeTo = (strTypeTo.isEmpty()) ? null : SiteType.valueOf(strTypeTo); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strNumLevel = Action.extractData(detailedString, "numLevel"); numLevel = Integer.parseInt(strNumLevel); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { final int contIdA = context.containerId()[from]; final int contIdB = context.containerId()[to]; final ContainerState csFrom = context.state().containerStates()[contIdA]; final ContainerState csTo = context.state().containerStates()[contIdB]; final int sizeStackA = csFrom.sizeStack(from, typeFrom); final int what = csFrom.what(from, typeFrom); // Keep in memory the data of the site from and to (for undo method) if(!alreadyApplied) { final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); previousWhatFrom = new int[sizeStackFrom]; previousWhoFrom = new int[sizeStackFrom]; previousStateFrom = new int[sizeStackFrom]; previousRotationFrom = new int[sizeStackFrom]; previousValueFrom = new int[sizeStackFrom]; for(int lvl = 0 ; lvl < sizeStackFrom; lvl++) { previousWhatFrom[lvl] = csFrom.what(from, lvl, typeFrom); previousWhoFrom[lvl] = csFrom.who(from, lvl, typeFrom); previousStateFrom[lvl] = csFrom.state(from, lvl, typeFrom); previousRotationFrom[lvl] = csFrom.rotation(from, lvl, typeFrom); previousValueFrom[lvl] = csFrom.value(from, lvl, typeFrom); if(context.game().hiddenInformation()) { previousHiddenFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenWhatFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenWhoFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenCountFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenRotationFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenStateFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenValueFrom = new boolean[sizeStackFrom][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenFrom[lvl][pid] = csFrom.isHidden(pid, from, lvl, typeFrom); previousHiddenWhatFrom[lvl][pid] = csFrom.isHiddenWhat(pid, from, lvl, typeFrom); previousHiddenWhoFrom[lvl][pid] = csFrom.isHiddenWho(pid, from, lvl, typeFrom); previousHiddenCountFrom[lvl][pid] = csFrom.isHiddenCount(pid, from, lvl, typeFrom); previousHiddenStateFrom[lvl][pid] = csFrom.isHiddenState(pid, from, lvl, typeFrom); previousHiddenRotationFrom[lvl][pid] = csFrom.isHiddenRotation(pid, from, lvl, typeFrom); previousHiddenValueFrom[lvl][pid] = csFrom.isHiddenValue(pid, from, lvl, typeFrom); } } } final int sizeStackTo = csTo.sizeStack(to, typeTo); previousWhatTo = new int[sizeStackTo]; previousWhoTo = new int[sizeStackTo]; previousStateTo = new int[sizeStackTo]; previousRotationTo = new int[sizeStackTo]; previousValueTo = new int[sizeStackTo]; for(int lvl = 0 ; lvl < sizeStackTo; lvl++) { previousWhatTo[lvl] = csTo.what(to, lvl, typeTo); previousWhoTo[lvl] = csTo.who(to, lvl, typeTo); previousStateTo[lvl] = csTo.state(to, lvl, typeTo); previousRotationTo[lvl] = csTo.rotation(to, lvl, typeTo); previousValueTo[lvl] = csTo.value(to, lvl, typeTo); if(context.game().hiddenInformation()) { previousHiddenTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenWhatTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenWhoTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenCountTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenRotationTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenStateTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenValueTo = new boolean[sizeStackTo][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenTo[lvl][pid] = csTo.isHidden(pid, to, lvl, typeTo); previousHiddenWhatTo[lvl][pid] = csTo.isHiddenWhat(pid, to, lvl, typeTo); previousHiddenWhoTo[lvl][pid] = csTo.isHiddenWho(pid, to, lvl, typeTo); previousHiddenCountTo[lvl][pid] = csTo.isHiddenCount(pid, to, lvl, typeTo); previousHiddenStateTo[lvl][pid] = csTo.isHiddenState(pid, to, lvl, typeTo); previousHiddenRotationTo[lvl][pid] = csTo.isHiddenRotation(pid, to, lvl, typeTo); previousHiddenValueTo[lvl][pid] = csTo.isHiddenValue(pid, to, lvl, typeTo); } } } alreadyApplied = true; } if (what == 0 || sizeStackA < numLevel) return this; final int[] movedElement = new int[numLevel]; final int[] ownerElement = new int[numLevel]; final int[] stateElement = new int[numLevel]; final int[] rotationElement = new int[numLevel]; final int[] valueElement = new int[numLevel]; for (int i = 0; i < numLevel; i++) { final int whatTop = csFrom.what(from, typeFrom); movedElement[i] = whatTop; final int whoTop = csFrom.who(from, typeFrom); ownerElement[i] = whoTop; final int stateTop = csFrom.state(from, typeFrom); stateElement[i] = stateTop; final int rotationTop = csFrom.rotation(from, typeFrom); rotationElement[i] = rotationTop; final int valueTop = csFrom.value(from, typeFrom); valueElement[i] = valueTop; final int topLevel = csFrom.sizeStack(from, typeFrom) - 1; context.state().owned().remove(whoTop, whatTop, from, topLevel, typeFrom); csFrom.remove(context.state(), from, typeFrom); } if (csFrom.sizeStack(from, typeFrom) == 0) csFrom.addToEmpty(from, typeFrom); boolean wasEmpty = (csTo.sizeStack(to, typeTo) == 0); for (int i = movedElement.length - 1; i >= 0; i--) { csTo.addItemGeneric(context.state(), to, movedElement[i], ownerElement[i], stateElement[i], rotationElement[i], valueElement[i], context.game(), typeTo); context.state().owned().add(ownerElement[i], movedElement[i], to, csTo.sizeStack(to, typeTo) - 1, typeTo); } if (wasEmpty && csTo.sizeStack(to, typeTo) != 0) csTo.removeFromEmpty(to, typeTo); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; final Game game = context.game(); final State gameState = context.state(); final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); final int sizeStackTo = csTo.sizeStack(to, typeTo); // We restore the from site for(int lvl = sizeStackFrom -1 ; lvl >= 0; lvl--) csFrom.remove(context.state(), from, lvl, typeFrom); for(int lvl = 0 ; lvl < previousWhatFrom.length; lvl++) { csFrom.addItemGeneric(gameState, from, previousWhatFrom[lvl], previousWhoFrom[lvl], previousStateFrom[lvl], previousRotationFrom[lvl], previousValueFrom[lvl], game, typeFrom); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, lvl, typeFrom, previousHiddenFrom[lvl][pid]); csFrom.setHiddenWhat(gameState, pid, from, lvl, typeFrom, previousHiddenWhatFrom[lvl][pid]); csFrom.setHiddenWho(gameState, pid, from, lvl, typeFrom, previousHiddenWhoFrom[lvl][pid]); csFrom.setHiddenCount(gameState, pid, from, lvl, typeFrom, previousHiddenCountFrom[lvl][pid]); csFrom.setHiddenState(gameState, pid, from, lvl, typeFrom, previousHiddenStateFrom[lvl][pid]); csFrom.setHiddenRotation(gameState, pid, from, lvl, typeFrom, previousHiddenRotationFrom[lvl][pid]); csFrom.setHiddenValue(gameState, pid, from, lvl, typeFrom, previousHiddenValueFrom[lvl][pid]); } } } // We restore the to site for(int lvl = sizeStackTo -1 ; lvl >= 0; lvl--) csTo.remove(context.state(), to, lvl, typeTo); for(int lvl = 0 ; lvl < previousWhatTo.length; lvl++) { csTo.addItemGeneric(gameState, to, previousWhatTo[lvl], previousWhoTo[lvl], previousStateTo[lvl], previousRotationTo[lvl], previousValueTo[lvl], game, typeTo); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, lvl, typeTo, previousHiddenTo[lvl][pid]); csTo.setHiddenWhat(gameState, pid, to, lvl, typeTo, previousHiddenWhatTo[lvl][pid]); csTo.setHiddenWho(gameState, pid, to, lvl, typeTo, previousHiddenWhoTo[lvl][pid]); csTo.setHiddenCount(gameState, pid, to, lvl, typeTo, previousHiddenCountTo[lvl][pid]); csTo.setHiddenState(gameState, pid, to, lvl, typeTo, previousHiddenStateTo[lvl][pid]); csTo.setHiddenRotation(gameState, pid, to, lvl, typeTo, previousHiddenRotationTo[lvl][pid]); csTo.setHiddenValue(gameState, pid, to, lvl, typeTo, previousHiddenValueTo[lvl][pid]); } } } if (csTo.sizeStack(to, typeTo) == 0) csTo.addToEmpty(to, typeTo); if (csFrom.sizeStack(from, typeFrom) != 0) csFrom.removeFromEmpty(from, typeFrom); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[StackMove:"); if (typeFrom != null || (context != null && typeFrom != context.board().defaultSite())) { sb.append("typeFrom=" + typeFrom); sb.append(",from=" + from); } else sb.append("from=" + from); if (typeTo != null || (context != null && typeTo != context.board().defaultSite())) sb.append(",typeTo=" + typeTo); sb.append(",to=" + to); sb.append(",numLevel=" + numLevel); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + numLevel; result = prime * result + (decision ? 1231 : 1237); result = prime * result + from; result = prime * result + to; result = prime * result + ((typeFrom == null) ? 0 : typeFrom.hashCode()); result = prime * result + ((typeTo == null) ? 0 : typeTo.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSubStackMove)) return false; final ActionSubStackMove other = (ActionSubStackMove) obj; return (numLevel == other.numLevel && decision == other.decision && from == other.from && to == other.to && typeFrom == other.typeFrom && typeTo == other.typeTo); } //------------------------------------------------------------------------- @Override public String getDescription() { return "StackMove"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && !typeFrom.equals(context.board().defaultSite())) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (levelFrom != Constants.UNDEFINED) sb.append(":" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeTo != null && !typeTo.equals(context.board().defaultSite())) sb.append("-" + typeTo + " " + newTo); else sb.append("-" + newTo); if (levelTo != Constants.UNDEFINED) sb.append(":" + levelTo); sb.append("^" + numLevel); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Move "); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && typeTo != null && (!typeFrom.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (levelFrom != Constants.UNDEFINED) sb.append("/" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeFrom != null && typeTo != null && (!typeTo.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(" - " + typeTo + " " + newTo); else sb.append("-" + newTo); if (levelTo != Constants.UNDEFINED) sb.append("/" + levelTo); sb.append(" numLevel=" + numLevel); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return typeFrom; } @Override public SiteType toType() { return typeTo; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int levelFrom() { return levelFrom; } @Override public int levelTo() { return levelTo; } /** * To set the level from. */ @Override public void setLevelFrom(final int levelA) { this.levelFrom = levelA; } /** * To set the level to. */ @Override public void setLevelTo(final int levelB) { this.levelTo = levelB; } @Override public ActionType actionType() { return ActionType.StackMove; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final int contIdA = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdB = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csA = context.state().containerStates()[contIdA]; final ContainerState csB = context.state().containerStates()[contIdB]; final int whatA = csA.what(from, typeFrom); final int whatB = csB.what(to, typeTo); final int whoA = csA.who(from, typeFrom); final int whoB = csB.who(to, typeTo); final BitSet concepts = new BitSet(); // ---- Hop concepts if (ludemeConcept.get(Concept.HopDecision.id())) { concepts.set(Concept.HopDecision.id(), true); if (whatA != 0) { final Topology topology = context.topology(); final TopologyElement fromV = topology.getGraphElements(typeFrom).get(from); final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, typeFrom); AbsoluteDirection direction = null; int distance = Constants.UNDEFINED; for (final DirectionFacing facingDirection : directionsSupported) { final AbsoluteDirection absDirection = facingDirection.toAbsolute(); final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), absDirection); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int toRadial = radial.steps()[toIdx].id(); if (toRadial == to) { direction = absDirection; distance = toIdx; break; } } if (direction != null) break; } } if (direction != null) { final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), direction); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < distance; toIdx++) { final int between = radial.steps()[toIdx].id(); final int whatBetween = csA.what(between, typeFrom); final int whoBetween = csA.who(between, typeFrom); if (whatBetween != 0) { if (areEnemies(context, whoA, whoBetween)) { if (whatB == 0) concepts.set(Concept.HopDecisionEnemyToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionEnemyToEnemy.id(), true); else concepts.set(Concept.HopDecisionEnemyToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); concepts.set(Concept.HopCaptureMoreThanOne.id(), true); } } else { if (whatB == 0) concepts.set(Concept.HopDecisionFriendToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionFriendToEnemy.id(), true); else concepts.set(Concept.HopDecisionFriendToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } } } } } } } } if (ludemeConcept.get(Concept.HopEffect.id())) concepts.set(Concept.HopEffect.id(), true); // ---- Step concepts if (ludemeConcept.get(Concept.StepEffect.id())) concepts.set(Concept.StepEffect.id(), true); if (ludemeConcept.get(Concept.StepDecision.id())) { concepts.set(Concept.StepDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.StepDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.StepDecisionToEnemy.id(), true); else concepts.set(Concept.StepDecisionToFriend.id(), true); } } } // ---- Leap concepts if (ludemeConcept.get(Concept.LeapEffect.id())) concepts.set(Concept.LeapEffect.id(), true); if (ludemeConcept.get(Concept.LeapDecision.id())) { concepts.set(Concept.LeapDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.LeapDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.LeapDecisionToEnemy.id(), true); else concepts.set(Concept.LeapDecisionToFriend.id(), true); } } } // ---- Slide concepts if (ludemeConcept.get(Concept.SlideEffect.id())) concepts.set(Concept.SlideEffect.id(), true); if (ludemeConcept.get(Concept.SlideDecision.id())) { concepts.set(Concept.SlideDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.SlideDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.SlideDecisionToEnemy.id(), true); else concepts.set(Concept.SlideDecisionToFriend.id(), true); } } } // ---- FromTo concepts if (ludemeConcept.get(Concept.FromToDecision.id())) { if (contIdA == contIdB) concepts.set(Concept.FromToDecisionWithinBoard.id(), true); else concepts.set(Concept.FromToDecisionBetweenContainers.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.FromToDecisionEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.FromToDecisionEnemy.id(), true); else concepts.set(Concept.FromToDecisionFriend.id(), true); } } } if (ludemeConcept.get(Concept.FromToEffect.id())) concepts.set(Concept.FromToEffect.id(), true); // ---- Swap Pieces concepts if (ludemeConcept.get(Concept.SwapPiecesEffect.id())) concepts.set(Concept.SwapPiecesEffect.id(), true); if (ludemeConcept.get(Concept.SwapPiecesDecision.id())) concepts.set(Concept.SwapPiecesDecision.id(), true); // ---- Sow concepts if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.Sow.id())) concepts.set(Concept.Sow.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.SowBacktracking.id())) concepts.set(Concept.SowBacktracking.id(), true); return concepts; } /** * @param context The context. * @param who1 The id of a player. * @param who2 The id of a player. * @return True if these players are enemies. */ public static boolean areEnemies(final Context context, final int who1, final int who2) { if (who1 == 0 || who2 == 0 || who1 == who2) return false; if (context.game().requiresTeams()) { final TIntArrayList teamMembers = new TIntArrayList(); final int tid = context.state().getTeam(who1); for (int i = 1; i < context.game().players().size(); i++) if (context.state().getTeam(i) == tid) teamMembers.add(i); return !teamMembers.contains(who2); } return who1 != who2; } }
28,056
30.313616
178
java
Ludii
Ludii-master/Core/src/other/action/move/move/ActionMove.java
package other.action.move.move; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; /** * Moves a piece from a site to another (only one piece or one full stack). * * @author Eric.Piette */ @SuppressWarnings("javadoc") public final class ActionMove extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @param typeFrom The graph element type of the from site. * @param from From site index. * @param levelFrom From level index. * @param typeTo The graph element type of the to site. * @param to To site index. * @param levelTo To level index. * @param state The state site of the to site. * @param rotation The rotation value of the to site. * @param value The piece value of the to site. * @param onStacking True if we move a full stack. */ public static BaseAction construct ( final SiteType typeFrom, final int from, final int levelFrom, final SiteType typeTo, final int to, final int levelTo, final int state, final int rotation, final int value, final boolean onStacking ) { if(onStacking) return new ActionMoveStacking(typeFrom, from, levelFrom, typeTo, to, levelTo, state, rotation, value); else if (levelFrom >= 0 && levelTo >= 0) return new ActionMoveLevelFromLevelTo(typeFrom, from, levelFrom, typeTo, to, levelTo, state, rotation, value); else if (levelFrom >= 0) return new ActionMoveLevelFrom(typeFrom, from, levelFrom, typeTo, to, state, rotation, value); else if (levelTo >= 0) return new ActionMoveLevelTo(typeFrom, from, typeTo, to, levelTo, state, rotation, value); else return new ActionMoveTopPiece(typeFrom, from, typeTo, to, state, rotation, value); } /** * Reconstructs an ActionMove object from a detailed String (generated using toDetailedString()) * @param detailedString */ public static BaseAction construct(final String detailedString) { assert (detailedString.startsWith("[Move:")); final String strTypeFrom = Action.extractData(detailedString, "typeFrom"); final SiteType typeFrom = (strTypeFrom.isEmpty()) ? null : SiteType.valueOf(strTypeFrom); final String strFrom = Action.extractData(detailedString, "from"); final int from = Integer.parseInt(strFrom); final String strLevelFrom = Action.extractData(detailedString, "levelFrom"); final int levelFrom = (strLevelFrom.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevelFrom); final String strTypeTo = Action.extractData(detailedString, "typeTo"); final SiteType typeTo = (strTypeTo.isEmpty()) ? null : SiteType.valueOf(strTypeTo); final String strTo = Action.extractData(detailedString, "to"); final int to = Integer.parseInt(strTo); final String strLevelTo = Action.extractData(detailedString, "levelTo"); final int levelTo = (strLevelTo.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevelTo); final String strState = Action.extractData(detailedString, "state"); final int state = (strState.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strState); final String strRotation = Action.extractData(detailedString, "rotation"); final int rotation = (strRotation.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strRotation); final String strValue = Action.extractData(detailedString, "value"); final int value = (strValue.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strValue); final String strStack = Action.extractData(detailedString, "stack"); final boolean onStacking = (strStack.isEmpty()) ? false : Boolean.parseBoolean(strStack); final String strDecision = Action.extractData(detailedString, "decision"); final boolean decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); BaseAction action = null; if(onStacking) action = new ActionMoveStacking(typeFrom, from, levelFrom, typeTo, to, levelTo, state, rotation, value); else if (levelFrom >= 0 && levelTo >= 0) action = new ActionMoveLevelFromLevelTo(typeFrom, from, levelFrom, typeTo, to, levelTo, state, rotation, value); else if (levelFrom >= 0) action = new ActionMoveLevelFrom(typeFrom, from, levelFrom, typeTo, to, state, rotation, value); else if (levelTo >= 0) action = new ActionMoveLevelTo(typeFrom, from, typeTo, to, levelTo, state, rotation, value); else action = new ActionMoveTopPiece(typeFrom, from, typeTo, to, state, rotation, value); action.setDecision(decision); return action; } //------------------------------------------------------------------------- @Override public Action apply ( final Context context, final boolean store ) { throw new UnsupportedOperationException("ActionMove.eval(): Should never be called directly."); } @Override public Action undo(final Context context, boolean discard) { throw new UnsupportedOperationException("ActionMove.undo(): Should never be called directly."); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { // Should never be there return null; } //------------------------------------------------------------------------- @Override public String getDescription() { // Should never be there return null; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { // Should never be there return null; } @Override public ActionType actionType() { return ActionType.Move; } //------------------------------------------------------------------------- }
5,754
32.852941
115
java
Ludii
Ludii-master/Core/src/other/action/move/move/ActionMoveLevelFrom.java
package other.action.move.move; import java.util.BitSet; import java.util.List; import game.Game; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.RelationType; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; import other.topology.Topology; import other.topology.TopologyElement; /** * Moves a piece from a site from a specific level to another at the top level. * * @author Eric.Piette */ public final class ActionMoveLevelFrom extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type of the from site. */ private final SiteType typeFrom; /** From site index. */ private final int from; /** From level index (e.g. stacking game). */ private int levelFrom; /** The graph element type of the to site. */ private final SiteType typeTo; /** To site index. */ private final int to; /** Site state value of the to site. */ private final int state; /** Rotation value of the to site. */ private final int rotation; /** piece value of the to site. */ private final int value; //----------------------Undo Data--------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; //-- from data /** Previous What value of the from site. */ private int[] previousWhatFrom; /** Previous Who value of the from site. */ private int[] previousWhoFrom; /** Previous Site state value of the from site. */ private int[] previousStateFrom; /** Previous Rotation value of the from site. */ private int[] previousRotationFrom; /** Previous Piece value of the from site. */ private int[] previousValueFrom; /** Previous Piece count of the from site. */ private int previousCountFrom; /** The previous hidden info values of the from site before to be removed. */ private boolean[][] previousHiddenFrom; /** The previous hidden what info values of the from site before to be removed. */ private boolean[][] previousHiddenWhatFrom; /** The previous hidden who info values of the from site before to be removed. */ private boolean[][] previousHiddenWhoFrom; /** The previous hidden count info values of the from site before to be removed. */ private boolean[][] previousHiddenCountFrom; /** The previous hidden rotation info values of the from site before to be removed. */ private boolean[][] previousHiddenRotationFrom; /** The previous hidden State info values of the from site before to be removed. */ private boolean[][] previousHiddenStateFrom; /** The previous hidden Value info values of the from site before to be removed. */ private boolean[][] previousHiddenValueFrom; //--- to data /** Previous What of the to site. */ private int[] previousWhatTo; /** Previous Who of the to site. */ private int[] previousWhoTo; /** Previous Site state value of the to site. */ private int[] previousStateTo; /** Previous Rotation value of the to site. */ private int[] previousRotationTo; /** Previous Piece value of the to site. */ private int[] previousValueTo; /** Previous Piece count of the to site. */ private int previousCountTo; /** The previous hidden info values of the to site before to be removed. */ private boolean[][] previousHiddenTo; /** The previous hidden what info values of the to site before to be removed. */ private boolean[][] previousHiddenWhatTo; /** The previous hidden who info values of the to site before to be removed. */ private boolean[][] previousHiddenWhoTo; /** The previous hidden count info values of the to site before to be removed. */ private boolean[][] previousHiddenCountTo; /** The previous hidden rotation info values of the to site before to be removed. */ private boolean[][] previousHiddenRotationTo; /** The previous hidden State info values of the to site before to be removed. */ private boolean[][] previousHiddenStateTo; /** The previous hidden Value info values of the to site before to be removed. */ private boolean[][] previousHiddenValueTo; //------------------------------------------------------------------------- /** * @param typeFrom The graph element type of the from site. * @param from From site index. * @param levelFrom From level index. * @param typeTo The graph element type of the to site. * @param to To site index. * @param state The state site of the to site. * @param rotation The rotation value of the to site. * @param value The piece value of the to site. */ public ActionMoveLevelFrom ( final SiteType typeFrom, final int from, final int levelFrom, final SiteType typeTo, final int to, final int state, final int rotation, final int value ) { this.typeFrom = typeFrom; this.from = from; this.levelFrom = levelFrom; this.typeTo = typeTo; this.to = to; this.state = state; this.rotation = rotation; this.value = value; } //------------------------------------------------------------------------- @Override public Action apply ( final Context context, final boolean store ) { final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final boolean requiresStack = context.currentInstanceContext().game().isStacking(); int currentStateFrom = Constants.UNDEFINED; int currentRotationFrom = Constants.UNDEFINED; int currentValueFrom = Constants.UNDEFINED; Component piece = null; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; // take the local state of the site from currentStateFrom = ((csFrom.what(from, levelFrom, typeFrom) == 0) ? Constants.UNDEFINED : csFrom.state(from, levelFrom, typeFrom)); currentRotationFrom = csFrom.rotation(from, levelFrom, typeFrom); currentValueFrom = csFrom.value(from, levelFrom, typeFrom); // Keep in memory the data of the site from and to (for undo method) if(!alreadyApplied) { final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); previousWhatFrom = new int[sizeStackFrom]; previousWhoFrom = new int[sizeStackFrom]; previousStateFrom = new int[sizeStackFrom]; previousRotationFrom = new int[sizeStackFrom]; previousValueFrom = new int[sizeStackFrom]; previousHiddenFrom = new boolean[sizeStackFrom][]; previousHiddenWhatFrom = new boolean[sizeStackFrom][]; previousHiddenWhoFrom = new boolean[sizeStackFrom][]; previousHiddenCountFrom = new boolean[sizeStackFrom][]; previousHiddenRotationFrom = new boolean[sizeStackFrom][]; previousHiddenStateFrom = new boolean[sizeStackFrom][]; previousHiddenValueFrom = new boolean[sizeStackFrom][]; if(!requiresStack) { previousCountFrom = csFrom.count(from, typeFrom); previousCountTo = csTo.count(to, typeTo); } for(int lvl = 0 ; lvl < sizeStackFrom; lvl++) { previousWhatFrom[lvl] = csFrom.what(from, lvl, typeFrom); previousWhoFrom[lvl] = csFrom.who(from, lvl, typeFrom); previousStateFrom[lvl] = csFrom.state(from, lvl, typeFrom); previousRotationFrom[lvl] = csFrom.rotation(from, lvl, typeFrom); previousValueFrom[lvl] = csFrom.value(from, lvl, typeFrom); if(context.game().hiddenInformation()) { previousHiddenFrom[lvl] = new boolean[context.players().size()]; previousHiddenWhatFrom[lvl] = new boolean[context.players().size()]; previousHiddenWhoFrom[lvl] = new boolean[context.players().size()]; previousHiddenCountFrom[lvl] = new boolean[context.players().size()]; previousHiddenStateFrom[lvl] = new boolean[context.players().size()]; previousHiddenRotationFrom[lvl] = new boolean[context.players().size()]; previousHiddenValueFrom[lvl] = new boolean[context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenFrom[lvl][pid] = csFrom.isHidden(pid, from, lvl, typeFrom); previousHiddenWhatFrom[lvl][pid] = csFrom.isHiddenWhat(pid, from, lvl, typeFrom); previousHiddenWhoFrom[lvl][pid] = csFrom.isHiddenWho(pid, from, lvl, typeFrom); previousHiddenCountFrom[lvl][pid] = csFrom.isHiddenCount(pid, from, lvl, typeFrom); previousHiddenStateFrom[lvl][pid] = csFrom.isHiddenState(pid, from, lvl, typeFrom); previousHiddenRotationFrom[lvl][pid] = csFrom.isHiddenRotation(pid, from, lvl, typeFrom); previousHiddenValueFrom[lvl][pid] = csFrom.isHiddenValue(pid, from, lvl, typeFrom); } } } final int sizeStackTo = csTo.sizeStack(to, typeTo); previousWhatTo = new int[sizeStackTo]; previousWhoTo = new int[sizeStackTo]; previousStateTo = new int[sizeStackTo]; previousRotationTo = new int[sizeStackTo]; previousValueTo = new int[sizeStackTo]; previousHiddenTo = new boolean[sizeStackTo][]; previousHiddenWhatTo = new boolean[sizeStackTo][]; previousHiddenWhoTo = new boolean[sizeStackTo][]; previousHiddenCountTo = new boolean[sizeStackTo][]; previousHiddenRotationTo = new boolean[sizeStackTo][]; previousHiddenStateTo = new boolean[sizeStackTo][]; previousHiddenValueTo = new boolean[sizeStackTo][]; for(int lvl = 0 ; lvl < sizeStackTo; lvl++) { previousWhatTo[lvl] = csTo.what(to, lvl, typeTo); previousWhoTo[lvl] = csTo.who(to, lvl, typeTo); previousStateTo[lvl] = csTo.state(to, lvl, typeTo); previousRotationTo[lvl] = csTo.rotation(to, lvl, typeTo); previousValueTo[lvl] = csTo.value(to, lvl, typeTo); if(context.game().hiddenInformation()) { previousHiddenTo[lvl] = new boolean[context.players().size()]; previousHiddenWhatTo[lvl] = new boolean[context.players().size()]; previousHiddenWhoTo[lvl] = new boolean[context.players().size()]; previousHiddenCountTo[lvl] = new boolean[context.players().size()]; previousHiddenStateTo[lvl] = new boolean[context.players().size()]; previousHiddenRotationTo[lvl] = new boolean[context.players().size()]; previousHiddenValueTo[lvl] = new boolean[context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenTo[lvl][pid] = csTo.isHidden(pid, to, lvl, typeTo); previousHiddenWhatTo[lvl][pid] = csTo.isHiddenWhat(pid, to, lvl, typeTo); previousHiddenWhoTo[lvl][pid] = csTo.isHiddenWho(pid, to, lvl, typeTo); previousHiddenCountTo[lvl][pid] = csTo.isHiddenCount(pid, to, lvl, typeTo); previousHiddenStateTo[lvl][pid] = csTo.isHiddenState(pid, to, lvl, typeTo); previousHiddenRotationTo[lvl][pid] = csTo.isHiddenRotation(pid, to, lvl, typeTo); previousHiddenValueTo[lvl][pid] = csTo.isHiddenValue(pid, to, lvl, typeTo); } } } alreadyApplied = true; } if (!requiresStack) { // If the origin is empty we do not apply this action. if (csFrom.what(from, typeFrom) == 0 && csFrom.count(from, typeFrom) == 0) return this; final int what = csFrom.what(from, typeFrom); final int count = csFrom.count(from, typeFrom); if (count == 1) { csFrom.remove(context.state(), from, typeFrom); // to keep the site of the item in cache for each player if (what != 0) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().remove(owner, what, from, typeFrom); } } else { csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, count - 1, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeFrom); } // update the local state of the site To if (currentStateFrom != Constants.UNDEFINED && state == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentStateFrom, Constants.UNDEFINED, Constants.OFF, typeTo); else if (state != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, state, Constants.UNDEFINED, Constants.OFF, typeTo); // update the rotation state of the site To if (currentRotationFrom != Constants.UNDEFINED && rotation == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentRotationFrom, Constants.OFF, typeTo); else if (rotation != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, rotation, Constants.OFF, typeTo); // update the piece value of the site To if (currentValueFrom != Constants.UNDEFINED && value == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : currentValueFrom), typeTo); else if (value != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : value), typeTo); final int who = (what < 1) ? 0 : context.components()[what].owner(); if (csTo.what(to, typeTo) != 0 && (!context.game().requiresCount() || context.game().requiresCount() && csTo.what(to, typeTo) != what)) { final Component pieceToRemove = context.components()[csTo.what(to, typeTo)]; final int owner = pieceToRemove.owner(); context.state().owned().remove(owner, csTo.what(to, typeTo), to, typeTo); } if (csTo.what(to, typeTo) == what && csTo.count(to, typeTo) > 0) { csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().requiresCount() ? csTo.count(to, typeTo) + 1 : 1), Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeTo); } else { csTo.setSite(context.state(), to, who, what, 1, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeTo); } // to keep the site of the item in cache for each player if (what != 0 && csTo.count(to, typeTo) == 1) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, typeTo); } // We update the structure about track indices if the game uses track. updateOnTrackIndices(what, onTrackIndices, context.board().tracks()); // We keep the update for hidden info. if (context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(context.state(), pid, to, 0, typeTo, csFrom.isHidden(pid, from, 0, typeFrom)); csTo.setHiddenWhat(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWhat(pid, from, 0, typeFrom)); csTo.setHiddenWho(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWho(pid, from, 0, typeFrom)); csTo.setHiddenCount(context.state(), pid, to, 0, typeTo, csFrom.isHiddenCount(pid, from, 0, typeFrom)); csTo.setHiddenRotation(context.state(), pid, to, 0, typeTo, csFrom.isHiddenRotation(pid, from, 0, typeFrom)); csTo.setHiddenState(context.state(), pid, to, 0, typeTo, csFrom.isHiddenState(pid, from, 0, typeFrom)); csTo.setHiddenValue(context.state(), pid, to, 0, typeTo, csFrom.isHiddenValue(pid, from, 0, typeFrom)); if (csFrom.what(from, typeFrom) == 0) { csFrom.setHidden(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWhat(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWho(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenCount(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenRotation(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenValue(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenState(context.state(), pid, from, 0, typeFrom, false); } } } if (csTo.isEmpty(to, typeTo)) { throw new RuntimeException("Did not expect locationTo to be empty at site locnTo="+to+"(who, what,count,state)=(" + csTo.who(to, typeTo) + "," + csTo.what(to, typeTo) + "," + csTo.count(to, typeTo) + "," + csTo.state(to, typeTo) + "," + csTo.state(to, typeTo) + ")"); } } // on a stacking game else { if(from == to) return this; final ContainerState containerFrom = context.state().containerStates()[contIdFrom]; final ContainerState containerTo = context.state().containerStates()[contIdTo]; final int what = containerFrom.what(from, levelFrom, typeFrom); final int newStateTo = (state == Constants.UNDEFINED) ? containerFrom.state(from, levelFrom, typeFrom) : state; final int newRotationTo = (rotation == Constants.UNDEFINED) ? containerFrom.rotation(from, levelFrom, typeFrom) : rotation; final int newValueTo = (value == Constants.UNDEFINED) ? containerFrom.value(from, levelFrom, typeFrom) : value; containerFrom.remove(context.state(), from, levelFrom, typeFrom); if (containerFrom.sizeStack(from, typeFrom) == 0) containerFrom.addToEmpty(from, typeFrom); final int who = (what < 1) ? 0 : context.components()[what].owner(); containerTo.addItemGeneric(context.state(), to, what, who, newStateTo, newRotationTo, newValueTo, context.game(), typeTo); if (containerTo.sizeStack(to, typeTo) != 0) containerTo.removeFromEmpty(to, typeTo); // to keep the site of the item in cache for each player Component pieceFrom = null; int ownerFrom = 0; if (what != 0) { pieceFrom = context.components()[what]; ownerFrom = pieceFrom.owner(); context.state().owned().add(ownerFrom, what, to, containerTo.sizeStack(to, typeTo) - 1, typeTo); context.state().owned().remove(ownerFrom, what, from, levelFrom, typeFrom); } // We update the structure about track indices if the game uses track. updateOnTrackIndices(what, onTrackIndices, context.board().tracks()); } return this; } /** * To update the onTrackIndices after a move. * * @param what The index of the component moved. * @param onTrackIndices The structure onTrackIndices * @param tracks The list of the tracks. */ public void updateOnTrackIndices(final int what, final OnTrackIndices onTrackIndices, final List<Track> tracks) { // We update the structure about track indices if the game uses track. if (what != 0 && onTrackIndices != null) { for (final Track track : tracks) { final int trackIdx = track.trackIdx(); final TIntArrayList indicesLocA = onTrackIndices.locToIndex(trackIdx, from); for (int k = 0; k < indicesLocA.size(); k++) { final int indexA = indicesLocA.getQuick(k); final int countAtIndex = onTrackIndices.whats(trackIdx, what, indicesLocA.getQuick(k)); if (countAtIndex > 0) { onTrackIndices.remove(trackIdx, what, 1, indexA); final TIntArrayList newWhatIndice = onTrackIndices.locToIndexFrom(trackIdx, to, indexA); if (newWhatIndice.size() > 0) { onTrackIndices.add(trackIdx, what, 1, newWhatIndice.getQuick(0)); } else { final TIntArrayList newWhatIndiceIfNotAfter = onTrackIndices.locToIndex(trackIdx, to); if (newWhatIndiceIfNotAfter.size() > 0) onTrackIndices.add(trackIdx, what, 1, newWhatIndiceIfNotAfter.getQuick(0)); } break; } } // If the piece was not in the track but enter on it, we update the structure // corresponding to that track. if (indicesLocA.size() == 0) { final TIntArrayList indicesLocB = onTrackIndices.locToIndex(trackIdx, to); if (indicesLocB.size() != 0) onTrackIndices.add(trackIdx, what, 1, indicesLocB.get(0)); } } } } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; final Game game = context.game(); final State gameState = context.state(); final boolean requiresStack = context.currentInstanceContext().game().isStacking(); final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); final int sizeStackTo = csTo.sizeStack(to, typeTo); if(requiresStack) // Stacking undo. { // We restore the from site for(int lvl = sizeStackFrom -1 ; lvl >= 0; lvl--) csFrom.remove(context.state(), from, lvl, typeFrom); for(int lvl = 0 ; lvl < previousWhatFrom.length; lvl++) { csFrom.addItemGeneric(gameState, from, previousWhatFrom[lvl], previousWhoFrom[lvl], previousStateFrom[lvl], previousRotationFrom[lvl], previousValueFrom[lvl], game, typeFrom); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, lvl, typeFrom, previousHiddenFrom[lvl][pid]); csFrom.setHiddenWhat(gameState, pid, from, lvl, typeFrom, previousHiddenWhatFrom[lvl][pid]); csFrom.setHiddenWho(gameState, pid, from, lvl, typeFrom, previousHiddenWhoFrom[lvl][pid]); csFrom.setHiddenCount(gameState, pid, from, lvl, typeFrom, previousHiddenCountFrom[lvl][pid]); csFrom.setHiddenState(gameState, pid, from, lvl, typeFrom, previousHiddenStateFrom[lvl][pid]); csFrom.setHiddenRotation(gameState, pid, from, lvl, typeFrom, previousHiddenRotationFrom[lvl][pid]); csFrom.setHiddenValue(gameState, pid, from, lvl, typeFrom, previousHiddenValueFrom[lvl][pid]); } } } // We restore the to site for(int lvl = sizeStackTo -1 ; lvl >= 0; lvl--) csTo.remove(context.state(), to, lvl, typeTo); for(int lvl = 0 ; lvl < previousWhatTo.length; lvl++) { csTo.addItemGeneric(gameState, to, previousWhatTo[lvl], previousWhoTo[lvl], previousStateTo[lvl], previousRotationTo[lvl], previousValueTo[lvl], game, typeTo); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, lvl, typeTo, previousHiddenTo[lvl][pid]); csTo.setHiddenWhat(gameState, pid, to, lvl, typeTo, previousHiddenWhatTo[lvl][pid]); csTo.setHiddenWho(gameState, pid, to, lvl, typeTo, previousHiddenWhoTo[lvl][pid]); csTo.setHiddenCount(gameState, pid, to, lvl, typeTo, previousHiddenCountTo[lvl][pid]); csTo.setHiddenState(gameState, pid, to, lvl, typeTo, previousHiddenStateTo[lvl][pid]); csTo.setHiddenRotation(gameState, pid, to, lvl, typeTo, previousHiddenRotationTo[lvl][pid]); csTo.setHiddenValue(gameState, pid, to, lvl, typeTo, previousHiddenValueTo[lvl][pid]); } } } } else // Non stacking undo. { csFrom.remove(context.state(), from, typeFrom); csTo.remove(context.state(), to, typeTo); if(previousCountFrom > 0) csFrom.setSite(context.state(), from, previousWhoFrom[0], previousWhatFrom[0], previousCountFrom, previousStateFrom[0], previousRotationFrom[0], previousValueFrom[0], typeFrom); if(previousCountTo > 0) csTo.setSite(context.state(), to, previousWhoTo[0], previousWhatTo[0], previousCountTo, previousStateTo[0], previousRotationTo[0], previousValueTo[0], typeTo); if(context.game().hiddenInformation()) { if(previousHiddenFrom.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, 0, typeFrom, previousHiddenFrom[0][pid]); csFrom.setHiddenWhat(gameState, pid, from, 0, typeFrom, previousHiddenWhatFrom[0][pid]); csFrom.setHiddenWho(gameState, pid, from, 0, typeFrom, previousHiddenWhoFrom[0][pid]); csFrom.setHiddenCount(gameState, pid, from, 0, typeFrom, previousHiddenCountFrom[0][pid]); csFrom.setHiddenState(gameState, pid, from, 0, typeFrom, previousHiddenStateFrom[0][pid]); csFrom.setHiddenRotation(gameState, pid, from, 0, typeFrom, previousHiddenRotationFrom[0][pid]); csFrom.setHiddenValue(gameState, pid, from, 0, typeFrom, previousHiddenValueFrom[0][pid]); } if(previousHiddenTo.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, 0, typeTo, previousHiddenTo[0][pid]); csTo.setHiddenWhat(gameState, pid, to, 0, typeTo, previousHiddenWhatTo[0][pid]); csTo.setHiddenWho(gameState, pid, to, 0, typeTo, previousHiddenWhoTo[0][pid]); csTo.setHiddenCount(gameState, pid, to, 0, typeTo, previousHiddenCountTo[0][pid]); csTo.setHiddenState(gameState, pid, to, 0, typeTo, previousHiddenStateTo[0][pid]); csTo.setHiddenRotation(gameState, pid, to, 0, typeTo, previousHiddenRotationTo[0][pid]); csTo.setHiddenValue(gameState, pid, to, 0, typeTo, previousHiddenValueTo[0][pid]); } } } if (csTo.sizeStack(to, typeTo) == 0) csTo.addToEmpty(to, typeTo); if (csFrom.sizeStack(from, typeFrom) != 0) csFrom.removeFromEmpty(from, typeFrom); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Move:"); if (typeFrom != null || (context != null && typeFrom != context.board().defaultSite())) { sb.append("typeFrom=" + typeFrom); sb.append(",from=" + from); } else sb.append("from=" + from); sb.append(",levelFrom=" + levelFrom); if (typeTo != null || (context != null && typeTo != context.board().defaultSite())) sb.append(",typeTo=" + typeTo); sb.append(",to=" + to); if (state != Constants.UNDEFINED) sb.append(",state=" + state); if (rotation != Constants.UNDEFINED) sb.append(",rotation=" + rotation); if (value != Constants.UNDEFINED) sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + from; result = prime * result + levelFrom; result = prime * result + to; result = prime * result + state; result = prime * result + rotation; result = prime * result + value; result = prime * result + 1237; result = prime * result + ((typeFrom == null) ? 0 : typeFrom.hashCode()); result = prime * result + ((typeTo == null) ? 0 : typeTo.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionMoveLevelFrom)) return false; final ActionMoveLevelFrom other = (ActionMoveLevelFrom) obj; return (decision == other.decision && from == other.from && levelFrom == other.levelFrom && to == other.to && state == other.state && rotation == other.rotation && value == other.value && typeFrom == other.typeFrom && typeTo == other.typeTo); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Move"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && !typeFrom.equals(context.board().defaultSite())) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (context.game().isStacking()) sb.append("/" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeTo != null && !typeTo.equals(context.board().defaultSite())) sb.append("-" + typeTo + " " + newTo); else sb.append("-" + newTo); if (state != Constants.UNDEFINED) sb.append("=" + state); if (rotation != Constants.UNDEFINED) sb.append(" r" + rotation); if (value != Constants.UNDEFINED) sb.append(" v" + value); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Move "); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && typeTo != null && (!typeFrom.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); sb.append("/" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); if (to < context.game().equipment().containers()[cid].topology().getGraphElements(realType).size()) newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); else // The site is not existing. newTo = "??"; } } if (typeFrom != null && typeTo != null && (!typeTo.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(" - " + typeTo + " " + newTo); else sb.append("-" + newTo); if (state != Constants.UNDEFINED) sb.append(" state=" + state); if (rotation != Constants.UNDEFINED) sb.append(" rotation=" + rotation); if (state != Constants.UNDEFINED) sb.append(" state=" + state); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return typeFrom; } @Override public SiteType toType() { return typeTo; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int levelFrom() { return levelFrom; } @Override public int levelTo() { return Constants.GROUND_LEVEL; } @Override public int state() { return state; } @Override public int rotation() { return rotation; } @Override public int value() { return value; } @Override public int count() { return 1; } @Override public boolean isStacking() { return false; } @Override public void setLevelFrom(final int levelA) { levelFrom = levelA; } @Override public ActionType actionType() { return ActionType.Move; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final int contIdA = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdB = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csA = context.state().containerStates()[contIdA]; final ContainerState csB = context.state().containerStates()[contIdB]; final int whatA = csA.what(from, typeFrom); final int whatB = csB.what(to, typeTo); final int whoA = csA.who(from, typeFrom); final int whoB = csB.who(to, typeTo); final BitSet concepts = new BitSet(); // ---- Hop concepts if (ludemeConcept.get(Concept.HopDecision.id())) { concepts.set(Concept.HopDecision.id(), true); if (whatA != 0) { final Topology topology = context.topology(); final TopologyElement fromV = topology.getGraphElements(typeFrom).get(from); final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, typeFrom); AbsoluteDirection direction = null; int distance = Constants.UNDEFINED; for (final DirectionFacing facingDirection : directionsSupported) { final AbsoluteDirection absDirection = facingDirection.toAbsolute(); final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), absDirection); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int toRadial = radial.steps()[toIdx].id(); if (toRadial == to) { direction = absDirection; distance = toIdx; break; } } if (direction != null) break; } } if (direction != null) { final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), direction); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < distance; toIdx++) { final int between = radial.steps()[toIdx].id(); final int whatBetween = csA.what(between, typeFrom); final int whoBetween = csA.who(between, typeFrom); if (whatBetween != 0) { if (areEnemies(context, whoA, whoBetween)) { if (whatB == 0) concepts.set(Concept.HopDecisionEnemyToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionEnemyToEnemy.id(), true); else concepts.set(Concept.HopDecisionEnemyToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); concepts.set(Concept.HopCaptureMoreThanOne.id(), true); } } else { if (whatB == 0) concepts.set(Concept.HopDecisionFriendToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionFriendToEnemy.id(), true); else concepts.set(Concept.HopDecisionFriendToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } } } } } } } } if (ludemeConcept.get(Concept.HopEffect.id())) concepts.set(Concept.HopEffect.id(), true); // ---- Step concepts if (ludemeConcept.get(Concept.StepEffect.id())) concepts.set(Concept.StepEffect.id(), true); if (ludemeConcept.get(Concept.StepDecision.id())) { concepts.set(Concept.StepDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.StepDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.StepDecisionToEnemy.id(), true); else concepts.set(Concept.StepDecisionToFriend.id(), true); } } } // ---- Leap concepts if (ludemeConcept.get(Concept.LeapEffect.id())) concepts.set(Concept.LeapEffect.id(), true); if (ludemeConcept.get(Concept.LeapDecision.id())) { concepts.set(Concept.LeapDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.LeapDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.LeapDecisionToEnemy.id(), true); else concepts.set(Concept.LeapDecisionToFriend.id(), true); } } } // ---- Slide concepts if (ludemeConcept.get(Concept.SlideEffect.id())) concepts.set(Concept.SlideEffect.id(), true); if (ludemeConcept.get(Concept.SlideDecision.id())) { concepts.set(Concept.SlideDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.SlideDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.SlideDecisionToEnemy.id(), true); else concepts.set(Concept.SlideDecisionToFriend.id(), true); } } } // ---- FromTo concepts if (ludemeConcept.get(Concept.FromToDecision.id())) { if (contIdA == contIdB) concepts.set(Concept.FromToDecisionWithinBoard.id(), true); else concepts.set(Concept.FromToDecisionBetweenContainers.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.FromToDecisionEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.FromToDecisionEnemy.id(), true); else concepts.set(Concept.FromToDecisionFriend.id(), true); } } } if (ludemeConcept.get(Concept.FromToEffect.id())) concepts.set(Concept.FromToEffect.id(), true); // ---- Swap Pieces concepts if (ludemeConcept.get(Concept.SwapPiecesEffect.id())) concepts.set(Concept.SwapPiecesEffect.id(), true); if (ludemeConcept.get(Concept.SwapPiecesDecision.id())) concepts.set(Concept.SwapPiecesDecision.id(), true); // ---- Sow concepts if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.Sow.id())) concepts.set(Concept.Sow.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.SowBacktracking.id())) concepts.set(Concept.SowBacktracking.id(), true); return concepts; } /** * @param context The context. * @param who1 The id of a player. * @param who2 The id of a player. * @return True if these players are enemies. */ public static boolean areEnemies(final Context context, final int who1, final int who2) { if (who1 == 0 || who2 == 0 || who1 == who2) return false; if (context.game().requiresTeams()) { final TIntArrayList teamMembers = new TIntArrayList(); final int tid = context.state().getTeam(who1); for (int i = 1; i < context.game().players().size(); i++) if (context.state().getTeam(i) == tid) teamMembers.add(i); return !teamMembers.contains(who2); } return who1 != who2; } }
40,015
32.626891
181
java
Ludii
Ludii-master/Core/src/other/action/move/move/ActionMoveLevelFromLevelTo.java
package other.action.move.move; import java.util.BitSet; import java.util.List; import game.Game; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.RelationType; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; import other.topology.Topology; import other.topology.TopologyElement; /** * Moves a piece from a site at a specific level to another site at a specific level. * * @author Eric.Piette */ public final class ActionMoveLevelFromLevelTo extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type of the from site. */ private final SiteType typeFrom; /** From site index. */ private final int from; /** From level index (e.g. stacking game). */ private int levelFrom; /** The graph element type of the to site. */ private final SiteType typeTo; /** To site index. */ private final int to; /** To level index (e.g. stacking game). */ private final int levelTo; /** Site state value of the to site. */ private final int state; /** Rotation value of the to site. */ private final int rotation; /** piece value of the to site. */ private final int value; //----------------------Undo Data--------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; //-- from data /** Previous What value of the from site. */ private int[] previousWhatFrom; /** Previous Who value of the from site. */ private int[] previousWhoFrom; /** Previous Site state value of the from site. */ private int[] previousStateFrom; /** Previous Rotation value of the from site. */ private int[] previousRotationFrom; /** Previous Piece value of the from site. */ private int[] previousValueFrom; /** Previous Piece count of the from site. */ private int previousCountFrom; /** The previous hidden info values of the from site before to be removed. */ private boolean[][] previousHiddenFrom; /** The previous hidden what info values of the from site before to be removed. */ private boolean[][] previousHiddenWhatFrom; /** The previous hidden who info values of the from site before to be removed. */ private boolean[][] previousHiddenWhoFrom; /** The previous hidden count info values of the from site before to be removed. */ private boolean[][] previousHiddenCountFrom; /** The previous hidden rotation info values of the from site before to be removed. */ private boolean[][] previousHiddenRotationFrom; /** The previous hidden State info values of the from site before to be removed. */ private boolean[][] previousHiddenStateFrom; /** The previous hidden Value info values of the from site before to be removed. */ private boolean[][] previousHiddenValueFrom; //--- to data /** Previous What of the to site. */ private int[] previousWhatTo; /** Previous Who of the to site. */ private int[] previousWhoTo; /** Previous Site state value of the to site. */ private int[] previousStateTo; /** Previous Rotation value of the to site. */ private int[] previousRotationTo; /** Previous Piece value of the to site. */ private int[] previousValueTo; /** Previous Piece count of the to site. */ private int previousCountTo; /** The previous hidden info values of the to site before to be removed. */ private boolean[][] previousHiddenTo; /** The previous hidden what info values of the to site before to be removed. */ private boolean[][] previousHiddenWhatTo; /** The previous hidden who info values of the to site before to be removed. */ private boolean[][] previousHiddenWhoTo; /** The previous hidden count info values of the to site before to be removed. */ private boolean[][] previousHiddenCountTo; /** The previous hidden rotation info values of the to site before to be removed. */ private boolean[][] previousHiddenRotationTo; /** The previous hidden State info values of the to site before to be removed. */ private boolean[][] previousHiddenStateTo; /** The previous hidden Value info values of the to site before to be removed. */ private boolean[][] previousHiddenValueTo; //------------------------------------------------------------------------- /** * @param typeFrom The graph element type of the from site. * @param from From site index. * @param levelFrom From level index. * @param typeTo The graph element type of the to site. * @param to To site index. * @param levelTo To level index. * @param state The state site of the to site. * @param rotation The rotation value of the to site. * @param value The piece value of the to site. */ public ActionMoveLevelFromLevelTo ( final SiteType typeFrom, final int from, final int levelFrom, final SiteType typeTo, final int to, final int levelTo, final int state, final int rotation, final int value ) { this.typeFrom = typeFrom; this.from = from; this.levelFrom = levelFrom; this.typeTo = typeTo; this.to = to; this.levelTo = levelTo; this.state = state; this.rotation = rotation; this.value = value; } //------------------------------------------------------------------------- @Override public Action apply ( final Context context, final boolean store ) { final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final boolean requiresStack = context.currentInstanceContext().game().isStacking(); int currentStateFrom = Constants.UNDEFINED; int currentRotationFrom = Constants.UNDEFINED; int currentValueFrom = Constants.UNDEFINED; Component piece = null; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; // take the local state of the site from currentStateFrom = ((csFrom.what(from, levelFrom, typeFrom) == 0) ? Constants.UNDEFINED : csFrom.state(from, levelFrom, typeFrom)); currentRotationFrom = csFrom.rotation(from, levelFrom, typeFrom); currentValueFrom = csFrom.value(from, levelFrom, typeFrom); // Keep in memory the data of the site from and to (for undo method) if(!alreadyApplied) { final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); previousWhatFrom = new int[sizeStackFrom]; previousWhoFrom = new int[sizeStackFrom]; previousStateFrom = new int[sizeStackFrom]; previousRotationFrom = new int[sizeStackFrom]; previousValueFrom = new int[sizeStackFrom]; previousHiddenFrom = new boolean[sizeStackFrom][]; previousHiddenWhatFrom = new boolean[sizeStackFrom][]; previousHiddenWhoFrom = new boolean[sizeStackFrom][]; previousHiddenCountFrom = new boolean[sizeStackFrom][]; previousHiddenRotationFrom = new boolean[sizeStackFrom][]; previousHiddenStateFrom = new boolean[sizeStackFrom][]; previousHiddenValueFrom = new boolean[sizeStackFrom][]; if(!requiresStack) { previousCountFrom = csFrom.count(from, typeFrom); previousCountTo = csTo.count(to, typeTo); } for(int lvl = 0 ; lvl < sizeStackFrom; lvl++) { previousWhatFrom[lvl] = csFrom.what(from, lvl, typeFrom); previousWhoFrom[lvl] = csFrom.who(from, lvl, typeFrom); previousStateFrom[lvl] = csFrom.state(from, lvl, typeFrom); previousRotationFrom[lvl] = csFrom.rotation(from, lvl, typeFrom); previousValueFrom[lvl] = csFrom.value(from, lvl, typeFrom); if(context.game().hiddenInformation()) { previousHiddenFrom[lvl] = new boolean[context.players().size()]; previousHiddenWhatFrom[lvl] = new boolean[context.players().size()]; previousHiddenWhoFrom[lvl] = new boolean[context.players().size()]; previousHiddenCountFrom[lvl] = new boolean[context.players().size()]; previousHiddenStateFrom[lvl] = new boolean[context.players().size()]; previousHiddenRotationFrom[lvl] = new boolean[context.players().size()]; previousHiddenValueFrom[lvl] = new boolean[context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenFrom[lvl][pid] = csFrom.isHidden(pid, from, lvl, typeFrom); previousHiddenWhatFrom[lvl][pid] = csFrom.isHiddenWhat(pid, from, lvl, typeFrom); previousHiddenWhoFrom[lvl][pid] = csFrom.isHiddenWho(pid, from, lvl, typeFrom); previousHiddenCountFrom[lvl][pid] = csFrom.isHiddenCount(pid, from, lvl, typeFrom); previousHiddenStateFrom[lvl][pid] = csFrom.isHiddenState(pid, from, lvl, typeFrom); previousHiddenRotationFrom[lvl][pid] = csFrom.isHiddenRotation(pid, from, lvl, typeFrom); previousHiddenValueFrom[lvl][pid] = csFrom.isHiddenValue(pid, from, lvl, typeFrom); } } } final int sizeStackTo = csTo.sizeStack(to, typeTo); previousWhatTo = new int[sizeStackTo]; previousWhoTo = new int[sizeStackTo]; previousStateTo = new int[sizeStackTo]; previousRotationTo = new int[sizeStackTo]; previousValueTo = new int[sizeStackTo]; previousHiddenTo = new boolean[sizeStackTo][]; previousHiddenWhatTo = new boolean[sizeStackTo][]; previousHiddenWhoTo = new boolean[sizeStackTo][]; previousHiddenCountTo = new boolean[sizeStackTo][]; previousHiddenRotationTo = new boolean[sizeStackTo][]; previousHiddenStateTo = new boolean[sizeStackTo][]; previousHiddenValueTo = new boolean[sizeStackTo][]; for(int lvl = 0 ; lvl < sizeStackTo; lvl++) { previousWhatTo[lvl] = csTo.what(to, lvl, typeTo); previousWhoTo[lvl] = csTo.who(to, lvl, typeTo); previousStateTo[lvl] = csTo.state(to, lvl, typeTo); previousRotationTo[lvl] = csTo.rotation(to, lvl, typeTo); previousValueTo[lvl] = csTo.value(to, lvl, typeTo); if(context.game().hiddenInformation()) { previousHiddenTo[lvl] = new boolean[context.players().size()]; previousHiddenWhatTo[lvl] = new boolean[context.players().size()]; previousHiddenWhoTo[lvl] = new boolean[context.players().size()]; previousHiddenCountTo[lvl] = new boolean[context.players().size()]; previousHiddenStateTo[lvl] = new boolean[context.players().size()]; previousHiddenRotationTo[lvl] = new boolean[context.players().size()]; previousHiddenValueTo[lvl] = new boolean[context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenTo[lvl][pid] = csTo.isHidden(pid, to, lvl, typeTo); previousHiddenWhatTo[lvl][pid] = csTo.isHiddenWhat(pid, to, lvl, typeTo); previousHiddenWhoTo[lvl][pid] = csTo.isHiddenWho(pid, to, lvl, typeTo); previousHiddenCountTo[lvl][pid] = csTo.isHiddenCount(pid, to, lvl, typeTo); previousHiddenStateTo[lvl][pid] = csTo.isHiddenState(pid, to, lvl, typeTo); previousHiddenRotationTo[lvl][pid] = csTo.isHiddenRotation(pid, to, lvl, typeTo); previousHiddenValueTo[lvl][pid] = csTo.isHiddenValue(pid, to, lvl, typeTo); } } } alreadyApplied = true; } if (!requiresStack) { // If the origin is empty we do not apply this action. if (csFrom.what(from, typeFrom) == 0 && csFrom.count(from, typeFrom) == 0) return this; final int what = csFrom.what(from, typeFrom); final int count = csFrom.count(from, typeFrom); if (count == 1) { csFrom.remove(context.state(), from, typeFrom); // to keep the site of the item in cache for each player if (what != 0) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().remove(owner, what, from, typeFrom); } } else { csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, count - 1, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeFrom); } // update the local state of the site To if (currentStateFrom != Constants.UNDEFINED && state == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentStateFrom, Constants.UNDEFINED, Constants.OFF, typeTo); else if (state != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, state, Constants.UNDEFINED, Constants.OFF, typeTo); // update the rotation state of the site To if (currentRotationFrom != Constants.UNDEFINED && rotation == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentRotationFrom, Constants.OFF, typeTo); else if (rotation != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, rotation, Constants.OFF, typeTo); // update the piece value of the site To if (currentValueFrom != Constants.UNDEFINED && value == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : currentValueFrom), typeTo); else if (value != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : value), typeTo); final int who = (what < 1) ? 0 : context.components()[what].owner(); if (csTo.what(to, typeTo) != 0 && (!context.game().requiresCount() || context.game().requiresCount() && csTo.what(to, typeTo) != what)) { final Component pieceToRemove = context.components()[csTo.what(to, typeTo)]; final int owner = pieceToRemove.owner(); context.state().owned().remove(owner, csTo.what(to, typeTo), to, typeTo); } if (csTo.what(to, typeTo) == what && csTo.count(to, typeTo) > 0) { csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().requiresCount() ? csTo.count(to, typeTo) + 1 : 1), Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeTo); } else { csTo.setSite(context.state(), to, who, what, 1, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeTo); } // to keep the site of the item in cache for each player if (what != 0 && csTo.count(to, typeTo) == 1) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, typeTo); } // We update the structure about track indices if the game uses track. updateOnTrackIndices(what, onTrackIndices, context.board().tracks()); // We keep the update for hidden info. if (context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(context.state(), pid, to, 0, typeTo, csFrom.isHidden(pid, from, 0, typeFrom)); csTo.setHiddenWhat(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWhat(pid, from, 0, typeFrom)); csTo.setHiddenWho(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWho(pid, from, 0, typeFrom)); csTo.setHiddenCount(context.state(), pid, to, 0, typeTo, csFrom.isHiddenCount(pid, from, 0, typeFrom)); csTo.setHiddenRotation(context.state(), pid, to, 0, typeTo, csFrom.isHiddenRotation(pid, from, 0, typeFrom)); csTo.setHiddenState(context.state(), pid, to, 0, typeTo, csFrom.isHiddenState(pid, from, 0, typeFrom)); csTo.setHiddenValue(context.state(), pid, to, 0, typeTo, csFrom.isHiddenValue(pid, from, 0, typeFrom)); if (csFrom.what(from, typeFrom) == 0) { csFrom.setHidden(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWhat(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWho(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenCount(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenRotation(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenValue(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenState(context.state(), pid, from, 0, typeFrom, false); } } } if (csTo.isEmpty(to, typeTo)) { throw new RuntimeException("Did not expect locationTo to be empty at site locnTo="+to+"(who, what,count,state)=(" + csTo.who(to, typeTo) + "," + csTo.what(to, typeTo) + "," + csTo.count(to, typeTo) + "," + csTo.state(to, typeTo) + "," + csTo.state(to, typeTo) + ")"); } } // on a stacking game else { if(from == to) return this; final ContainerState containerFrom = context.state().containerStates()[contIdFrom]; final ContainerState containerTo = context.state().containerStates()[contIdTo]; final int what = containerFrom.what(from, levelFrom, typeFrom); containerFrom.remove(context.state(), from, levelFrom, typeFrom); if (containerFrom.sizeStack(from, typeFrom) == 0) containerFrom.addToEmpty(from, typeFrom); final int who = (what < 1) ? 0 : context.components()[what].owner(); final int sizeStack = containerTo.sizeStack(to, typeTo); // we update the own list of the pieces on the top of that piece inserted. for (int i = sizeStack - 1; i >= levelTo; i--) { final int owner = containerTo.who(to, i, typeTo); final int pieceTo = containerTo.what(to, i, typeTo); context.state().owned().remove(owner, pieceTo, to, i, typeTo); context.state().owned().add(owner, pieceTo, to, i + 1, typeTo); } // We insert the piece. containerTo.insertCell(context.state(), to, levelTo, what, who, state, rotation, value, context.game()); // we update the own list with the new piece final Component pieceTo = context.components()[what]; final int owner = pieceTo.owner(); context.state().owned().add(owner, what, to, levelTo, typeTo); if (containerTo.sizeStack(to, typeTo) != 0) containerTo.removeFromEmpty(to, typeTo); // to keep the site of the item in cache for each player Component pieceFrom = null; int ownerFrom = 0; if (what != 0) { pieceFrom = context.components()[what]; ownerFrom = pieceFrom.owner(); if (ownerFrom != 0) context.state().owned().remove(ownerFrom, what, from, levelFrom, typeFrom); } // We update the structure about track indices if the game uses track. updateOnTrackIndices(what, onTrackIndices, context.board().tracks()); } return this; } /** * To update the onTrackIndices after a move. * * @param what The index of the component moved. * @param onTrackIndices The structure onTrackIndices * @param tracks The list of the tracks. */ public void updateOnTrackIndices(final int what, final OnTrackIndices onTrackIndices, final List<Track> tracks) { // We update the structure about track indices if the game uses track. if (what != 0 && onTrackIndices != null) { for (final Track track : tracks) { final int trackIdx = track.trackIdx(); final TIntArrayList indicesLocA = onTrackIndices.locToIndex(trackIdx, from); for (int k = 0; k < indicesLocA.size(); k++) { final int indexA = indicesLocA.getQuick(k); final int countAtIndex = onTrackIndices.whats(trackIdx, what, indicesLocA.getQuick(k)); if (countAtIndex > 0) { onTrackIndices.remove(trackIdx, what, 1, indexA); final TIntArrayList newWhatIndice = onTrackIndices.locToIndexFrom(trackIdx, to, indexA); if (newWhatIndice.size() > 0) { onTrackIndices.add(trackIdx, what, 1, newWhatIndice.getQuick(0)); } else { final TIntArrayList newWhatIndiceIfNotAfter = onTrackIndices.locToIndex(trackIdx, to); if (newWhatIndiceIfNotAfter.size() > 0) onTrackIndices.add(trackIdx, what, 1, newWhatIndiceIfNotAfter.getQuick(0)); } break; } } // If the piece was not in the track but enter on it, we update the structure // corresponding to that track. if (indicesLocA.size() == 0) { final TIntArrayList indicesLocB = onTrackIndices.locToIndex(trackIdx, to); if (indicesLocB.size() != 0) onTrackIndices.add(trackIdx, what, 1, indicesLocB.get(0)); } } } } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; final Game game = context.game(); final State gameState = context.state(); final boolean requiresStack = context.currentInstanceContext().game().isStacking(); final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); final int sizeStackTo = csTo.sizeStack(to, typeTo); if(requiresStack) // Stacking undo. { // We restore the from site for(int lvl = sizeStackFrom -1 ; lvl >= 0; lvl--) csFrom.remove(context.state(), from, lvl, typeFrom); for(int lvl = 0 ; lvl < previousWhatFrom.length; lvl++) { csFrom.addItemGeneric(gameState, from, previousWhatFrom[lvl], previousWhoFrom[lvl], previousStateFrom[lvl], previousRotationFrom[lvl], previousValueFrom[lvl], game, typeFrom); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, lvl, typeFrom, previousHiddenFrom[lvl][pid]); csFrom.setHiddenWhat(gameState, pid, from, lvl, typeFrom, previousHiddenWhatFrom[lvl][pid]); csFrom.setHiddenWho(gameState, pid, from, lvl, typeFrom, previousHiddenWhoFrom[lvl][pid]); csFrom.setHiddenCount(gameState, pid, from, lvl, typeFrom, previousHiddenCountFrom[lvl][pid]); csFrom.setHiddenState(gameState, pid, from, lvl, typeFrom, previousHiddenStateFrom[lvl][pid]); csFrom.setHiddenRotation(gameState, pid, from, lvl, typeFrom, previousHiddenRotationFrom[lvl][pid]); csFrom.setHiddenValue(gameState, pid, from, lvl, typeFrom, previousHiddenValueFrom[lvl][pid]); } } } // We restore the to site for(int lvl = sizeStackTo -1 ; lvl >= 0; lvl--) csTo.remove(context.state(), to, lvl, typeTo); for(int lvl = 0 ; lvl < previousWhatTo.length; lvl++) { csTo.addItemGeneric(gameState, to, previousWhatTo[lvl], previousWhoTo[lvl], previousStateTo[lvl], previousRotationTo[lvl], previousValueTo[lvl], game, typeTo); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, lvl, typeTo, previousHiddenTo[lvl][pid]); csTo.setHiddenWhat(gameState, pid, to, lvl, typeTo, previousHiddenWhatTo[lvl][pid]); csTo.setHiddenWho(gameState, pid, to, lvl, typeTo, previousHiddenWhoTo[lvl][pid]); csTo.setHiddenCount(gameState, pid, to, lvl, typeTo, previousHiddenCountTo[lvl][pid]); csTo.setHiddenState(gameState, pid, to, lvl, typeTo, previousHiddenStateTo[lvl][pid]); csTo.setHiddenRotation(gameState, pid, to, lvl, typeTo, previousHiddenRotationTo[lvl][pid]); csTo.setHiddenValue(gameState, pid, to, lvl, typeTo, previousHiddenValueTo[lvl][pid]); } } } } else // Non stacking undo. { csFrom.remove(context.state(), from, typeFrom); csTo.remove(context.state(), to, typeTo); if(previousCountFrom > 0) csFrom.setSite(context.state(), from, previousWhoFrom[0], previousWhatFrom[0], previousCountFrom, previousStateFrom[0], previousRotationFrom[0], previousValueFrom[0], typeFrom); if(previousCountTo > 0) csTo.setSite(context.state(), to, previousWhoTo[0], previousWhatTo[0], previousCountTo, previousStateTo[0], previousRotationTo[0], previousValueTo[0], typeTo); if(context.game().hiddenInformation()) { if(previousHiddenFrom.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, 0, typeFrom, previousHiddenFrom[0][pid]); csFrom.setHiddenWhat(gameState, pid, from, 0, typeFrom, previousHiddenWhatFrom[0][pid]); csFrom.setHiddenWho(gameState, pid, from, 0, typeFrom, previousHiddenWhoFrom[0][pid]); csFrom.setHiddenCount(gameState, pid, from, 0, typeFrom, previousHiddenCountFrom[0][pid]); csFrom.setHiddenState(gameState, pid, from, 0, typeFrom, previousHiddenStateFrom[0][pid]); csFrom.setHiddenRotation(gameState, pid, from, 0, typeFrom, previousHiddenRotationFrom[0][pid]); csFrom.setHiddenValue(gameState, pid, from, 0, typeFrom, previousHiddenValueFrom[0][pid]); } if(previousHiddenTo.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, 0, typeTo, previousHiddenTo[0][pid]); csTo.setHiddenWhat(gameState, pid, to, 0, typeTo, previousHiddenWhatTo[0][pid]); csTo.setHiddenWho(gameState, pid, to, 0, typeTo, previousHiddenWhoTo[0][pid]); csTo.setHiddenCount(gameState, pid, to, 0, typeTo, previousHiddenCountTo[0][pid]); csTo.setHiddenState(gameState, pid, to, 0, typeTo, previousHiddenStateTo[0][pid]); csTo.setHiddenRotation(gameState, pid, to, 0, typeTo, previousHiddenRotationTo[0][pid]); csTo.setHiddenValue(gameState, pid, to, 0, typeTo, previousHiddenValueTo[0][pid]); } } } if (csTo.sizeStack(to, typeTo) == 0) csTo.addToEmpty(to, typeTo); if (csFrom.sizeStack(from, typeFrom) != 0) csFrom.removeFromEmpty(from, typeFrom); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Move:"); if (typeFrom != null || (context != null && typeFrom != context.board().defaultSite())) { sb.append("typeFrom=" + typeFrom); sb.append(",from=" + from); } else sb.append("from=" + from); sb.append(",levelFrom=" + levelFrom); if (typeTo != null || (context != null && typeTo != context.board().defaultSite())) sb.append(",typeTo=" + typeTo); sb.append(",to=" + to); sb.append(",levelTo=" + levelTo); if (state != Constants.UNDEFINED) sb.append(",state=" + state); if (rotation != Constants.UNDEFINED) sb.append(",rotation=" + rotation); if (value != Constants.UNDEFINED) sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + from; result = prime * result + levelFrom; result = prime * result + to; result = prime * result + levelTo; result = prime * result + state; result = prime * result + rotation; result = prime * result + value; result = prime * result + 1237; result = prime * result + ((typeFrom == null) ? 0 : typeFrom.hashCode()); result = prime * result + ((typeTo == null) ? 0 : typeTo.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionMoveLevelFromLevelTo)) return false; final ActionMoveLevelFromLevelTo other = (ActionMoveLevelFromLevelTo) obj; return (decision == other.decision && from == other.from && levelFrom == other.levelFrom && to == other.to && levelTo == other.levelTo && state == other.state && rotation == other.rotation && value == other.value && typeFrom == other.typeFrom && typeTo == other.typeTo); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Move"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && !typeFrom.equals(context.board().defaultSite())) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (context.game().isStacking()) sb.append("/" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeTo != null && !typeTo.equals(context.board().defaultSite())) sb.append("-" + typeTo + " " + newTo); else sb.append("-" + newTo); sb.append("/" + levelTo); if (state != Constants.UNDEFINED) sb.append("=" + state); if (rotation != Constants.UNDEFINED) sb.append(" r" + rotation); if (value != Constants.UNDEFINED) sb.append(" v" + value); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Move "); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && typeTo != null && (!typeFrom.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); sb.append("/" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); if (to < context.game().equipment().containers()[cid].topology().getGraphElements(realType).size()) newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); else // The site is not existing. newTo = "??"; } } if (typeFrom != null && typeTo != null && (!typeTo.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(" - " + typeTo + " " + newTo); else sb.append("-" + newTo); sb.append("/" + levelTo); if (state != Constants.UNDEFINED) sb.append(" state=" + state); if (rotation != Constants.UNDEFINED) sb.append(" rotation=" + rotation); if (state != Constants.UNDEFINED) sb.append(" state=" + state); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return typeFrom; } @Override public SiteType toType() { return typeTo; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int levelFrom() { return levelFrom; } @Override public int levelTo() { return levelTo; } @Override public int state() { return state; } @Override public int rotation() { return rotation; } @Override public int value() { return value; } @Override public int count() { return 1; } @Override public boolean isStacking() { return false; } @Override public void setLevelFrom(final int levelA) { levelFrom = levelA; } @Override public ActionType actionType() { return ActionType.Move; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final int contIdA = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdB = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csA = context.state().containerStates()[contIdA]; final ContainerState csB = context.state().containerStates()[contIdB]; final int whatA = csA.what(from, typeFrom); final int whatB = csB.what(to, typeTo); final int whoA = csA.who(from, typeFrom); final int whoB = csB.who(to, typeTo); final BitSet concepts = new BitSet(); // ---- Hop concepts if (ludemeConcept.get(Concept.HopDecision.id())) { concepts.set(Concept.HopDecision.id(), true); if (whatA != 0) { final Topology topology = context.topology(); final TopologyElement fromV = topology.getGraphElements(typeFrom).get(from); final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, typeFrom); AbsoluteDirection direction = null; int distance = Constants.UNDEFINED; for (final DirectionFacing facingDirection : directionsSupported) { final AbsoluteDirection absDirection = facingDirection.toAbsolute(); final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), absDirection); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int toRadial = radial.steps()[toIdx].id(); if (toRadial == to) { direction = absDirection; distance = toIdx; break; } } if (direction != null) break; } } if (direction != null) { final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), direction); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < distance; toIdx++) { final int between = radial.steps()[toIdx].id(); final int whatBetween = csA.what(between, typeFrom); final int whoBetween = csA.who(between, typeFrom); if (whatBetween != 0) { if (areEnemies(context, whoA, whoBetween)) { if (whatB == 0) concepts.set(Concept.HopDecisionEnemyToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionEnemyToEnemy.id(), true); else concepts.set(Concept.HopDecisionEnemyToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); concepts.set(Concept.HopCaptureMoreThanOne.id(), true); } } else { if (whatB == 0) concepts.set(Concept.HopDecisionFriendToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionFriendToEnemy.id(), true); else concepts.set(Concept.HopDecisionFriendToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } } } } } } } } if (ludemeConcept.get(Concept.HopEffect.id())) concepts.set(Concept.HopEffect.id(), true); // ---- Step concepts if (ludemeConcept.get(Concept.StepEffect.id())) concepts.set(Concept.StepEffect.id(), true); if (ludemeConcept.get(Concept.StepDecision.id())) { concepts.set(Concept.StepDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.StepDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.StepDecisionToEnemy.id(), true); else concepts.set(Concept.StepDecisionToFriend.id(), true); } } } // ---- Leap concepts if (ludemeConcept.get(Concept.LeapEffect.id())) concepts.set(Concept.LeapEffect.id(), true); if (ludemeConcept.get(Concept.LeapDecision.id())) { concepts.set(Concept.LeapDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.LeapDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.LeapDecisionToEnemy.id(), true); else concepts.set(Concept.LeapDecisionToFriend.id(), true); } } } // ---- Slide concepts if (ludemeConcept.get(Concept.SlideEffect.id())) concepts.set(Concept.SlideEffect.id(), true); if (ludemeConcept.get(Concept.SlideDecision.id())) { concepts.set(Concept.SlideDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.SlideDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.SlideDecisionToEnemy.id(), true); else concepts.set(Concept.SlideDecisionToFriend.id(), true); } } } // ---- FromTo concepts if (ludemeConcept.get(Concept.FromToDecision.id())) { if (contIdA == contIdB) concepts.set(Concept.FromToDecisionWithinBoard.id(), true); else concepts.set(Concept.FromToDecisionBetweenContainers.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.FromToDecisionEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.FromToDecisionEnemy.id(), true); else concepts.set(Concept.FromToDecisionFriend.id(), true); } } } if (ludemeConcept.get(Concept.FromToEffect.id())) concepts.set(Concept.FromToEffect.id(), true); // ---- Swap Pieces concepts if (ludemeConcept.get(Concept.SwapPiecesEffect.id())) concepts.set(Concept.SwapPiecesEffect.id(), true); if (ludemeConcept.get(Concept.SwapPiecesDecision.id())) concepts.set(Concept.SwapPiecesDecision.id(), true); // ---- Sow concepts if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.Sow.id())) concepts.set(Concept.Sow.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.SowBacktracking.id())) concepts.set(Concept.SowBacktracking.id(), true); return concepts; } /** * @param context The context. * @param who1 The id of a player. * @param who2 The id of a player. * @return True if these players are enemies. */ public static boolean areEnemies(final Context context, final int who1, final int who2) { if (who1 == 0 || who2 == 0 || who1 == who2) return false; if (context.game().requiresTeams()) { final TIntArrayList teamMembers = new TIntArrayList(); final int tid = context.state().getTeam(who1); for (int i = 1; i < context.game().players().size(); i++) if (context.state().getTeam(i) == tid) teamMembers.add(i); return !teamMembers.contains(who2); } return who1 != who2; } }
40,600
32.38898
181
java
Ludii
Ludii-master/Core/src/other/action/move/move/ActionMoveLevelTo.java
package other.action.move.move; import java.util.BitSet; import java.util.List; import game.Game; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.RelationType; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; import other.topology.Topology; import other.topology.TopologyElement; /** * Moves a piece from a site to another (only the top piece). * * @author Eric.Piette */ public final class ActionMoveLevelTo extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type of the from site. */ private final SiteType typeFrom; /** From site index. */ private final int from; /** The graph element type of the to site. */ private final SiteType typeTo; /** To site index. */ private final int to; /** To level index (e.g. stacking game). */ private final int levelTo; /** Site state value of the to site. */ private final int state; /** Rotation value of the to site. */ private final int rotation; /** piece value of the to site. */ private final int value; //----------------------Undo Data--------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; //-- from data /** Previous What value of the from site. */ private int[] previousWhatFrom; /** Previous Who value of the from site. */ private int[] previousWhoFrom; /** Previous Site state value of the from site. */ private int[] previousStateFrom; /** Previous Rotation value of the from site. */ private int[] previousRotationFrom; /** Previous Piece value of the from site. */ private int[] previousValueFrom; /** Previous Piece count of the from site. */ private int previousCountFrom; /** The previous hidden info values of the from site before to be removed. */ private boolean[][] previousHiddenFrom; /** The previous hidden what info values of the from site before to be removed. */ private boolean[][] previousHiddenWhatFrom; /** The previous hidden who info values of the from site before to be removed. */ private boolean[][] previousHiddenWhoFrom; /** The previous hidden count info values of the from site before to be removed. */ private boolean[][] previousHiddenCountFrom; /** The previous hidden rotation info values of the from site before to be removed. */ private boolean[][] previousHiddenRotationFrom; /** The previous hidden State info values of the from site before to be removed. */ private boolean[][] previousHiddenStateFrom; /** The previous hidden Value info values of the from site before to be removed. */ private boolean[][] previousHiddenValueFrom; //--- to data /** Previous What of the to site. */ private int[] previousWhatTo; /** Previous Who of the to site. */ private int[] previousWhoTo; /** Previous Site state value of the to site. */ private int[] previousStateTo; /** Previous Rotation value of the to site. */ private int[] previousRotationTo; /** Previous Piece value of the to site. */ private int[] previousValueTo; /** Previous Piece count of the to site. */ private int previousCountTo; /** The previous hidden info values of the to site before to be removed. */ private boolean[][] previousHiddenTo; /** The previous hidden what info values of the to site before to be removed. */ private boolean[][] previousHiddenWhatTo; /** The previous hidden who info values of the to site before to be removed. */ private boolean[][] previousHiddenWhoTo; /** The previous hidden count info values of the to site before to be removed. */ private boolean[][] previousHiddenCountTo; /** The previous hidden rotation info values of the to site before to be removed. */ private boolean[][] previousHiddenRotationTo; /** The previous hidden State info values of the to site before to be removed. */ private boolean[][] previousHiddenStateTo; /** The previous hidden Value info values of the to site before to be removed. */ private boolean[][] previousHiddenValueTo; //------------------------------------------------------------------------- /** * @param typeFrom The graph element type of the from site. * @param from From site index. * @param typeTo The graph element type of the to site. * @param to To site index. * @param levelTo To level index. * @param state The state site of the to site. * @param rotation The rotation value of the to site. * @param value The piece value of the to site. */ public ActionMoveLevelTo ( final SiteType typeFrom, final int from, final SiteType typeTo, final int to, final int levelTo, final int state, final int rotation, final int value ) { this.typeFrom = typeFrom; this.from = from; this.typeTo = typeTo; this.to = to; this.levelTo = levelTo; this.state = state; this.rotation = rotation; this.value = value; } //------------------------------------------------------------------------- @Override public Action apply ( final Context context, final boolean store ) { final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final boolean requiresStack = context.currentInstanceContext().game().isStacking(); int currentStateFrom = Constants.UNDEFINED; int currentRotationFrom = Constants.UNDEFINED; int currentValueFrom = Constants.UNDEFINED; Component piece = null; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; // take the local state of the site from currentStateFrom = ((csFrom.what(from, typeFrom) == 0) ? Constants.UNDEFINED : csFrom.state(from, typeFrom)); currentRotationFrom = csFrom.rotation(from, typeFrom); currentValueFrom = csFrom.value(from, typeFrom); // Keep in memory the data of the site from and to (for undo method) if(!alreadyApplied) { final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); previousWhatFrom = new int[sizeStackFrom]; previousWhoFrom = new int[sizeStackFrom]; previousStateFrom = new int[sizeStackFrom]; previousRotationFrom = new int[sizeStackFrom]; previousValueFrom = new int[sizeStackFrom]; previousHiddenFrom = new boolean[sizeStackFrom][]; previousHiddenWhatFrom = new boolean[sizeStackFrom][]; previousHiddenWhoFrom = new boolean[sizeStackFrom][]; previousHiddenCountFrom = new boolean[sizeStackFrom][]; previousHiddenRotationFrom = new boolean[sizeStackFrom][]; previousHiddenStateFrom = new boolean[sizeStackFrom][]; previousHiddenValueFrom = new boolean[sizeStackFrom][]; if(!requiresStack) { previousCountFrom = csFrom.count(from, typeFrom); previousCountTo = csTo.count(to, typeTo); } for(int lvl = 0 ; lvl < sizeStackFrom; lvl++) { previousWhatFrom[lvl] = csFrom.what(from, lvl, typeFrom); previousWhoFrom[lvl] = csFrom.who(from, lvl, typeFrom); previousStateFrom[lvl] = csFrom.state(from, lvl, typeFrom); previousRotationFrom[lvl] = csFrom.rotation(from, lvl, typeFrom); previousValueFrom[lvl] = csFrom.value(from, lvl, typeFrom); if(context.game().hiddenInformation()) { previousHiddenFrom[lvl] = new boolean[context.players().size()]; previousHiddenWhatFrom[lvl] = new boolean[context.players().size()]; previousHiddenWhoFrom[lvl] = new boolean[context.players().size()]; previousHiddenCountFrom[lvl] = new boolean[context.players().size()]; previousHiddenStateFrom[lvl] = new boolean[context.players().size()]; previousHiddenRotationFrom[lvl] = new boolean[context.players().size()]; previousHiddenValueFrom[lvl] = new boolean[context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenFrom[lvl][pid] = csFrom.isHidden(pid, from, lvl, typeFrom); previousHiddenWhatFrom[lvl][pid] = csFrom.isHiddenWhat(pid, from, lvl, typeFrom); previousHiddenWhoFrom[lvl][pid] = csFrom.isHiddenWho(pid, from, lvl, typeFrom); previousHiddenCountFrom[lvl][pid] = csFrom.isHiddenCount(pid, from, lvl, typeFrom); previousHiddenStateFrom[lvl][pid] = csFrom.isHiddenState(pid, from, lvl, typeFrom); previousHiddenRotationFrom[lvl][pid] = csFrom.isHiddenRotation(pid, from, lvl, typeFrom); previousHiddenValueFrom[lvl][pid] = csFrom.isHiddenValue(pid, from, lvl, typeFrom); } } } final int sizeStackTo = csTo.sizeStack(to, typeTo); previousWhatTo = new int[sizeStackTo]; previousWhoTo = new int[sizeStackTo]; previousStateTo = new int[sizeStackTo]; previousRotationTo = new int[sizeStackTo]; previousValueTo = new int[sizeStackTo]; previousHiddenTo = new boolean[sizeStackTo][]; previousHiddenWhatTo = new boolean[sizeStackTo][]; previousHiddenWhoTo = new boolean[sizeStackTo][]; previousHiddenCountTo = new boolean[sizeStackTo][]; previousHiddenRotationTo = new boolean[sizeStackTo][]; previousHiddenStateTo = new boolean[sizeStackTo][]; previousHiddenValueTo = new boolean[sizeStackTo][]; for(int lvl = 0 ; lvl < sizeStackTo; lvl++) { previousWhatTo[lvl] = csTo.what(to, lvl, typeTo); previousWhoTo[lvl] = csTo.who(to, lvl, typeTo); previousStateTo[lvl] = csTo.state(to, lvl, typeTo); previousRotationTo[lvl] = csTo.rotation(to, lvl, typeTo); previousValueTo[lvl] = csTo.value(to, lvl, typeTo); if(context.game().hiddenInformation()) { previousHiddenTo[lvl] = new boolean[context.players().size()]; previousHiddenWhatTo[lvl] = new boolean[context.players().size()]; previousHiddenWhoTo[lvl] = new boolean[context.players().size()]; previousHiddenCountTo[lvl] = new boolean[context.players().size()]; previousHiddenStateTo[lvl] = new boolean[context.players().size()]; previousHiddenRotationTo[lvl] = new boolean[context.players().size()]; previousHiddenValueTo[lvl] = new boolean[context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenTo[lvl][pid] = csTo.isHidden(pid, to, lvl, typeTo); previousHiddenWhatTo[lvl][pid] = csTo.isHiddenWhat(pid, to, lvl, typeTo); previousHiddenWhoTo[lvl][pid] = csTo.isHiddenWho(pid, to, lvl, typeTo); previousHiddenCountTo[lvl][pid] = csTo.isHiddenCount(pid, to, lvl, typeTo); previousHiddenStateTo[lvl][pid] = csTo.isHiddenState(pid, to, lvl, typeTo); previousHiddenRotationTo[lvl][pid] = csTo.isHiddenRotation(pid, to, lvl, typeTo); previousHiddenValueTo[lvl][pid] = csTo.isHiddenValue(pid, to, lvl, typeTo); } } } alreadyApplied = true; } if (!requiresStack) { // If the origin is empty we do not apply this action. if (csFrom.what(from, typeFrom) == 0 && csFrom.count(from, typeFrom) == 0) return this; final int what = csFrom.what(from, typeFrom); final int count = csFrom.count(from, typeFrom); if (count == 1) { csFrom.remove(context.state(), from, typeFrom); // to keep the site of the item in cache for each player if (what != 0) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().remove(owner, what, from, typeFrom); } } else { csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, count - 1, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeFrom); } // update the local state of the site To if (currentStateFrom != Constants.UNDEFINED && state == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentStateFrom, Constants.UNDEFINED, Constants.OFF, typeTo); else if (state != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, state, Constants.UNDEFINED, Constants.OFF, typeTo); // update the rotation state of the site To if (currentRotationFrom != Constants.UNDEFINED && rotation == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentRotationFrom, Constants.OFF, typeTo); else if (rotation != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, rotation, Constants.OFF, typeTo); // update the piece value of the site To if (currentValueFrom != Constants.UNDEFINED && value == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : currentValueFrom), typeTo); else if (value != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : value), typeTo); final int who = (what < 1) ? 0 : context.components()[what].owner(); if (csTo.what(to, typeTo) != 0 && (!context.game().requiresCount() || context.game().requiresCount() && csTo.what(to, typeTo) != what)) { final Component pieceToRemove = context.components()[csTo.what(to, typeTo)]; final int owner = pieceToRemove.owner(); context.state().owned().remove(owner, csTo.what(to, typeTo), to, typeTo); } if (csTo.what(to, typeTo) == what && csTo.count(to, typeTo) > 0) { csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().requiresCount() ? csTo.count(to, typeTo) + 1 : 1), Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeTo); } else { csTo.setSite(context.state(), to, who, what, 1, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeTo); } // to keep the site of the item in cache for each player if (what != 0 && csTo.count(to, typeTo) == 1) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, typeTo); } // We update the structure about track indices if the game uses track. updateOnTrackIndices(what, onTrackIndices, context.board().tracks()); // We keep the update for hidden info. if (context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(context.state(), pid, to, 0, typeTo, csFrom.isHidden(pid, from, 0, typeFrom)); csTo.setHiddenWhat(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWhat(pid, from, 0, typeFrom)); csTo.setHiddenWho(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWho(pid, from, 0, typeFrom)); csTo.setHiddenCount(context.state(), pid, to, 0, typeTo, csFrom.isHiddenCount(pid, from, 0, typeFrom)); csTo.setHiddenRotation(context.state(), pid, to, 0, typeTo, csFrom.isHiddenRotation(pid, from, 0, typeFrom)); csTo.setHiddenState(context.state(), pid, to, 0, typeTo, csFrom.isHiddenState(pid, from, 0, typeFrom)); csTo.setHiddenValue(context.state(), pid, to, 0, typeTo, csFrom.isHiddenValue(pid, from, 0, typeFrom)); if (csFrom.what(from, typeFrom) == 0) { csFrom.setHidden(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWhat(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWho(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenCount(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenRotation(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenValue(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenState(context.state(), pid, from, 0, typeFrom, false); } } } if (csTo.isEmpty(to, typeTo)) { throw new RuntimeException("Did not expect locationTo to be empty at site locnTo="+to+"(who, what,count,state)=(" + csTo.who(to, typeTo) + "," + csTo.what(to, typeTo) + "," + csTo.count(to, typeTo) + "," + csTo.state(to, typeTo) + "," + csTo.state(to, typeTo) + ")"); } } // on a stacking game else { if(from == to) return this; final ContainerState containerFrom = context.state().containerStates()[contIdFrom]; final ContainerState containerTo = context.state().containerStates()[contIdTo]; final int what = containerFrom.what(from, typeFrom); containerFrom.remove(context.state(), from, typeFrom); if (containerFrom.sizeStack(from, typeFrom) == 0) containerFrom.addToEmpty(from, typeFrom); final int who = (what < 1) ? 0 : context.components()[what].owner(); if (!context.game().hasCard()) containerTo.insert(context.state(), typeTo, to, levelTo, what, who, state, rotation, value, context.game()); if (containerTo.sizeStack(to, typeTo) != 0) containerTo.removeFromEmpty(to, typeTo); // to keep the site of the item in cache for each player Component pieceFrom = null; int ownerFrom = 0; if (what != 0) { pieceFrom = context.components()[what]; ownerFrom = pieceFrom.owner(); context.state().owned().add(ownerFrom, what, to, containerTo.sizeStack(to, typeTo) - 1, typeTo); context.state().owned().remove(ownerFrom, what, from, containerFrom.sizeStack(from, typeFrom), typeFrom); } // We update the structure about track indices if the game uses track. updateOnTrackIndices(what, onTrackIndices, context.board().tracks()); } return this; } /** * To update the onTrackIndices after a move. * * @param what The index of the component moved. * @param onTrackIndices The structure onTrackIndices * @param tracks The list of the tracks. */ public void updateOnTrackIndices(final int what, final OnTrackIndices onTrackIndices, final List<Track> tracks) { // We update the structure about track indices if the game uses track. if (what != 0 && onTrackIndices != null) { for (final Track track : tracks) { final int trackIdx = track.trackIdx(); final TIntArrayList indicesLocA = onTrackIndices.locToIndex(trackIdx, from); for (int k = 0; k < indicesLocA.size(); k++) { final int indexA = indicesLocA.getQuick(k); final int countAtIndex = onTrackIndices.whats(trackIdx, what, indicesLocA.getQuick(k)); if (countAtIndex > 0) { onTrackIndices.remove(trackIdx, what, 1, indexA); final TIntArrayList newWhatIndice = onTrackIndices.locToIndexFrom(trackIdx, to, indexA); if (newWhatIndice.size() > 0) { onTrackIndices.add(trackIdx, what, 1, newWhatIndice.getQuick(0)); } else { final TIntArrayList newWhatIndiceIfNotAfter = onTrackIndices.locToIndex(trackIdx, to); if (newWhatIndiceIfNotAfter.size() > 0) onTrackIndices.add(trackIdx, what, 1, newWhatIndiceIfNotAfter.getQuick(0)); } break; } } // If the piece was not in the track but enter on it, we update the structure // corresponding to that track. if (indicesLocA.size() == 0) { final TIntArrayList indicesLocB = onTrackIndices.locToIndex(trackIdx, to); if (indicesLocB.size() != 0) onTrackIndices.add(trackIdx, what, 1, indicesLocB.get(0)); } } } } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; final Game game = context.game(); final State gameState = context.state(); final boolean requiresStack = context.currentInstanceContext().game().isStacking(); final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); final int sizeStackTo = csTo.sizeStack(to, typeTo); if(requiresStack) // Stacking undo. { // We restore the from site for(int lvl = sizeStackFrom -1 ; lvl >= 0; lvl--) csFrom.remove(context.state(), from, lvl, typeFrom); for(int lvl = 0 ; lvl < previousWhatFrom.length; lvl++) { csFrom.addItemGeneric(gameState, from, previousWhatFrom[lvl], previousWhoFrom[lvl], previousStateFrom[lvl], previousRotationFrom[lvl], previousValueFrom[lvl], game, typeFrom); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, lvl, typeFrom, previousHiddenFrom[lvl][pid]); csFrom.setHiddenWhat(gameState, pid, from, lvl, typeFrom, previousHiddenWhatFrom[lvl][pid]); csFrom.setHiddenWho(gameState, pid, from, lvl, typeFrom, previousHiddenWhoFrom[lvl][pid]); csFrom.setHiddenCount(gameState, pid, from, lvl, typeFrom, previousHiddenCountFrom[lvl][pid]); csFrom.setHiddenState(gameState, pid, from, lvl, typeFrom, previousHiddenStateFrom[lvl][pid]); csFrom.setHiddenRotation(gameState, pid, from, lvl, typeFrom, previousHiddenRotationFrom[lvl][pid]); csFrom.setHiddenValue(gameState, pid, from, lvl, typeFrom, previousHiddenValueFrom[lvl][pid]); } } } // We restore the to site for(int lvl = sizeStackTo -1 ; lvl >= 0; lvl--) csTo.remove(context.state(), to, lvl, typeTo); for(int lvl = 0 ; lvl < previousWhatTo.length; lvl++) { csTo.addItemGeneric(gameState, to, previousWhatTo[lvl], previousWhoTo[lvl], previousStateTo[lvl], previousRotationTo[lvl], previousValueTo[lvl], game, typeTo); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, lvl, typeTo, previousHiddenTo[lvl][pid]); csTo.setHiddenWhat(gameState, pid, to, lvl, typeTo, previousHiddenWhatTo[lvl][pid]); csTo.setHiddenWho(gameState, pid, to, lvl, typeTo, previousHiddenWhoTo[lvl][pid]); csTo.setHiddenCount(gameState, pid, to, lvl, typeTo, previousHiddenCountTo[lvl][pid]); csTo.setHiddenState(gameState, pid, to, lvl, typeTo, previousHiddenStateTo[lvl][pid]); csTo.setHiddenRotation(gameState, pid, to, lvl, typeTo, previousHiddenRotationTo[lvl][pid]); csTo.setHiddenValue(gameState, pid, to, lvl, typeTo, previousHiddenValueTo[lvl][pid]); } } } } else // Non stacking undo. { csFrom.remove(context.state(), from, typeFrom); csTo.remove(context.state(), to, typeTo); if(previousCountFrom > 0) csFrom.setSite(context.state(), from, previousWhoFrom[0], previousWhatFrom[0], previousCountFrom, previousStateFrom[0], previousRotationFrom[0], previousValueFrom[0], typeFrom); if(previousCountTo > 0) csTo.setSite(context.state(), to, previousWhoTo[0], previousWhatTo[0], previousCountTo, previousStateTo[0], previousRotationTo[0], previousValueTo[0], typeTo); if(context.game().hiddenInformation()) { if(previousHiddenFrom.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, 0, typeFrom, previousHiddenFrom[0][pid]); csFrom.setHiddenWhat(gameState, pid, from, 0, typeFrom, previousHiddenWhatFrom[0][pid]); csFrom.setHiddenWho(gameState, pid, from, 0, typeFrom, previousHiddenWhoFrom[0][pid]); csFrom.setHiddenCount(gameState, pid, from, 0, typeFrom, previousHiddenCountFrom[0][pid]); csFrom.setHiddenState(gameState, pid, from, 0, typeFrom, previousHiddenStateFrom[0][pid]); csFrom.setHiddenRotation(gameState, pid, from, 0, typeFrom, previousHiddenRotationFrom[0][pid]); csFrom.setHiddenValue(gameState, pid, from, 0, typeFrom, previousHiddenValueFrom[0][pid]); } if(previousHiddenTo.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, 0, typeTo, previousHiddenTo[0][pid]); csTo.setHiddenWhat(gameState, pid, to, 0, typeTo, previousHiddenWhatTo[0][pid]); csTo.setHiddenWho(gameState, pid, to, 0, typeTo, previousHiddenWhoTo[0][pid]); csTo.setHiddenCount(gameState, pid, to, 0, typeTo, previousHiddenCountTo[0][pid]); csTo.setHiddenState(gameState, pid, to, 0, typeTo, previousHiddenStateTo[0][pid]); csTo.setHiddenRotation(gameState, pid, to, 0, typeTo, previousHiddenRotationTo[0][pid]); csTo.setHiddenValue(gameState, pid, to, 0, typeTo, previousHiddenValueTo[0][pid]); } } } if (csTo.sizeStack(to, typeTo) == 0) csTo.addToEmpty(to, typeTo); if (csFrom.sizeStack(from, typeFrom) != 0) csFrom.removeFromEmpty(from, typeFrom); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Move:"); if (typeFrom != null || (context != null && typeFrom != context.board().defaultSite())) { sb.append("typeFrom=" + typeFrom); sb.append(",from=" + from); } else sb.append("from=" + from); if (typeTo != null || (context != null && typeTo != context.board().defaultSite())) sb.append(",typeTo=" + typeTo); sb.append(",to=" + to); sb.append(",levelTo=" + levelTo); if (state != Constants.UNDEFINED) sb.append(",state=" + state); if (rotation != Constants.UNDEFINED) sb.append(",rotation=" + rotation); if (value != Constants.UNDEFINED) sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + from; result = prime * result + to; result = prime * result + levelTo; result = prime * result + state; result = prime * result + rotation; result = prime * result + value; result = prime * result + 1237; result = prime * result + ((typeFrom == null) ? 0 : typeFrom.hashCode()); result = prime * result + ((typeTo == null) ? 0 : typeTo.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionMoveLevelTo)) return false; final ActionMoveLevelTo other = (ActionMoveLevelTo) obj; return (decision == other.decision && from == other.from && to == other.to && levelTo == other.levelTo && state == other.state && rotation == other.rotation && value == other.value && typeFrom == other.typeFrom && typeTo == other.typeTo); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Move"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && !typeFrom.equals(context.board().defaultSite())) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeTo != null && !typeTo.equals(context.board().defaultSite())) sb.append("-" + typeTo + " " + newTo); else sb.append("-" + newTo); sb.append("/" + levelTo); if (state != Constants.UNDEFINED) sb.append("=" + state); if (rotation != Constants.UNDEFINED) sb.append(" r" + rotation); if (value != Constants.UNDEFINED) sb.append(" v" + value); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Move "); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && typeTo != null && (!typeFrom.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); if (to < context.game().equipment().containers()[cid].topology().getGraphElements(realType).size()) newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); else // The site is not existing. newTo = "??"; } } if (typeFrom != null && typeTo != null && (!typeTo.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(" - " + typeTo + " " + newTo); else sb.append("-" + newTo); sb.append("/" + levelTo); if (state != Constants.UNDEFINED) sb.append(" state=" + state); if (rotation != Constants.UNDEFINED) sb.append(" rotation=" + rotation); if (state != Constants.UNDEFINED) sb.append(" state=" + state); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return typeFrom; } @Override public SiteType toType() { return typeTo; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int levelFrom() { return Constants.GROUND_LEVEL; } @Override public int levelTo() { return levelTo; } @Override public int state() { return state; } @Override public int rotation() { return rotation; } @Override public int value() { return value; } @Override public int count() { return 1; } @Override public boolean isStacking() { return false; } @Override public ActionType actionType() { return ActionType.Move; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final int contIdA = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdB = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csA = context.state().containerStates()[contIdA]; final ContainerState csB = context.state().containerStates()[contIdB]; final int whatA = csA.what(from, typeFrom); final int whatB = csB.what(to, typeTo); final int whoA = csA.who(from, typeFrom); final int whoB = csB.who(to, typeTo); final BitSet concepts = new BitSet(); // ---- Hop concepts if (ludemeConcept.get(Concept.HopDecision.id())) { concepts.set(Concept.HopDecision.id(), true); if (whatA != 0) { final Topology topology = context.topology(); final TopologyElement fromV = topology.getGraphElements(typeFrom).get(from); final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, typeFrom); AbsoluteDirection direction = null; int distance = Constants.UNDEFINED; for (final DirectionFacing facingDirection : directionsSupported) { final AbsoluteDirection absDirection = facingDirection.toAbsolute(); final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), absDirection); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int toRadial = radial.steps()[toIdx].id(); if (toRadial == to) { direction = absDirection; distance = toIdx; break; } } if (direction != null) break; } } if (direction != null) { final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), direction); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < distance; toIdx++) { final int between = radial.steps()[toIdx].id(); final int whatBetween = csA.what(between, typeFrom); final int whoBetween = csA.who(between, typeFrom); if (whatBetween != 0) { if (areEnemies(context, whoA, whoBetween)) { if (whatB == 0) concepts.set(Concept.HopDecisionEnemyToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionEnemyToEnemy.id(), true); else concepts.set(Concept.HopDecisionEnemyToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); concepts.set(Concept.HopCaptureMoreThanOne.id(), true); } } else { if (whatB == 0) concepts.set(Concept.HopDecisionFriendToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionFriendToEnemy.id(), true); else concepts.set(Concept.HopDecisionFriendToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } } } } } } } } if (ludemeConcept.get(Concept.HopEffect.id())) concepts.set(Concept.HopEffect.id(), true); // ---- Step concepts if (ludemeConcept.get(Concept.StepEffect.id())) concepts.set(Concept.StepEffect.id(), true); if (ludemeConcept.get(Concept.StepDecision.id())) { concepts.set(Concept.StepDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.StepDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.StepDecisionToEnemy.id(), true); else concepts.set(Concept.StepDecisionToFriend.id(), true); } } } // ---- Leap concepts if (ludemeConcept.get(Concept.LeapEffect.id())) concepts.set(Concept.LeapEffect.id(), true); if (ludemeConcept.get(Concept.LeapDecision.id())) { concepts.set(Concept.LeapDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.LeapDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.LeapDecisionToEnemy.id(), true); else concepts.set(Concept.LeapDecisionToFriend.id(), true); } } } // ---- Slide concepts if (ludemeConcept.get(Concept.SlideEffect.id())) concepts.set(Concept.SlideEffect.id(), true); if (ludemeConcept.get(Concept.SlideDecision.id())) { concepts.set(Concept.SlideDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.SlideDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.SlideDecisionToEnemy.id(), true); else concepts.set(Concept.SlideDecisionToFriend.id(), true); } } } // ---- FromTo concepts if (ludemeConcept.get(Concept.FromToDecision.id())) { if (contIdA == contIdB) concepts.set(Concept.FromToDecisionWithinBoard.id(), true); else concepts.set(Concept.FromToDecisionBetweenContainers.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.FromToDecisionEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.FromToDecisionEnemy.id(), true); else concepts.set(Concept.FromToDecisionFriend.id(), true); } } } if (ludemeConcept.get(Concept.FromToEffect.id())) concepts.set(Concept.FromToEffect.id(), true); // ---- Swap Pieces concepts if (ludemeConcept.get(Concept.SwapPiecesEffect.id())) concepts.set(Concept.SwapPiecesEffect.id(), true); if (ludemeConcept.get(Concept.SwapPiecesDecision.id())) concepts.set(Concept.SwapPiecesDecision.id(), true); // ---- Sow concepts if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.Sow.id())) concepts.set(Concept.Sow.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.SowBacktracking.id())) concepts.set(Concept.SowBacktracking.id(), true); return concepts; } /** * @param context The context. * @param who1 The id of a player. * @param who2 The id of a player. * @return True if these players are enemies. */ public static boolean areEnemies(final Context context, final int who1, final int who2) { if (who1 == 0 || who2 == 0 || who1 == who2) return false; if (context.game().requiresTeams()) { final TIntArrayList teamMembers = new TIntArrayList(); final int tid = context.state().getTeam(who1); for (int i = 1; i < context.game().players().size(); i++) if (context.state().getTeam(i) == tid) teamMembers.add(i); return !teamMembers.contains(who2); } return who1 != who2; } }
39,474
32.396785
181
java
Ludii
Ludii-master/Core/src/other/action/move/move/ActionMoveStacking.java
package other.action.move.move; import java.util.BitSet; import java.util.List; import game.Game; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.RelationType; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; import other.topology.Topology; import other.topology.TopologyElement; /** * Moves a full stack from a site to another. * * @author Eric.Piette */ public final class ActionMoveStacking extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type of the from site. */ private final SiteType typeFrom; /** From site index. */ private final int from; /** From level index (e.g. stacking game). */ private int levelFrom; /** The graph element type of the to site. */ private final SiteType typeTo; /** To site index. */ private final int to; /** To level index (e.g. stacking game). */ private final int levelTo; /** Site state value of the to site. */ private final int state; /** Rotation value of the to site. */ private final int rotation; /** piece value of the to site. */ private final int value; //----------------------Undo Data--------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; //-- from data /** Previous What value of the from site. */ private int[] previousWhatFrom; /** Previous Who value of the from site. */ private int[] previousWhoFrom; /** Previous Site state value of the from site. */ private int[] previousStateFrom; /** Previous Rotation value of the from site. */ private int[] previousRotationFrom; /** Previous Piece value of the from site. */ private int[] previousValueFrom; /** Previous Piece count of the from site. */ private int previousCountFrom; /** The previous hidden info values of the from site before to be removed. */ private boolean[][] previousHiddenFrom; /** The previous hidden what info values of the from site before to be removed. */ private boolean[][] previousHiddenWhatFrom; /** The previous hidden who info values of the from site before to be removed. */ private boolean[][] previousHiddenWhoFrom; /** The previous hidden count info values of the from site before to be removed. */ private boolean[][] previousHiddenCountFrom; /** The previous hidden rotation info values of the from site before to be removed. */ private boolean[][] previousHiddenRotationFrom; /** The previous hidden State info values of the from site before to be removed. */ private boolean[][] previousHiddenStateFrom; /** The previous hidden Value info values of the from site before to be removed. */ private boolean[][] previousHiddenValueFrom; //--- to data /** Previous What of the to site. */ private int[] previousWhatTo; /** Previous Who of the to site. */ private int[] previousWhoTo; /** Previous Site state value of the to site. */ private int[] previousStateTo; /** Previous Rotation value of the to site. */ private int[] previousRotationTo; /** Previous Piece value of the to site. */ private int[] previousValueTo; /** Previous Piece count of the to site. */ private int previousCountTo; /** The previous hidden info values of the to site before to be removed. */ private boolean[][] previousHiddenTo; /** The previous hidden what info values of the to site before to be removed. */ private boolean[][] previousHiddenWhatTo; /** The previous hidden who info values of the to site before to be removed. */ private boolean[][] previousHiddenWhoTo; /** The previous hidden count info values of the to site before to be removed. */ private boolean[][] previousHiddenCountTo; /** The previous hidden rotation info values of the to site before to be removed. */ private boolean[][] previousHiddenRotationTo; /** The previous hidden State info values of the to site before to be removed. */ private boolean[][] previousHiddenStateTo; /** The previous hidden Value info values of the to site before to be removed. */ private boolean[][] previousHiddenValueTo; //------------------------------------------------------------------------- /** * @param typeFrom The graph element type of the from site. * @param from From site index. * @param levelFrom From level index. * @param typeTo The graph element type of the to site. * @param to To site index. * @param levelTo To level index. * @param state The state site of the to site. * @param rotation The rotation value of the to site. * @param value The piece value of the to site. */ public ActionMoveStacking ( final SiteType typeFrom, final int from, final int levelFrom, final SiteType typeTo, final int to, final int levelTo, final int state, final int rotation, final int value ) { this.typeFrom = typeFrom; this.from = from; this.levelFrom = levelFrom; this.typeTo = typeTo; this.to = to; this.levelTo = levelTo; this.state = state; this.rotation = rotation; this.value = value; } //------------------------------------------------------------------------- @Override public Action apply ( final Context context, final boolean store ) { final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final boolean requiresStack = context.currentInstanceContext().game().isStacking(); final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; // Keep in memory the data of the site from and to (for undo method) if(!alreadyApplied) { final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); previousWhatFrom = new int[sizeStackFrom]; previousWhoFrom = new int[sizeStackFrom]; previousStateFrom = new int[sizeStackFrom]; previousRotationFrom = new int[sizeStackFrom]; previousValueFrom = new int[sizeStackFrom]; previousHiddenFrom = new boolean[sizeStackFrom][]; previousHiddenWhatFrom = new boolean[sizeStackFrom][]; previousHiddenWhoFrom = new boolean[sizeStackFrom][]; previousHiddenCountFrom = new boolean[sizeStackFrom][]; previousHiddenRotationFrom = new boolean[sizeStackFrom][]; previousHiddenStateFrom = new boolean[sizeStackFrom][]; previousHiddenValueFrom = new boolean[sizeStackFrom][]; if(!requiresStack) { previousCountFrom = csFrom.count(from, typeFrom); previousCountTo = csTo.count(to, typeTo); } for(int lvl = 0 ; lvl < sizeStackFrom; lvl++) { previousWhatFrom[lvl] = csFrom.what(from, lvl, typeFrom); previousWhoFrom[lvl] = csFrom.who(from, lvl, typeFrom); previousStateFrom[lvl] = csFrom.state(from, lvl, typeFrom); previousRotationFrom[lvl] = csFrom.rotation(from, lvl, typeFrom); previousValueFrom[lvl] = csFrom.value(from, lvl, typeFrom); if(context.game().hiddenInformation()) { previousHiddenFrom[lvl] = new boolean[context.players().size()]; previousHiddenWhatFrom[lvl] = new boolean[context.players().size()]; previousHiddenWhoFrom[lvl] = new boolean[context.players().size()]; previousHiddenCountFrom[lvl] = new boolean[context.players().size()]; previousHiddenStateFrom[lvl] = new boolean[context.players().size()]; previousHiddenRotationFrom[lvl] = new boolean[context.players().size()]; previousHiddenValueFrom[lvl] = new boolean[context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenFrom[lvl][pid] = csFrom.isHidden(pid, from, lvl, typeFrom); previousHiddenWhatFrom[lvl][pid] = csFrom.isHiddenWhat(pid, from, lvl, typeFrom); previousHiddenWhoFrom[lvl][pid] = csFrom.isHiddenWho(pid, from, lvl, typeFrom); previousHiddenCountFrom[lvl][pid] = csFrom.isHiddenCount(pid, from, lvl, typeFrom); previousHiddenStateFrom[lvl][pid] = csFrom.isHiddenState(pid, from, lvl, typeFrom); previousHiddenRotationFrom[lvl][pid] = csFrom.isHiddenRotation(pid, from, lvl, typeFrom); previousHiddenValueFrom[lvl][pid] = csFrom.isHiddenValue(pid, from, lvl, typeFrom); } } } final int sizeStackTo = csTo.sizeStack(to, typeTo); previousWhatTo = new int[sizeStackTo]; previousWhoTo = new int[sizeStackTo]; previousStateTo = new int[sizeStackTo]; previousRotationTo = new int[sizeStackTo]; previousValueTo = new int[sizeStackTo]; previousHiddenTo = new boolean[sizeStackTo][]; previousHiddenWhatTo = new boolean[sizeStackTo][]; previousHiddenWhoTo = new boolean[sizeStackTo][]; previousHiddenCountTo = new boolean[sizeStackTo][]; previousHiddenRotationTo = new boolean[sizeStackTo][]; previousHiddenStateTo = new boolean[sizeStackTo][]; previousHiddenValueTo = new boolean[sizeStackTo][]; for(int lvl = 0 ; lvl < sizeStackTo; lvl++) { previousWhatTo[lvl] = csTo.what(to, lvl, typeTo); previousWhoTo[lvl] = csTo.who(to, lvl, typeTo); previousStateTo[lvl] = csTo.state(to, lvl, typeTo); previousRotationTo[lvl] = csTo.rotation(to, lvl, typeTo); previousValueTo[lvl] = csTo.value(to, lvl, typeTo); if(context.game().hiddenInformation()) { previousHiddenTo[lvl] = new boolean[context.players().size()]; previousHiddenWhatTo[lvl] = new boolean[context.players().size()]; previousHiddenWhoTo[lvl] = new boolean[context.players().size()]; previousHiddenCountTo[lvl] = new boolean[context.players().size()]; previousHiddenStateTo[lvl] = new boolean[context.players().size()]; previousHiddenRotationTo[lvl] = new boolean[context.players().size()]; previousHiddenValueTo[lvl] = new boolean[context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenTo[lvl][pid] = csTo.isHidden(pid, to, lvl, typeTo); previousHiddenWhatTo[lvl][pid] = csTo.isHiddenWhat(pid, to, lvl, typeTo); previousHiddenWhoTo[lvl][pid] = csTo.isHiddenWho(pid, to, lvl, typeTo); previousHiddenCountTo[lvl][pid] = csTo.isHiddenCount(pid, to, lvl, typeTo); previousHiddenStateTo[lvl][pid] = csTo.isHiddenState(pid, to, lvl, typeTo); previousHiddenRotationTo[lvl][pid] = csTo.isHiddenRotation(pid, to, lvl, typeTo); previousHiddenValueTo[lvl][pid] = csTo.isHiddenValue(pid, to, lvl, typeTo); } } } alreadyApplied = true; } if(from == to) return this; final ContainerState containerFrom = context.state().containerStates()[contIdFrom]; final ContainerState containerTo = context.state().containerStates()[contIdTo]; final int sizeStackFrom = containerFrom.sizeStack(from, typeFrom); for (int slevel = 0; slevel < containerFrom.sizeStack(from, typeFrom); slevel++) { if (levelTo == Constants.UNDEFINED) containerTo.addItemGeneric(context.state(), to, containerFrom.what(from, slevel, typeFrom), containerFrom.who(from, slevel, typeFrom), containerFrom.state(from, slevel, typeFrom), containerFrom.rotation(from, slevel, typeFrom), containerFrom.value(from, slevel, typeFrom), context.game(), typeTo); else { containerTo.insert(context.state(), typeTo, to, levelTo, containerFrom.what(from, slevel, typeFrom), containerFrom.who(from, slevel, typeFrom), state, rotation, value, context.game()); } } // we update owned for loc From. for (int level = 0; level < containerFrom.sizeStack(from, typeFrom); level++) { final int whatFrom = containerFrom.what(from, level, typeFrom); if (whatFrom != 0) { final Component pieceFrom = context.components()[whatFrom]; final int ownerFrom = pieceFrom.owner(); if (ownerFrom != 0) context.state().owned().remove(ownerFrom, whatFrom, from, typeFrom); } } containerFrom.removeStackGeneric(context.state(), from, typeFrom); containerFrom.addToEmpty(from, typeFrom); containerTo.removeFromEmpty(to, typeTo); // we update owned for loc To. for (int level = containerTo.sizeStack(to, typeTo) - sizeStackFrom; level < containerTo.sizeStack(to, typeTo); level++) { if (level < 0) continue; final int whatTo = containerTo.what(to, level, typeTo); if (whatTo != 0) { final Component pieceTo = context.components()[whatTo]; final int ownerTo = pieceTo.owner(); if (ownerTo != 0) context.state().owned().add(ownerTo, whatTo, to, level, typeTo); } } return this; } /** * To update the onTrackIndices after a move. * * @param what The index of the component moved. * @param onTrackIndices The structure onTrackIndices * @param tracks The list of the tracks. */ public void updateOnTrackIndices(final int what, final OnTrackIndices onTrackIndices, final List<Track> tracks) { // We update the structure about track indices if the game uses track. if (what != 0 && onTrackIndices != null) { for (final Track track : tracks) { final int trackIdx = track.trackIdx(); final TIntArrayList indicesLocA = onTrackIndices.locToIndex(trackIdx, from); for (int k = 0; k < indicesLocA.size(); k++) { final int indexA = indicesLocA.getQuick(k); final int countAtIndex = onTrackIndices.whats(trackIdx, what, indicesLocA.getQuick(k)); if (countAtIndex > 0) { onTrackIndices.remove(trackIdx, what, 1, indexA); final TIntArrayList newWhatIndice = onTrackIndices.locToIndexFrom(trackIdx, to, indexA); if (newWhatIndice.size() > 0) { onTrackIndices.add(trackIdx, what, 1, newWhatIndice.getQuick(0)); } else { final TIntArrayList newWhatIndiceIfNotAfter = onTrackIndices.locToIndex(trackIdx, to); if (newWhatIndiceIfNotAfter.size() > 0) onTrackIndices.add(trackIdx, what, 1, newWhatIndiceIfNotAfter.getQuick(0)); } break; } } // If the piece was not in the track but enter on it, we update the structure // corresponding to that track. if (indicesLocA.size() == 0) { final TIntArrayList indicesLocB = onTrackIndices.locToIndex(trackIdx, to); if (indicesLocB.size() != 0) onTrackIndices.add(trackIdx, what, 1, indicesLocB.get(0)); } } } } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; final Game game = context.game(); final State gameState = context.state(); final boolean requiresStack = context.currentInstanceContext().game().isStacking(); final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); final int sizeStackTo = csTo.sizeStack(to, typeTo); if(requiresStack) // Stacking undo. { // We restore the from site for(int lvl = sizeStackFrom -1 ; lvl >= 0; lvl--) csFrom.remove(context.state(), from, lvl, typeFrom); for(int lvl = 0 ; lvl < previousWhatFrom.length; lvl++) { csFrom.addItemGeneric(gameState, from, previousWhatFrom[lvl], previousWhoFrom[lvl], previousStateFrom[lvl], previousRotationFrom[lvl], previousValueFrom[lvl], game, typeFrom); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, lvl, typeFrom, previousHiddenFrom[lvl][pid]); csFrom.setHiddenWhat(gameState, pid, from, lvl, typeFrom, previousHiddenWhatFrom[lvl][pid]); csFrom.setHiddenWho(gameState, pid, from, lvl, typeFrom, previousHiddenWhoFrom[lvl][pid]); csFrom.setHiddenCount(gameState, pid, from, lvl, typeFrom, previousHiddenCountFrom[lvl][pid]); csFrom.setHiddenState(gameState, pid, from, lvl, typeFrom, previousHiddenStateFrom[lvl][pid]); csFrom.setHiddenRotation(gameState, pid, from, lvl, typeFrom, previousHiddenRotationFrom[lvl][pid]); csFrom.setHiddenValue(gameState, pid, from, lvl, typeFrom, previousHiddenValueFrom[lvl][pid]); } } } // We restore the to site for(int lvl = sizeStackTo -1 ; lvl >= 0; lvl--) csTo.remove(context.state(), to, lvl, typeTo); for(int lvl = 0 ; lvl < previousWhatTo.length; lvl++) { csTo.addItemGeneric(gameState, to, previousWhatTo[lvl], previousWhoTo[lvl], previousStateTo[lvl], previousRotationTo[lvl], previousValueTo[lvl], game, typeTo); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, lvl, typeTo, previousHiddenTo[lvl][pid]); csTo.setHiddenWhat(gameState, pid, to, lvl, typeTo, previousHiddenWhatTo[lvl][pid]); csTo.setHiddenWho(gameState, pid, to, lvl, typeTo, previousHiddenWhoTo[lvl][pid]); csTo.setHiddenCount(gameState, pid, to, lvl, typeTo, previousHiddenCountTo[lvl][pid]); csTo.setHiddenState(gameState, pid, to, lvl, typeTo, previousHiddenStateTo[lvl][pid]); csTo.setHiddenRotation(gameState, pid, to, lvl, typeTo, previousHiddenRotationTo[lvl][pid]); csTo.setHiddenValue(gameState, pid, to, lvl, typeTo, previousHiddenValueTo[lvl][pid]); } } } } else // Non stacking undo. { csFrom.remove(context.state(), from, typeFrom); csTo.remove(context.state(), to, typeTo); if(previousCountFrom > 0) csFrom.setSite(context.state(), from, previousWhoFrom[0], previousWhatFrom[0], previousCountFrom, previousStateFrom[0], previousRotationFrom[0], previousValueFrom[0], typeFrom); if(previousCountTo > 0) csTo.setSite(context.state(), to, previousWhoTo[0], previousWhatTo[0], previousCountTo, previousStateTo[0], previousRotationTo[0], previousValueTo[0], typeTo); if(context.game().hiddenInformation()) { if(previousHiddenFrom.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, 0, typeFrom, previousHiddenFrom[0][pid]); csFrom.setHiddenWhat(gameState, pid, from, 0, typeFrom, previousHiddenWhatFrom[0][pid]); csFrom.setHiddenWho(gameState, pid, from, 0, typeFrom, previousHiddenWhoFrom[0][pid]); csFrom.setHiddenCount(gameState, pid, from, 0, typeFrom, previousHiddenCountFrom[0][pid]); csFrom.setHiddenState(gameState, pid, from, 0, typeFrom, previousHiddenStateFrom[0][pid]); csFrom.setHiddenRotation(gameState, pid, from, 0, typeFrom, previousHiddenRotationFrom[0][pid]); csFrom.setHiddenValue(gameState, pid, from, 0, typeFrom, previousHiddenValueFrom[0][pid]); } if(previousHiddenTo.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, 0, typeTo, previousHiddenTo[0][pid]); csTo.setHiddenWhat(gameState, pid, to, 0, typeTo, previousHiddenWhatTo[0][pid]); csTo.setHiddenWho(gameState, pid, to, 0, typeTo, previousHiddenWhoTo[0][pid]); csTo.setHiddenCount(gameState, pid, to, 0, typeTo, previousHiddenCountTo[0][pid]); csTo.setHiddenState(gameState, pid, to, 0, typeTo, previousHiddenStateTo[0][pid]); csTo.setHiddenRotation(gameState, pid, to, 0, typeTo, previousHiddenRotationTo[0][pid]); csTo.setHiddenValue(gameState, pid, to, 0, typeTo, previousHiddenValueTo[0][pid]); } } } if (csTo.sizeStack(to, typeTo) == 0) csTo.addToEmpty(to, typeTo); if (csFrom.sizeStack(from, typeFrom) != 0) csFrom.removeFromEmpty(from, typeFrom); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Move:"); if (typeFrom != null || (context != null && typeFrom != context.board().defaultSite())) { sb.append("typeFrom=" + typeFrom); sb.append(",from=" + from); } else sb.append("from=" + from); if (levelFrom != Constants.UNDEFINED) sb.append(",levelFrom=" + levelFrom); if (typeTo != null || (context != null && typeTo != context.board().defaultSite())) sb.append(",typeTo=" + typeTo); sb.append(",to=" + to); if (levelTo != Constants.UNDEFINED) sb.append(",levelTo=" + levelTo); if (state != Constants.UNDEFINED) sb.append(",state=" + state); if (rotation != Constants.UNDEFINED) sb.append(",rotation=" + rotation); if (value != Constants.UNDEFINED) sb.append(",value=" + value); sb.append(",stack=" + true); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + from; result = prime * result + levelFrom; result = prime * result + to; result = prime * result + levelTo; result = prime * result + state; result = prime * result + rotation; result = prime * result + value; result = prime * result + 1231; result = prime * result + ((typeFrom == null) ? 0 : typeFrom.hashCode()); result = prime * result + ((typeTo == null) ? 0 : typeTo.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionMoveStacking)) return false; final ActionMoveStacking other = (ActionMoveStacking) obj; return (decision == other.decision && from == other.from && levelFrom == other.levelFrom && to == other.to && levelTo == other.levelTo && state == other.state && rotation == other.rotation && value == other.value && typeFrom == other.typeFrom && typeTo == other.typeTo); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Move"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && !typeFrom.equals(context.board().defaultSite())) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (levelFrom != Constants.UNDEFINED && context.game().isStacking()) sb.append("/" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeTo != null && !typeTo.equals(context.board().defaultSite())) sb.append("-" + typeTo + " " + newTo); else sb.append("-" + newTo); if (levelTo != Constants.UNDEFINED) sb.append("/" + levelTo); if (state != Constants.UNDEFINED) sb.append("=" + state); if (rotation != Constants.UNDEFINED) sb.append(" r" + rotation); if (value != Constants.UNDEFINED) sb.append(" v" + value); sb.append(" ^"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Move "); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && typeTo != null && (!typeFrom.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); if (levelFrom != Constants.UNDEFINED) sb.append("/" + levelFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); if (to < context.game().equipment().containers()[cid].topology().getGraphElements(realType).size()) newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); else // The site is not existing. newTo = "??"; } } if (typeFrom != null && typeTo != null && (!typeTo.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(" - " + typeTo + " " + newTo); else sb.append("-" + newTo); if (levelTo != Constants.UNDEFINED) sb.append("/" + levelTo); if (state != Constants.UNDEFINED) sb.append(" state=" + state); if (rotation != Constants.UNDEFINED) sb.append(" rotation=" + rotation); if (state != Constants.UNDEFINED) sb.append(" state=" + state); sb.append(" stack=" + true); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return typeFrom; } @Override public SiteType toType() { return typeTo; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int levelFrom() { return (levelFrom == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : levelFrom; } @Override public int levelTo() { return (levelTo == Constants.UNDEFINED) ? Constants.GROUND_LEVEL : levelTo; } @Override public int state() { return state; } @Override public int rotation() { return rotation; } @Override public int value() { return value; } @Override public int count() { return 1; } @Override public boolean isStacking() { return true; } @Override public void setLevelFrom(final int levelA) { levelFrom = levelA; } @Override public ActionType actionType() { return ActionType.Move; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final int contIdA = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdB = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csA = context.state().containerStates()[contIdA]; final ContainerState csB = context.state().containerStates()[contIdB]; final int whatA = csA.what(from, typeFrom); final int whatB = csB.what(to, typeTo); final int whoA = csA.who(from, typeFrom); final int whoB = csB.who(to, typeTo); final BitSet concepts = new BitSet(); // ---- Hop concepts if (ludemeConcept.get(Concept.HopDecision.id())) { concepts.set(Concept.HopDecision.id(), true); if (whatA != 0) { final Topology topology = context.topology(); final TopologyElement fromV = topology.getGraphElements(typeFrom).get(from); final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, typeFrom); AbsoluteDirection direction = null; int distance = Constants.UNDEFINED; for (final DirectionFacing facingDirection : directionsSupported) { final AbsoluteDirection absDirection = facingDirection.toAbsolute(); final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), absDirection); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int toRadial = radial.steps()[toIdx].id(); if (toRadial == to) { direction = absDirection; distance = toIdx; break; } } if (direction != null) break; } } if (direction != null) { final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), direction); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < distance; toIdx++) { final int between = radial.steps()[toIdx].id(); final int whatBetween = csA.what(between, typeFrom); final int whoBetween = csA.who(between, typeFrom); if (whatBetween != 0) { if (areEnemies(context, whoA, whoBetween)) { if (whatB == 0) concepts.set(Concept.HopDecisionEnemyToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionEnemyToEnemy.id(), true); else concepts.set(Concept.HopDecisionEnemyToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); concepts.set(Concept.HopCaptureMoreThanOne.id(), true); } } else { if (whatB == 0) concepts.set(Concept.HopDecisionFriendToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionFriendToEnemy.id(), true); else concepts.set(Concept.HopDecisionFriendToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } } } } } } } } if (ludemeConcept.get(Concept.HopEffect.id())) concepts.set(Concept.HopEffect.id(), true); // ---- Step concepts if (ludemeConcept.get(Concept.StepEffect.id())) concepts.set(Concept.StepEffect.id(), true); if (ludemeConcept.get(Concept.StepDecision.id())) { concepts.set(Concept.StepDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.StepDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.StepDecisionToEnemy.id(), true); else concepts.set(Concept.StepDecisionToFriend.id(), true); } } } // ---- Leap concepts if (ludemeConcept.get(Concept.LeapEffect.id())) concepts.set(Concept.LeapEffect.id(), true); if (ludemeConcept.get(Concept.LeapDecision.id())) { concepts.set(Concept.LeapDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.LeapDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.LeapDecisionToEnemy.id(), true); else concepts.set(Concept.LeapDecisionToFriend.id(), true); } } } // ---- Slide concepts if (ludemeConcept.get(Concept.SlideEffect.id())) concepts.set(Concept.SlideEffect.id(), true); if (ludemeConcept.get(Concept.SlideDecision.id())) { concepts.set(Concept.SlideDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.SlideDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.SlideDecisionToEnemy.id(), true); else concepts.set(Concept.SlideDecisionToFriend.id(), true); } } } // ---- FromTo concepts if (ludemeConcept.get(Concept.FromToDecision.id())) { if (contIdA == contIdB) concepts.set(Concept.FromToDecisionWithinBoard.id(), true); else concepts.set(Concept.FromToDecisionBetweenContainers.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.FromToDecisionEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.FromToDecisionEnemy.id(), true); else concepts.set(Concept.FromToDecisionFriend.id(), true); } } } if (ludemeConcept.get(Concept.FromToEffect.id())) concepts.set(Concept.FromToEffect.id(), true); // ---- Swap Pieces concepts if (ludemeConcept.get(Concept.SwapPiecesEffect.id())) concepts.set(Concept.SwapPiecesEffect.id(), true); if (ludemeConcept.get(Concept.SwapPiecesDecision.id())) concepts.set(Concept.SwapPiecesDecision.id(), true); // ---- Sow concepts if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.Sow.id())) concepts.set(Concept.Sow.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.SowBacktracking.id())) concepts.set(Concept.SowBacktracking.id(), true); return concepts; } /** * @param context The context. * @param who1 The id of a player. * @param who2 The id of a player. * @return True if these players are enemies. */ public static boolean areEnemies(final Context context, final int who1, final int who2) { if (who1 == 0 || who2 == 0 || who1 == who2) return false; if (context.game().requiresTeams()) { final TIntArrayList teamMembers = new TIntArrayList(); final int tid = context.state().getTeam(who1); for (int i = 1; i < context.game().players().size(); i++) if (context.state().getTeam(i) == tid) teamMembers.add(i); return !teamMembers.contains(who2); } return who1 != who2; } }
34,833
30.753874
181
java
Ludii
Ludii-master/Core/src/other/action/move/move/ActionMoveTopPiece.java
package other.action.move.move; import java.util.BitSet; import java.util.List; import game.Game; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.RelationType; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; import other.topology.Topology; import other.topology.TopologyElement; /** * Moves a piece from a site to another (only the top piece). * * @author Eric.Piette */ public class ActionMoveTopPiece extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type of the from site. */ private final SiteType typeFrom; /** From site index. */ private final int from; /** The graph element type of the to site. */ private final SiteType typeTo; /** To site index. */ private final int to; /** Site state value of the to site. */ private final int state; /** Rotation value of the to site. */ private final int rotation; /** piece value of the to site. */ private final int value; //----------------------Undo Data--------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; //-- from data /** Previous What value of the from site. */ private int[] previousWhatFrom; /** Previous Who value of the from site. */ private int[] previousWhoFrom; /** Previous Site state value of the from site. */ private int[] previousStateFrom; /** Previous Rotation value of the from site. */ private int[] previousRotationFrom; /** Previous Piece value of the from site. */ private int[] previousValueFrom; /** Previous Piece count of the from site. */ private int previousCountFrom; /** The previous hidden info values of the from site before to be removed. */ private boolean[][] previousHiddenFrom; /** The previous hidden what info values of the from site before to be removed. */ private boolean[][] previousHiddenWhatFrom; /** The previous hidden who info values of the from site before to be removed. */ private boolean[][] previousHiddenWhoFrom; /** The previous hidden count info values of the from site before to be removed. */ private boolean[][] previousHiddenCountFrom; /** The previous hidden rotation info values of the from site before to be removed. */ private boolean[][] previousHiddenRotationFrom; /** The previous hidden State info values of the from site before to be removed. */ private boolean[][] previousHiddenStateFrom; /** The previous hidden Value info values of the from site before to be removed. */ private boolean[][] previousHiddenValueFrom; //--- to data /** Previous What of the to site. */ private int[] previousWhatTo; /** Previous Who of the to site. */ private int[] previousWhoTo; /** Previous Site state value of the to site. */ private int[] previousStateTo; /** Previous Rotation value of the to site. */ private int[] previousRotationTo; /** Previous Piece value of the to site. */ private int[] previousValueTo; /** Previous Piece count of the to site. */ private int previousCountTo; /** The previous hidden info values of the to site before to be removed. */ private boolean[][] previousHiddenTo; /** The previous hidden what info values of the to site before to be removed. */ private boolean[][] previousHiddenWhatTo; /** The previous hidden who info values of the to site before to be removed. */ private boolean[][] previousHiddenWhoTo; /** The previous hidden count info values of the to site before to be removed. */ private boolean[][] previousHiddenCountTo; /** The previous hidden rotation info values of the to site before to be removed. */ private boolean[][] previousHiddenRotationTo; /** The previous hidden State info values of the to site before to be removed. */ private boolean[][] previousHiddenStateTo; /** The previous hidden Value info values of the to site before to be removed. */ private boolean[][] previousHiddenValueTo; //------------------------------------------------------------------------- private boolean actionLargePiece = false; //------------------------------------------------------------------------- /** * @param typeFrom The graph element type of the from site. * @param from From site index. * @param typeTo The graph element type of the to site. * @param to To site index. * @param state The state site of the to site. * @param rotation The rotation value of the to site. * @param value The piece value of the to site. */ public ActionMoveTopPiece ( final SiteType typeFrom, final int from, final SiteType typeTo, final int to, final int state, final int rotation, final int value ) { this.typeFrom = typeFrom; this.from = from; this.typeTo = typeTo; this.to = to; this.state = state; this.rotation = rotation; this.value = value; } //------------------------------------------------------------------------- @Override public Action apply ( final Context context, final boolean store ) { final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final boolean requiresStack = context.currentInstanceContext().game().isStacking(); int currentStateFrom = Constants.UNDEFINED; int currentRotationFrom = Constants.UNDEFINED; int currentValueFrom = Constants.UNDEFINED; Component piece = null; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; final int what = csFrom.what(from, typeFrom); // We check if this a large piece to call the related class. if(what != 0) { piece = context.components()[what]; if(piece.isLargePiece()) { actionLargePiece = true; applyLargePiece(context, store); return this; } } // take the local state of the site from currentStateFrom = (csFrom.what(from, typeFrom) == 0) ? Constants.UNDEFINED : csFrom.state(from, typeFrom); currentRotationFrom = csFrom.rotation(from, typeFrom); currentValueFrom = csFrom.value(from, typeFrom); // Keep in memory the data of the site from and to (for undo method) if(!alreadyApplied) { if(!requiresStack) { previousCountFrom = csFrom.count(from, typeFrom); previousWhatFrom = new int[1]; previousWhoFrom = new int[1]; previousStateFrom = new int[1]; previousRotationFrom = new int[1]; previousValueFrom = new int[1]; previousWhatFrom[0] = csFrom.what(from, 0, typeFrom); previousWhoFrom[0] = csFrom.who(from, 0, typeFrom); previousStateFrom[0] = csFrom.state(from, 0, typeFrom); previousRotationFrom[0] = csFrom.rotation(from, 0, typeFrom); previousValueFrom[0] = csFrom.value(from, 0, typeFrom); previousCountTo = csTo.count(to, typeTo); previousWhatTo = new int[1]; previousWhoTo = new int[1]; previousStateTo = new int[1]; previousRotationTo = new int[1]; previousValueTo = new int[1]; previousWhatTo[0] = csTo.what(to, 0, typeTo); previousWhoTo[0] = csTo.who(to, 0, typeTo); previousStateTo[0] = csTo.state(to, 0, typeTo); previousRotationTo[0] = csTo.rotation(to, 0, typeTo); previousValueTo[0] = csTo.value(to, 0, typeTo); if(context.game().hiddenInformation()) { previousHiddenFrom = new boolean[1][context.players().size()]; previousHiddenWhatFrom = new boolean[1][context.players().size()]; previousHiddenWhoFrom = new boolean[1][context.players().size()]; previousHiddenCountFrom = new boolean[1][context.players().size()]; previousHiddenRotationFrom = new boolean[1][context.players().size()]; previousHiddenStateFrom = new boolean[1][context.players().size()]; previousHiddenValueFrom = new boolean[1][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenFrom[0][pid] = csFrom.isHidden(pid, from, 0, typeFrom); previousHiddenWhatFrom[0][pid] = csFrom.isHiddenWhat(pid, from, 0, typeFrom); previousHiddenWhoFrom[0][pid] = csFrom.isHiddenWho(pid, from, 0, typeFrom); previousHiddenCountFrom[0][pid] = csFrom.isHiddenCount(pid, from, 0, typeFrom); previousHiddenStateFrom[0][pid] = csFrom.isHiddenState(pid, from, 0, typeFrom); previousHiddenRotationFrom[0][pid] = csFrom.isHiddenRotation(pid, from, 0, typeFrom); previousHiddenValueFrom[0][pid] = csFrom.isHiddenValue(pid, from, 0, typeFrom); } previousHiddenTo = new boolean[1][context.players().size()]; previousHiddenWhatTo = new boolean[1][context.players().size()]; previousHiddenWhoTo = new boolean[1][context.players().size()]; previousHiddenCountTo = new boolean[1][context.players().size()]; previousHiddenRotationTo = new boolean[1][context.players().size()]; previousHiddenStateTo = new boolean[1][context.players().size()]; previousHiddenValueTo = new boolean[1][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenTo[0][pid] = csTo.isHidden(pid, to, 0, typeTo); previousHiddenWhatTo[0][pid] = csTo.isHiddenWhat(pid, to, 0, typeTo); previousHiddenWhoTo[0][pid] = csTo.isHiddenWho(pid, to, 0, typeTo); previousHiddenCountTo[0][pid] = csTo.isHiddenCount(pid, to, 0, typeTo); previousHiddenStateTo[0][pid] = csTo.isHiddenState(pid, to, 0, typeTo); previousHiddenRotationTo[0][pid] = csTo.isHiddenRotation(pid, to, 0, typeTo); previousHiddenValueTo[0][pid] = csTo.isHiddenValue(pid, to, 0, typeTo); } } } else // Stacking game. { final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); previousWhatFrom = new int[sizeStackFrom]; previousWhoFrom = new int[sizeStackFrom]; previousStateFrom = new int[sizeStackFrom]; previousRotationFrom = new int[sizeStackFrom]; previousValueFrom = new int[sizeStackFrom]; for(int lvl = 0 ; lvl < sizeStackFrom; lvl++) { previousWhatFrom[lvl] = csFrom.what(from, lvl, typeFrom); previousWhoFrom[lvl] = csFrom.who(from, lvl, typeFrom); previousStateFrom[lvl] = csFrom.state(from, lvl, typeFrom); previousRotationFrom[lvl] = csFrom.rotation(from, lvl, typeFrom); previousValueFrom[lvl] = csFrom.value(from, lvl, typeFrom); if(context.game().hiddenInformation()) { previousHiddenFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenWhatFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenWhoFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenCountFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenRotationFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenStateFrom = new boolean[sizeStackFrom][context.players().size()]; previousHiddenValueFrom = new boolean[sizeStackFrom][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenFrom[lvl][pid] = csFrom.isHidden(pid, from, lvl, typeFrom); previousHiddenWhatFrom[lvl][pid] = csFrom.isHiddenWhat(pid, from, lvl, typeFrom); previousHiddenWhoFrom[lvl][pid] = csFrom.isHiddenWho(pid, from, lvl, typeFrom); previousHiddenCountFrom[lvl][pid] = csFrom.isHiddenCount(pid, from, lvl, typeFrom); previousHiddenStateFrom[lvl][pid] = csFrom.isHiddenState(pid, from, lvl, typeFrom); previousHiddenRotationFrom[lvl][pid] = csFrom.isHiddenRotation(pid, from, lvl, typeFrom); previousHiddenValueFrom[lvl][pid] = csFrom.isHiddenValue(pid, from, lvl, typeFrom); } } } final int sizeStackTo = csTo.sizeStack(to, typeTo); previousWhatTo = new int[sizeStackTo]; previousWhoTo = new int[sizeStackTo]; previousStateTo = new int[sizeStackTo]; previousRotationTo = new int[sizeStackTo]; previousValueTo = new int[sizeStackTo]; for(int lvl = 0 ; lvl < sizeStackTo; lvl++) { previousWhatTo[lvl] = csTo.what(to, lvl, typeTo); previousWhoTo[lvl] = csTo.who(to, lvl, typeTo); previousStateTo[lvl] = csTo.state(to, lvl, typeTo); previousRotationTo[lvl] = csTo.rotation(to, lvl, typeTo); previousValueTo[lvl] = csTo.value(to, lvl, typeTo); if(context.game().hiddenInformation()) { previousHiddenTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenWhatTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenWhoTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenCountTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenRotationTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenStateTo = new boolean[sizeStackTo][context.players().size()]; previousHiddenValueTo = new boolean[sizeStackTo][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenTo[lvl][pid] = csTo.isHidden(pid, to, lvl, typeTo); previousHiddenWhatTo[lvl][pid] = csTo.isHiddenWhat(pid, to, lvl, typeTo); previousHiddenWhoTo[lvl][pid] = csTo.isHiddenWho(pid, to, lvl, typeTo); previousHiddenCountTo[lvl][pid] = csTo.isHiddenCount(pid, to, lvl, typeTo); previousHiddenStateTo[lvl][pid] = csTo.isHiddenState(pid, to, lvl, typeTo); previousHiddenRotationTo[lvl][pid] = csTo.isHiddenRotation(pid, to, lvl, typeTo); previousHiddenValueTo[lvl][pid] = csTo.isHiddenValue(pid, to, lvl, typeTo); } } } } alreadyApplied = true; } if (!requiresStack) { // If the origin is empty we do not apply this action. if (csFrom.what(from, typeFrom) == 0 && csFrom.count(from, typeFrom) == 0) return this; final int count = csFrom.count(from, typeFrom); if (count == 1) { csFrom.remove(context.state(), from, typeFrom); // to keep the site of the item in cache for each player if (what != 0) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().remove(owner, what, from, typeFrom); } } else { final int valueFrom = (context.game().usesLineOfPlay() ? 1 : Constants.OFF); csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, count - 1, Constants.UNDEFINED, Constants.UNDEFINED, valueFrom, typeFrom); } // update the local state of the site To if (currentStateFrom != Constants.UNDEFINED && state == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentStateFrom, Constants.UNDEFINED, Constants.OFF, typeTo); else if (state != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, state, Constants.UNDEFINED, Constants.OFF, typeTo); // update the rotation state of the site To if (currentRotationFrom != Constants.UNDEFINED && rotation == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentRotationFrom, Constants.OFF, typeTo); else if (rotation != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, rotation, Constants.OFF, typeTo); // update the piece value of the site To if (currentValueFrom != Constants.UNDEFINED && value == Constants.UNDEFINED) { final int valueFrom = (context.game().usesLineOfPlay() ? 1 : currentValueFrom); csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, valueFrom, typeTo); } else if (value != Constants.UNDEFINED) { final int valueFrom = (context.game().usesLineOfPlay() ? 1 : value); csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, valueFrom, typeTo); } final int who = (what < 1) ? 0 : context.components()[what].owner(); if (csTo.what(to, typeTo) != 0 && (!context.game().requiresCount() || context.game().requiresCount() && csTo.what(to, typeTo) != what)) { final Component pieceToRemove = context.components()[csTo.what(to, typeTo)]; final int owner = pieceToRemove.owner(); context.state().owned().remove(owner, csTo.what(to, typeTo), to, typeTo); } final int valueToSet = (context.game().usesLineOfPlay() ? 1 : Constants.OFF); if (csTo.what(to, typeTo) == what && csTo.count(to, typeTo) > 0) { final int countToSet = (context.game().requiresCount() ? csTo.count(to, typeTo) + 1 : 1); csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, countToSet, Constants.UNDEFINED, Constants.UNDEFINED, valueToSet, typeTo); } else { csTo.setSite(context.state(), to, who, what, 1, Constants.UNDEFINED, Constants.UNDEFINED, valueToSet, typeTo); } // To keep the site of the item in cache for each player. if (what != 0 && csTo.count(to, typeTo) == 1) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, typeTo); } // We update the structure about track indices if the game uses track. updateOnTrackIndices(what, onTrackIndices, context.board().tracks()); // We keep the update for hidden info. if (context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(context.state(), pid, to, 0, typeTo, csFrom.isHidden(pid, from, 0, typeFrom)); csTo.setHiddenWhat(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWhat(pid, from, 0, typeFrom)); csTo.setHiddenWho(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWho(pid, from, 0, typeFrom)); csTo.setHiddenCount(context.state(), pid, to, 0, typeTo, csFrom.isHiddenCount(pid, from, 0, typeFrom)); csTo.setHiddenRotation(context.state(), pid, to, 0, typeTo, csFrom.isHiddenRotation(pid, from, 0, typeFrom)); csTo.setHiddenState(context.state(), pid, to, 0, typeTo, csFrom.isHiddenState(pid, from, 0, typeFrom)); csTo.setHiddenValue(context.state(), pid, to, 0, typeTo, csFrom.isHiddenValue(pid, from, 0, typeFrom)); if (csFrom.what(from, typeFrom) == 0) { csFrom.setHidden(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWhat(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWho(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenCount(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenRotation(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenValue(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenState(context.state(), pid, from, 0, typeFrom, false); } } } if (csTo.isEmpty(to, typeTo)) { throw new RuntimeException("Did not expect locationTo to be empty at site locnTo="+to+"(who, what,count,state)=(" + csTo.who(to, typeTo) + "," + csTo.what(to, typeTo) + "," + csTo.count(to, typeTo) + "," + csTo.state(to, typeTo) + "," + csTo.state(to, typeTo) + ")"); } } // on a stacking game else { if(from == to) return this; csFrom.remove(context.state(), from, typeFrom); if (csFrom.sizeStack(from, typeFrom) == 0) csFrom.addToEmpty(from, typeFrom); final int who = (what < 1) ? 0 : context.components()[what].owner(); if (!context.game().hasCard()) csTo.addItemGeneric(context.state(), to, what, who, context.game(), typeTo); if (csTo.sizeStack(to, typeTo) != 0) csTo.removeFromEmpty(to, typeTo); // to keep the site of the item in cache for each player Component pieceFrom = null; int ownerFrom = 0; if (what != 0) { pieceFrom = context.components()[what]; ownerFrom = pieceFrom.owner(); context.state().owned().add(ownerFrom, what, to, csTo.sizeStack(to, typeTo) - 1, typeTo); context.state().owned().remove(ownerFrom, what, from, csFrom.sizeStack(from, typeFrom), typeFrom); } // We update the structure about track indices if the game uses track. updateOnTrackIndices(what, onTrackIndices, context.board().tracks()); } return this; } /** * To update the onTrackIndices after a move. * * @param what The index of the component moved. * @param onTrackIndices The structure onTrackIndices * @param tracks The list of the tracks. */ public void updateOnTrackIndices(final int what, final OnTrackIndices onTrackIndices, final List<Track> tracks) { // We update the structure about track indices if the game uses track. if (what != 0 && onTrackIndices != null) { for (final Track track : tracks) { final int trackIdx = track.trackIdx(); final TIntArrayList indicesLocA = onTrackIndices.locToIndex(trackIdx, from); for (int k = 0; k < indicesLocA.size(); k++) { final int indexA = indicesLocA.getQuick(k); final int countAtIndex = onTrackIndices.whats(trackIdx, what, indicesLocA.getQuick(k)); if (countAtIndex > 0) { onTrackIndices.remove(trackIdx, what, 1, indexA); final TIntArrayList newWhatIndice = onTrackIndices.locToIndexFrom(trackIdx, to, indexA); if (newWhatIndice.size() > 0) { onTrackIndices.add(trackIdx, what, 1, newWhatIndice.getQuick(0)); } else { final TIntArrayList newWhatIndiceIfNotAfter = onTrackIndices.locToIndex(trackIdx, to); if (newWhatIndiceIfNotAfter.size() > 0) onTrackIndices.add(trackIdx, what, 1, newWhatIndiceIfNotAfter.getQuick(0)); } break; } } // If the piece was not in the track but enter on it, we update the structure // corresponding to that track. if (indicesLocA.size() == 0) { final TIntArrayList indicesLocB = onTrackIndices.locToIndex(trackIdx, to); if (indicesLocB.size() != 0) onTrackIndices.add(trackIdx, what, 1, indicesLocB.get(0)); } } } } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { // If a large piece was moved we call the right class. if(actionLargePiece) { undoLargePiece(context); return this; } final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; final Game game = context.game(); final State gameState = context.state(); final boolean requiresStack = context.currentInstanceContext().game().isStacking(); final int sizeStackFrom = csFrom.sizeStack(from, typeFrom); final int sizeStackTo = csTo.sizeStack(to, typeTo); if(requiresStack) // Stacking undo. { // We restore the from site for(int lvl = sizeStackFrom -1 ; lvl >= 0; lvl--) csFrom.remove(context.state(), from, lvl, typeFrom); for(int lvl = 0 ; lvl < previousWhatFrom.length; lvl++) { csFrom.addItemGeneric(gameState, from, previousWhatFrom[lvl], previousWhoFrom[lvl], previousStateFrom[lvl], previousRotationFrom[lvl], previousValueFrom[lvl], game, typeFrom); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, lvl, typeFrom, previousHiddenFrom[lvl][pid]); csFrom.setHiddenWhat(gameState, pid, from, lvl, typeFrom, previousHiddenWhatFrom[lvl][pid]); csFrom.setHiddenWho(gameState, pid, from, lvl, typeFrom, previousHiddenWhoFrom[lvl][pid]); csFrom.setHiddenCount(gameState, pid, from, lvl, typeFrom, previousHiddenCountFrom[lvl][pid]); csFrom.setHiddenState(gameState, pid, from, lvl, typeFrom, previousHiddenStateFrom[lvl][pid]); csFrom.setHiddenRotation(gameState, pid, from, lvl, typeFrom, previousHiddenRotationFrom[lvl][pid]); csFrom.setHiddenValue(gameState, pid, from, lvl, typeFrom, previousHiddenValueFrom[lvl][pid]); } } } // We restore the to site for(int lvl = sizeStackTo -1 ; lvl >= 0; lvl--) csTo.remove(context.state(), to, lvl, typeTo); for(int lvl = 0 ; lvl < previousWhatTo.length; lvl++) { csTo.addItemGeneric(gameState, to, previousWhatTo[lvl], previousWhoTo[lvl], previousStateTo[lvl], previousRotationTo[lvl], previousValueTo[lvl], game, typeTo); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, lvl, typeTo, previousHiddenTo[lvl][pid]); csTo.setHiddenWhat(gameState, pid, to, lvl, typeTo, previousHiddenWhatTo[lvl][pid]); csTo.setHiddenWho(gameState, pid, to, lvl, typeTo, previousHiddenWhoTo[lvl][pid]); csTo.setHiddenCount(gameState, pid, to, lvl, typeTo, previousHiddenCountTo[lvl][pid]); csTo.setHiddenState(gameState, pid, to, lvl, typeTo, previousHiddenStateTo[lvl][pid]); csTo.setHiddenRotation(gameState, pid, to, lvl, typeTo, previousHiddenRotationTo[lvl][pid]); csTo.setHiddenValue(gameState, pid, to, lvl, typeTo, previousHiddenValueTo[lvl][pid]); } } } } else // Non stacking undo. { csFrom.remove(context.state(), from, typeFrom); csTo.remove(context.state(), to, typeTo); csFrom.setSite(context.state(), from, previousWhoFrom[0], previousWhatFrom[0], previousCountFrom, previousStateFrom[0], previousRotationFrom[0], previousValueFrom[0], typeFrom); csTo.setSite(context.state(), to, previousWhoTo[0], previousWhatTo[0], previousCountTo, previousStateTo[0], previousRotationTo[0], previousValueTo[0], typeTo); if(context.game().hiddenInformation()) { if(previousHiddenFrom.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(gameState, pid, from, 0, typeFrom, previousHiddenFrom[0][pid]); csFrom.setHiddenWhat(gameState, pid, from, 0, typeFrom, previousHiddenWhatFrom[0][pid]); csFrom.setHiddenWho(gameState, pid, from, 0, typeFrom, previousHiddenWhoFrom[0][pid]); csFrom.setHiddenCount(gameState, pid, from, 0, typeFrom, previousHiddenCountFrom[0][pid]); csFrom.setHiddenState(gameState, pid, from, 0, typeFrom, previousHiddenStateFrom[0][pid]); csFrom.setHiddenRotation(gameState, pid, from, 0, typeFrom, previousHiddenRotationFrom[0][pid]); csFrom.setHiddenValue(gameState, pid, from, 0, typeFrom, previousHiddenValueFrom[0][pid]); } if(previousHiddenTo.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, 0, typeTo, previousHiddenTo[0][pid]); csTo.setHiddenWhat(gameState, pid, to, 0, typeTo, previousHiddenWhatTo[0][pid]); csTo.setHiddenWho(gameState, pid, to, 0, typeTo, previousHiddenWhoTo[0][pid]); csTo.setHiddenCount(gameState, pid, to, 0, typeTo, previousHiddenCountTo[0][pid]); csTo.setHiddenState(gameState, pid, to, 0, typeTo, previousHiddenStateTo[0][pid]); csTo.setHiddenRotation(gameState, pid, to, 0, typeTo, previousHiddenRotationTo[0][pid]); csTo.setHiddenValue(gameState, pid, to, 0, typeTo, previousHiddenValueTo[0][pid]); } } } if (csTo.sizeStack(to, typeTo) == 0) csTo.addToEmpty(to, typeTo); if (csFrom.sizeStack(from, typeFrom) != 0) csFrom.removeFromEmpty(from, typeFrom); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Move:"); if (typeFrom != null || (context != null && typeFrom != context.board().defaultSite())) { sb.append("typeFrom=" + typeFrom); sb.append(",from=" + from); } else sb.append("from=" + from); if (typeTo != null || (context != null && typeTo != context.board().defaultSite())) sb.append(",typeTo=" + typeTo); sb.append(",to=" + to); if (state != Constants.UNDEFINED) sb.append(",state=" + state); if (rotation != Constants.UNDEFINED) sb.append(",rotation=" + rotation); if (value != Constants.UNDEFINED) sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + from; result = prime * result + to; result = prime * result + state; result = prime * result + rotation; result = prime * result + value; result = prime * result + 1237; result = prime * result + ((typeFrom == null) ? 0 : typeFrom.hashCode()); result = prime * result + ((typeTo == null) ? 0 : typeTo.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionMoveTopPiece)) return false; final ActionMoveTopPiece other = (ActionMoveTopPiece) obj; return (decision == other.decision && from == other.from && to == other.to && state == other.state && rotation == other.rotation && value == other.value && typeFrom == other.typeFrom && typeTo == other.typeTo); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Move"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && !typeFrom.equals(context.board().defaultSite())) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (typeTo != null && !typeTo.equals(context.board().defaultSite())) sb.append("-" + typeTo + " " + newTo); else sb.append("-" + newTo); if (state != Constants.UNDEFINED) sb.append("=" + state); if (rotation != Constants.UNDEFINED) sb.append(" r" + rotation); if (value != Constants.UNDEFINED) sb.append(" v" + value); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Move "); String newFrom = from + ""; if (useCoords) { final int cid = (typeFrom == SiteType.Cell || typeFrom == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[from] : 0; if (cid == 0) { final SiteType realType = (typeFrom != null) ? typeFrom : context.board().defaultSite(); newFrom = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(from) .label(); } } if (typeFrom != null && typeTo != null && (!typeFrom.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(typeFrom + " " + newFrom); else sb.append(newFrom); String newTo = to + ""; if (useCoords) { final int cid = (typeTo == SiteType.Cell || typeTo == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (typeTo != null) ? typeTo : context.board().defaultSite(); if (to < context.game().equipment().containers()[cid].topology().getGraphElements(realType).size()) newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); else // The site is not existing. newTo = "??"; } } if (typeFrom != null && typeTo != null && (!typeTo.equals(context.board().defaultSite()) || !typeFrom.equals(typeTo))) sb.append(" - " + typeTo + " " + newTo); else sb.append("-" + newTo); if (state != Constants.UNDEFINED) sb.append(" state=" + state); if (rotation != Constants.UNDEFINED) sb.append(" rotation=" + rotation); if (state != Constants.UNDEFINED) sb.append(" state=" + state); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return typeFrom; } @Override public SiteType toType() { return typeTo; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int levelFrom() { return Constants.GROUND_LEVEL; } @Override public int levelTo() { return Constants.GROUND_LEVEL; } @Override public int state() { return state; } @Override public int rotation() { return rotation; } @Override public int value() { return value; } @Override public int count() { return 1; } @Override public boolean isStacking() { return false; } @Override public ActionType actionType() { return ActionType.Move; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final int contIdA = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdB = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csA = context.state().containerStates()[contIdA]; final ContainerState csB = context.state().containerStates()[contIdB]; final int whatA = csA.what(from, typeFrom); final int whatB = csB.what(to, typeTo); final int whoA = csA.who(from, typeFrom); final int whoB = csB.who(to, typeTo); final BitSet concepts = new BitSet(); // ---- Hop concepts if (ludemeConcept.get(Concept.HopDecision.id())) { concepts.set(Concept.HopDecision.id(), true); if (whatA != 0) { final Topology topology = context.topology(); final TopologyElement fromV = topology.getGraphElements(typeFrom).get(from); final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, typeFrom); AbsoluteDirection direction = null; int distance = Constants.UNDEFINED; for (final DirectionFacing facingDirection : directionsSupported) { final AbsoluteDirection absDirection = facingDirection.toAbsolute(); final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), absDirection); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < radial.steps().length; toIdx++) { final int toRadial = radial.steps()[toIdx].id(); if (toRadial == to) { direction = absDirection; distance = toIdx; break; } } if (direction != null) break; } } if (direction != null) { final List<Radial> radials = topology.trajectories().radials(typeFrom, fromV.index(), direction); for (final Radial radial : radials) { for (int toIdx = 1; toIdx < distance; toIdx++) { final int between = radial.steps()[toIdx].id(); final int whatBetween = csA.what(between, typeFrom); final int whoBetween = csA.who(between, typeFrom); if (whatBetween != 0) { if (areEnemies(context, whoA, whoBetween)) { if (whatB == 0) concepts.set(Concept.HopDecisionEnemyToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionEnemyToEnemy.id(), true); else concepts.set(Concept.HopDecisionEnemyToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); concepts.set(Concept.HopCaptureMoreThanOne.id(), true); } } else { if (whatB == 0) concepts.set(Concept.HopDecisionFriendToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.HopDecisionFriendToEnemy.id(), true); else concepts.set(Concept.HopDecisionFriendToFriend.id(), true); } if(distance > 1) { concepts.set(Concept.HopDecisionMoreThanOne.id(), true); } } } } } } } } if (ludemeConcept.get(Concept.HopEffect.id())) concepts.set(Concept.HopEffect.id(), true); // ---- Step concepts if (ludemeConcept.get(Concept.StepEffect.id())) concepts.set(Concept.StepEffect.id(), true); if (ludemeConcept.get(Concept.StepDecision.id())) { concepts.set(Concept.StepDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.StepDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.StepDecisionToEnemy.id(), true); else concepts.set(Concept.StepDecisionToFriend.id(), true); } } } // ---- Leap concepts if (ludemeConcept.get(Concept.LeapEffect.id())) concepts.set(Concept.LeapEffect.id(), true); if (ludemeConcept.get(Concept.LeapDecision.id())) { concepts.set(Concept.LeapDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.LeapDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.LeapDecisionToEnemy.id(), true); else concepts.set(Concept.LeapDecisionToFriend.id(), true); } } } // ---- Slide concepts if (ludemeConcept.get(Concept.SlideEffect.id())) concepts.set(Concept.SlideEffect.id(), true); if (ludemeConcept.get(Concept.SlideDecision.id())) { concepts.set(Concept.SlideDecision.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.SlideDecisionToEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.SlideDecisionToEnemy.id(), true); else concepts.set(Concept.SlideDecisionToFriend.id(), true); } } } // ---- FromTo concepts if (ludemeConcept.get(Concept.FromToDecision.id())) { if (contIdA == contIdB) concepts.set(Concept.FromToDecisionWithinBoard.id(), true); else concepts.set(Concept.FromToDecisionBetweenContainers.id(), true); if (whatA != 0) { if (whatB == 0) concepts.set(Concept.FromToDecisionEmpty.id(), true); else { if (areEnemies(context, whoA, whoB)) concepts.set(Concept.FromToDecisionEnemy.id(), true); else concepts.set(Concept.FromToDecisionFriend.id(), true); } } } if (ludemeConcept.get(Concept.FromToEffect.id())) concepts.set(Concept.FromToEffect.id(), true); // ---- Swap Pieces concepts if (ludemeConcept.get(Concept.SwapPiecesEffect.id())) concepts.set(Concept.SwapPiecesEffect.id(), true); if (ludemeConcept.get(Concept.SwapPiecesDecision.id())) concepts.set(Concept.SwapPiecesDecision.id(), true); // ---- Sow concepts if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.Sow.id())) concepts.set(Concept.Sow.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.SowBacktracking.id())) concepts.set(Concept.SowBacktracking.id(), true); return concepts; } /** * @param context The context. * @param who1 The id of a player. * @param who2 The id of a player. * @return True if these players are enemies. */ public static boolean areEnemies(final Context context, final int who1, final int who2) { if (who1 == 0 || who2 == 0 || who1 == who2) return false; if (context.game().requiresTeams()) { final TIntArrayList teamMembers = new TIntArrayList(); final int tid = context.state().getTeam(who1); for (int i = 1; i < context.game().players().size(); i++) if (context.state().getTeam(i) == tid) teamMembers.add(i); return !teamMembers.contains(who2); } return who1 != who2; } //-------------------------------------Large Piece code-------------------------------------- /** * Apply method only for large piece. * @param context The context. * @param store To store or not in the list of legal moves. * @return The action. */ public Action applyLargePiece ( final Context context, final boolean store ) { final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; int currentStateFrom = Constants.UNDEFINED; int currentRotationFrom = Constants.UNDEFINED; int currentValueFrom = Constants.UNDEFINED; Component piece = null; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; final ContainerState csTo = context.state().containerStates()[contIdTo]; // Take the local state of the site from. currentStateFrom = (csFrom.what(from, typeFrom) == 0) ? Constants.UNDEFINED : csFrom.state(from, typeFrom); currentRotationFrom = csFrom.rotation(from, typeFrom); currentValueFrom = csFrom.value(from, typeFrom); // Keep in memory the data of the site from and to (for undo method). if(!alreadyApplied) { previousStateFrom = new int[1]; previousRotationFrom = new int[1]; previousValueFrom = new int[1]; previousStateTo = new int[1]; previousRotationTo = new int[1]; previousValueTo = new int[1]; previousWhoTo = new int[1]; previousWhatTo = new int[1]; previousStateFrom[0] = currentStateFrom; previousRotationFrom[0] = currentRotationFrom; previousValueFrom[0] = currentValueFrom; previousStateTo[0] = csTo.state(to, typeTo); previousRotationTo[0] = csTo.rotation(to, typeTo); previousValueTo[0] = csTo.value(to, typeTo); previousWhoTo[0] = csTo.who(to, typeTo); previousWhatTo[0] = csTo.what(to, typeTo); previousCountFrom = csFrom.count(from, typeFrom); previousCountTo = csTo.count(to, typeTo); if(context.game().hiddenInformation()) { previousHiddenFrom = new boolean[1][context.players().size()]; previousHiddenWhatFrom = new boolean[1][context.players().size()]; previousHiddenWhoFrom = new boolean[1][context.players().size()]; previousHiddenCountFrom = new boolean[1][context.players().size()]; previousHiddenStateFrom = new boolean[1][context.players().size()]; previousHiddenRotationFrom = new boolean[1][context.players().size()]; previousHiddenValueFrom = new boolean[1][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenFrom[0][pid] = csFrom.isHidden(pid, from, 0, typeFrom); previousHiddenWhatFrom[0][pid] = csFrom.isHiddenWhat(pid, from, 0, typeFrom); previousHiddenWhoFrom[0][pid] = csFrom.isHiddenWho(pid, from, 0, typeFrom); previousHiddenCountFrom[0][pid] = csFrom.isHiddenCount(pid, from, 0, typeFrom); previousHiddenStateFrom[0][pid] = csFrom.isHiddenState(pid, from, 0, typeFrom); previousHiddenRotationFrom[0][pid] = csFrom.isHiddenRotation(pid, from, 0, typeFrom); previousHiddenValueFrom[0][pid] = csFrom.isHiddenValue(pid, from, 0, typeFrom); } previousHiddenTo = new boolean[1][context.players().size()]; previousHiddenWhatTo = new boolean[1][context.players().size()]; previousHiddenWhoTo = new boolean[1][context.players().size()]; previousHiddenCountTo = new boolean[1][context.players().size()]; previousHiddenStateTo = new boolean[1][context.players().size()]; previousHiddenRotationTo = new boolean[1][context.players().size()]; previousHiddenValueTo = new boolean[1][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHiddenTo[0][pid] = csTo.isHidden(pid, to, 0, typeTo); previousHiddenWhatTo[0][pid] = csTo.isHiddenWhat(pid, to, 0, typeTo); previousHiddenWhoTo[0][pid] = csTo.isHiddenWho(pid, to, 0, typeTo); previousHiddenCountTo[0][pid] = csTo.isHiddenCount(pid, to, 0, typeTo); previousHiddenStateTo[0][pid] = csTo.isHiddenState(pid, to, 0, typeTo); previousHiddenRotationTo[0][pid] = csTo.isHiddenRotation(pid, to, 0, typeTo); previousHiddenValueTo[0][pid] = csTo.isHiddenValue(pid, to, 0, typeTo); } } alreadyApplied = true; } // If the origin is empty we do not apply this action. if (csFrom.what(from, typeFrom) == 0 && csFrom.count(from, typeFrom) == 0) return this; final int what = csFrom.what(from, typeFrom); final int count = csFrom.count(from, typeFrom); if (count == 1) { csFrom.remove(context.state(), from, typeFrom); // to keep the site of the item in cache for each player if (what != 0) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().remove(owner, what, from, typeFrom); } if (piece != null && piece.isLargePiece()) { final Component largePiece = piece; final TIntArrayList locs = largePiece.locs(context, from, currentStateFrom, context.topology()); for (int i = 0; i < locs.size(); i++) { csFrom.addToEmpty(locs.getQuick(i), SiteType.Cell); csFrom.setCount(context.state(), locs.getQuick(i), 0); } if (largePiece.isDomino() && context.containerId()[from] == 0) { for (int i = 0; i < 4; i++) csFrom.setValueCell(context.state(), locs.getQuick(i), largePiece.getValue()); for (int i = 4; i < 8; i++) csFrom.setValueCell(context.state(), locs.getQuick(i), largePiece.getValue2()); } } } else { csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, count - 1, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeFrom); } // update the local state of the site To if (currentStateFrom != Constants.UNDEFINED && state == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentStateFrom, Constants.UNDEFINED, Constants.OFF, typeTo); else if (state != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, state, Constants.UNDEFINED, Constants.OFF, typeTo); // update the rotation state of the site To if (currentRotationFrom != Constants.UNDEFINED && rotation == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentRotationFrom, Constants.OFF, typeTo); else if (rotation != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, rotation, Constants.OFF, typeTo); // update the piece value of the site To if (currentValueFrom != Constants.UNDEFINED && value == Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : currentValueFrom), typeTo); else if (value != Constants.UNDEFINED) csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : value), typeTo); final int who = (what < 1) ? 0 : context.components()[what].owner(); if (csTo.what(to, typeTo) != 0 && (!context.game().requiresCount() || context.game().requiresCount() && csTo.what(to, typeTo) != what)) { final Component pieceToRemove = context.components()[csTo.what(to, typeTo)]; final int owner = pieceToRemove.owner(); context.state().owned().remove(owner, csTo.what(to, typeTo), to, typeTo); } final int valueToSet = (context.game().usesLineOfPlay() ? 1 : Constants.OFF); if (csTo.what(to, typeTo) == what && csTo.count(to, typeTo) > 0) { final int countToSet = (context.game().requiresCount() ? csTo.count(to, typeTo) + 1 : 1); csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, countToSet, Constants.UNDEFINED, Constants.UNDEFINED, valueToSet, typeTo); } else { csTo.setSite(context.state(), to, who, what, 1, Constants.UNDEFINED, Constants.UNDEFINED, valueToSet, typeTo); } // To keep the site of the item in cache for each player. if (what != 0 && csTo.count(to, typeTo) == 1) { piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, typeTo); } // In case of LargePiece we update the empty chunkSet if (piece != null && piece.isLargePiece()) { final Component largePiece = piece; final TIntArrayList locs = largePiece.locs(context, to, state, context.topology()); for (int i = 0; i < locs.size(); i++) { csTo.removeFromEmpty(locs.getQuick(i), SiteType.Cell); final int countTo = (context.game().usesLineOfPlay() ? piece.index() : 1); csTo.setCount(context.state(), locs.getQuick(i), countTo); } if (context.game().usesLineOfPlay() && context.containerId()[to] == 0) { for (int i = 0; i < 4; i++) { csTo.setValueCell(context.state(), locs.getQuick(i), largePiece.getValue()); } for (int i = 4; i < 8; i++) { csTo.setValueCell(context.state(), locs.getQuick(i), largePiece.getValue2()); } // We update the line of play for dominoes for (int i = 0; i < context.containers()[0].numSites(); i++) csTo.setPlayable(context.state(), i, false); for (int i = 0; i < context.containers()[0].numSites(); i++) { if (csTo.what(i, typeTo) != 0) { final Component currentComponent = context.components()[csTo.what(i, typeTo)]; final int currentState = csTo.state(i, typeTo); final TIntArrayList locsToUpdate = largePiece.locs(context, i, currentState, context.topology()); lineOfPlayDominoes(context, locsToUpdate.getQuick(0), locsToUpdate.getQuick(1), getDirnDomino(0, currentState), false, true); lineOfPlayDominoes(context, locsToUpdate.getQuick(7), locsToUpdate.getQuick(6), getDirnDomino(2, currentState), false, false); if (currentComponent.isDoubleDomino()) { lineOfPlayDominoes(context, locsToUpdate.getQuick(2), locsToUpdate.getQuick(5), getDirnDomino(1, currentState), true, true); lineOfPlayDominoes(context, locsToUpdate.getQuick(3), locsToUpdate.getQuick(4), getDirnDomino(3, currentState), true, true); } } } } } // We update the structure about track indices if the game uses track. updateOnTrackIndices(what, onTrackIndices, context.board().tracks()); // We keep the update for hidden info. if (context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(context.state(), pid, to, 0, typeTo, csFrom.isHidden(pid, from, 0, typeFrom)); csTo.setHiddenWhat(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWhat(pid, from, 0, typeFrom)); csTo.setHiddenWho(context.state(), pid, to, 0, typeTo, csFrom.isHiddenWho(pid, from, 0, typeFrom)); csTo.setHiddenCount(context.state(), pid, to, 0, typeTo, csFrom.isHiddenCount(pid, from, 0, typeFrom)); csTo.setHiddenRotation(context.state(), pid, to, 0, typeTo, csFrom.isHiddenRotation(pid, from, 0, typeFrom)); csTo.setHiddenState(context.state(), pid, to, 0, typeTo, csFrom.isHiddenState(pid, from, 0, typeFrom)); csTo.setHiddenValue(context.state(), pid, to, 0, typeTo, csFrom.isHiddenValue(pid, from, 0, typeFrom)); if (csFrom.what(from, typeFrom) == 0) { csFrom.setHidden(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWhat(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenWho(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenCount(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenRotation(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenValue(context.state(), pid, from, 0, typeFrom, false); csFrom.setHiddenState(context.state(), pid, from, 0, typeFrom, false); } } } if (csTo.isEmpty(to, typeTo)) { throw new RuntimeException("Did not expect locationTo to be empty at site locnTo="+to+"(who, what,count,state)=(" + csTo.who(to, typeTo) + "," + csTo.what(to, typeTo) + "," + csTo.count(to, typeTo) + "," + csTo.state(to, typeTo) + "," + csTo.state(to, typeTo) + ")"); } return this; } //------------------------------------------------------------------------- /** * Undo method for large piece. * @param context The context. * @return The action undo. */ public Action undoLargePiece(final Context context) { final int contIdTo = typeTo.equals(SiteType.Cell) ? context.containerId()[to] : 0; final int contIdFrom = typeFrom.equals(SiteType.Cell) ? context.containerId()[from] : 0; final Game game = context.game(); // Nothing to do if no modification. if(from == to && state == Constants.UNDEFINED && rotation == Constants.UNDEFINED && value == Constants.UNDEFINED || previousCountFrom == 0) return this; // System.out.println("loc is " + loc); final ContainerState csTo = context.state().containerStates()[contIdTo]; final ContainerState csFrom = context.state().containerStates()[contIdFrom]; // If the origin is empty we do not apply this action. if (csTo.what(to, typeTo) == 0 && csTo.count(to, typeTo) == 0) return this; final int what = csTo.what(to, typeTo); final int countTo = csTo.count(to, typeTo); int currentStateTo = Constants.UNDEFINED; int currentRotationTo = Constants.UNDEFINED; int currentValueTo = Constants.UNDEFINED; Component piece = null; // take the local state of the site from currentStateTo = (csTo.what(to, typeTo) == 0) ? Constants.UNDEFINED : csTo.state(to, typeTo); currentRotationTo = csTo.rotation(to, typeTo); currentValueTo = csTo.value(to, typeTo); if (countTo == 1) { csTo.remove(context.state(), to, typeTo); // to keep the site of the item in cache for each player if (what != 0) piece = context.components()[what]; // In case of LargePiece we update the empty chunkSet if (piece != null && piece.isLargePiece()) { final Component largePiece = piece; final TIntArrayList locs = largePiece.locs(context, to, currentStateTo, context.topology()); for (int i = 0; i < locs.size(); i++) { csTo.addToEmpty(locs.getQuick(i), SiteType.Cell); csTo.setCount(context.state(), locs.getQuick(i), 0); csTo.remove(context.state(), locs.getQuick(i), SiteType.Cell); } if (largePiece.isDomino() && context.containerId()[to] == 0) { for (int i = 0; i < 4; i++) csTo.setValueCell(context.state(), locs.getQuick(i), 0); for (int i = 4; i < 8; i++) csTo.setValueCell(context.state(), locs.getQuick(i), 0); } } // In case the to site was occupied by another piece we re-add it. if(previousWhatTo[0] > 0) { if(csTo.what(to, typeTo) != previousWhatTo[0]) { final int toValue = (context.game().hasDominoes() ? 1 : previousValueTo[0]); csTo.setSite(context.state(), to, previousWhoTo[0], previousWhatTo[0], 1, previousStateTo[0], previousRotationTo[0], toValue, typeTo); Component pieceTo = null; // to keep the site of the item in cache for each player pieceTo = context.components()[previousWhatTo[0]]; if (pieceTo.isDomino()) context.state().remainingDominoes().remove(pieceTo.index()); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(context.state(), pid, to, 0, typeTo, previousHiddenTo[0][pid]); csTo.setHiddenWhat(context.state(), pid, to, 0, typeTo, previousHiddenWhatTo[0][pid]); csTo.setHiddenWho(context.state(), pid, to, 0, typeTo, previousHiddenWhoTo[0][pid]); csTo.setHiddenCount(context.state(), pid, to, 0, typeTo, previousHiddenCountTo[0][pid]); csTo.setHiddenState(context.state(), pid, to, 0, typeTo, previousHiddenStateTo[0][pid]); csTo.setHiddenRotation(context.state(), pid, to, 0, typeTo, previousHiddenRotationTo[0][pid]); csTo.setHiddenValue(context.state(), pid, to, 0, typeTo, previousHiddenValueTo[0][pid]); } } } } else { if(previousStateTo[0] > 0 || previousRotationTo[0] > 0 || previousValueTo[0] > 0) { final int toValue = (context.game().hasDominoes() ? 1 : previousValueTo[0]); csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, 0, previousStateTo[0], previousRotationTo[0], toValue, typeTo); } } } else { if(game.hasDominoes()) // Special case for dominoes because the count is used for the value of each part of the domino too.... { csTo.remove(context.state(), to, typeTo); // to keep the site of the item in cache for each player if (what != 0) piece = context.components()[what]; // In case of LargePiece we update the empty chunkSet if (piece != null && piece.isLargePiece()) { final Component largePiece = piece; final TIntArrayList locs = largePiece.locs(context, to, currentStateTo, context.topology()); for (int i = 0; i < locs.size(); i++) { csTo.addToEmpty(locs.getQuick(i), SiteType.Cell); csTo.setCount(context.state(), locs.getQuick(i), 0); csTo.remove(context.state(), locs.getQuick(i), SiteType.Cell); } if (largePiece.isDomino() && context.containerId()[to] == 0) { for (int i = 0; i < 4; i++) csTo.setValueCell(context.state(), locs.getQuick(i), 0); for (int i = 4; i < 8; i++) csTo.setValueCell(context.state(), locs.getQuick(i), 0); } } } else { csTo.setSite(context.state(), to, Constants.UNDEFINED, Constants.UNDEFINED, previousCountTo, Constants.UNDEFINED, Constants.UNDEFINED, (context.game().usesLineOfPlay() ? 1 : Constants.OFF), typeTo); } } // update the local state of the site From if (currentStateTo != Constants.UNDEFINED && previousStateFrom[0] == Constants.UNDEFINED) csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentStateTo, Constants.UNDEFINED, Constants.OFF, typeFrom); else if (previousStateFrom[0] != Constants.UNDEFINED) csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, previousStateFrom[0], Constants.UNDEFINED, Constants.OFF, typeFrom); // update the rotation state of the site From if (currentRotationTo != Constants.UNDEFINED && previousRotationFrom[0] == Constants.UNDEFINED) csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, currentRotationTo, Constants.OFF, typeFrom); else if (previousRotationFrom[0] != Constants.UNDEFINED) csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, previousRotationFrom[0], Constants.OFF, typeFrom); // update the piece value of the site From if (currentValueTo != Constants.UNDEFINED && previousValueFrom[0] == Constants.UNDEFINED) { final int fromValue = (context.game().usesLineOfPlay() ? 1 : currentValueTo); csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, fromValue, typeFrom); } else if (previousValueFrom[0] != Constants.UNDEFINED) { final int fromValue = (context.game().usesLineOfPlay() ? 1 : previousValueFrom[0]); csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, fromValue, typeFrom); } final int who = (what < 1) ? 0 : context.components()[what].owner(); if (csFrom.what(from, typeFrom) == what && csFrom.count(from, typeFrom) > 0) { final int fromCount = (context.game().requiresCount() ? csFrom.count(from, typeFrom) + 1 : 1); final int fromValue = (context.game().usesLineOfPlay() ? 1 : Constants.OFF); csFrom.setSite(context.state(), from, Constants.UNDEFINED, Constants.UNDEFINED, fromCount, Constants.UNDEFINED, Constants.UNDEFINED, fromValue, typeFrom); } else { final int fromValue = (context.game().usesLineOfPlay() ? 1 : Constants.OFF); csFrom.setSite(context.state(), from, who, what, 1, Constants.UNDEFINED, Constants.UNDEFINED, fromValue, typeFrom); } // to keep the site of the item in cache for each player if (what != 0) piece = context.components()[what]; // In case of LargePiece we update the empty chunkSet if (piece != null && piece.isLargePiece()) { final Component largePiece = piece; final TIntArrayList locs = largePiece.locs(context, from, previousStateFrom[0], context.topology()); for (int i = 0; i < locs.size(); i++) { csFrom.removeFromEmpty(locs.getQuick(i), SiteType.Cell); final int fromCount = (context.game().usesLineOfPlay() ? piece.index() : 1); csFrom.setCount(context.state(), locs.getQuick(i), fromCount); } if (context.game().usesLineOfPlay() && context.containerId()[to] == 0) { for (int i = 0; i < 4; i++) csTo.setValueCell(context.state(), locs.getQuick(i), 0); for (int i = 4; i < 8; i++) csTo.setValueCell(context.state(), locs.getQuick(i), 0); // We update the line of play for dominoes for (int i = 0; i < context.containers()[0].numSites(); i++) csTo.setPlayable(context.state(), i, false); for (int i = 0; i < context.containers()[0].numSites(); i++) { if (csTo.what(i, typeTo) != 0) { final Component currentComponent = context.components()[csTo.what(i, typeTo)]; final int currentState = csTo.state(i, typeTo); final TIntArrayList locsToUpdate = largePiece.locs(context, i, currentState, context.topology()); lineOfPlayDominoes(context, locsToUpdate.getQuick(0), locsToUpdate.getQuick(1), getDirnDomino(0, currentState), false, true); lineOfPlayDominoes(context, locsToUpdate.getQuick(7), locsToUpdate.getQuick(6), getDirnDomino(2, currentState), false, false); if (currentComponent.isDoubleDomino()) { lineOfPlayDominoes(context, locsToUpdate.getQuick(2), locsToUpdate.getQuick(5), getDirnDomino(1, currentState), true, true); lineOfPlayDominoes(context, locsToUpdate.getQuick(3), locsToUpdate.getQuick(4), getDirnDomino(3, currentState), true, true); } } } } } // We keep the update for hidden info. if (context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csFrom.setHidden(context.state(), pid, from, 0, typeFrom, csTo.isHidden(pid, to, 0, typeTo)); csFrom.setHiddenWhat(context.state(), pid, from, 0, typeFrom, csTo.isHiddenWhat(pid, to, 0, typeTo)); csFrom.setHiddenWho(context.state(), pid, from, 0, typeFrom, csTo.isHiddenWho(pid, to, 0, typeTo)); csFrom.setHiddenCount(context.state(), pid, from, 0, typeFrom, csTo.isHiddenCount(pid, to, 0, typeTo)); csFrom.setHiddenRotation(context.state(), pid, from, 0, typeFrom, csTo.isHiddenRotation(pid, to, 0, typeTo)); csFrom.setHiddenState(context.state(), pid, from, 0, typeFrom, csTo.isHiddenState(pid, to, 0, typeTo)); csFrom.setHiddenValue(context.state(), pid, from, 0, typeFrom, csTo.isHiddenValue(pid, to, 0, typeTo)); if (csTo.what(to, typeTo) == 0) { csTo.setHidden(context.state(), pid, to, 0, typeTo, false); csTo.setHiddenWhat(context.state(), pid, to, 0, typeTo, false); csTo.setHiddenWho(context.state(), pid, to, 0, typeTo, false); csTo.setHiddenCount(context.state(), pid, to, 0, typeTo, false); csTo.setHiddenRotation(context.state(), pid, to, 0, typeTo, false); csTo.setHiddenValue(context.state(), pid, to, 0, typeTo, false); csTo.setHiddenState(context.state(), pid, to, 0, typeTo, false); } } } if (csFrom.isEmpty(from, typeFrom)) { throw new RuntimeException("Undo: Did not expect locationFrom to be empty at site locnFrom="+from+"(who, what,count,state)=(" + csFrom.who(from, typeFrom) + "," + csFrom.what(from, typeFrom) + "," + csFrom.count(from, typeFrom) + "," + csFrom.state(from, typeFrom) + "," + csFrom.state(from, typeFrom) + ")"); } return this; } }
66,540
36.743052
208
java
Ludii
Ludii-master/Core/src/other/action/move/remove/ActionRemove.java
package other.action.move.remove; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; @SuppressWarnings("javadoc") public class ActionRemove extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * @param type The graph element type. * @param to Location to remove the component(s). * @param level Level to remove the component(s). * @param applied True if the action has to be applied immediately. */ public static BaseAction construct ( final SiteType type, final int to, final int level, final boolean applied ) { if(!applied) return new ActionRemoveNonApplied(type, to); else if(level != Constants.UNDEFINED) return new ActionRemoveLevel(type, to, level); else return new ActionRemoveTopPiece(type, to); } /** * Reconstructs a ActionRemove object from a detailed String (generated using toDetailedString()) * * @param detailedString */ public static BaseAction construct (final String detailedString) { assert (detailedString.startsWith("[Remove:")); final String strType = Action.extractData(detailedString, "type"); final SiteType type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); final int to = Integer.parseInt(strTo); final String strLevel = Action.extractData(detailedString, "level"); final int level = (strLevel.isEmpty()) ? Constants.UNDEFINED : Integer.parseInt(strLevel); final String strApplied = Action.extractData(detailedString, "applied"); final boolean applied = (strApplied.isEmpty()) ? true : Boolean.parseBoolean(strApplied); final String strDecision = Action.extractData(detailedString, "decision"); final boolean decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); BaseAction action = null; if(!applied) action = new ActionRemoveNonApplied(type, to); else if(level != Constants.UNDEFINED) action = new ActionRemoveLevel(type, to, level); else action= new ActionRemoveTopPiece(type, to); action.setDecision(decision); return action; } //------------------------------------------------------------------------- @Override public Action apply(Context context, boolean store) { throw new UnsupportedOperationException("ActionRemove.eval(): Should never be called directly."); } @Override public Action undo(Context context, boolean discard) { throw new UnsupportedOperationException("ActionRemove.undo(): Should never be called directly."); } @Override public String toTrialFormat(Context context) { // Should never be there return null; } @Override public String getDescription() { // Should never be there return null; } @Override public String toTurnFormat(Context context, boolean useCoords) { // Should never be there return null; } @Override public ActionType actionType() { return ActionType.Remove; } //------------------------------------------------------------------------- }
3,222
25.858333
99
java
Ludii
Ludii-master/Core/src/other/action/move/remove/ActionRemoveLevel.java
package other.action.move.remove; import java.util.BitSet; import game.Game; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.SiteType; import gnu.trove.list.array.TIntArrayList; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; /** * Removes one component from a location and a specific level. * * @author Eric.Piette */ public final class ActionRemoveLevel extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location where to remove the component(s). */ private final int to; /** Level where to remove the component(s). */ private final int level; /** The graph element type. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** Previous What value of the site. */ private int[] previousWhat; /** Previous Who value of the site. */ private int[] previousWho; /** Previous Site state value of the site. */ private int[] previousState; /** Previous Rotation value of the site. */ private int[] previousRotation; /** Previous Piece value of the site. */ private int[] previousValue; /** Previous Piece count of the site. */ private int previousCount; /** The previous hidden info values of the site before to be removed. */ private boolean[][] previousHidden; /** The previous hidden what info values of the site before to be removed. */ private boolean[][] previousHiddenWhat; /** The previous hidden who info values of the site before to be removed. */ private boolean[][] previousHiddenWho; /** The previous hidden count info values of the site before to be removed. */ private boolean[][] previousHiddenCount; /** The previous hidden rotation info values of the site before to be removed. */ private boolean[][] previousHiddenRotation; /** The previous hidden State info values of the site before to be removed. */ private boolean[][] previousHiddenState; /** The previous hidden Value info values of the site before to be removed. */ private boolean[][] previousHiddenValue; //------------------------------------------------------------------------- /** * @param type The graph element type. * @param to Location to remove the component(s). * @param level Level to remove the component(s). */ public ActionRemoveLevel ( final SiteType type, final int to, final int level ) { this.to = to; this.level = level; this.type = type; } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { final Game game = context.game(); type = (type == null) ? context.board().defaultSite() : type; final int contID = to >= context.containerId().length ? 0 : context.containerId()[to]; final ContainerState cs = context.state().containerStates()[contID]; final boolean requiresStack = game.isStacking(); // Keep in memory the data of the site from and to (for undo method) if(!alreadyApplied) { if(!requiresStack) { previousCount = cs.count(to, type); previousWhat = new int[1]; previousWho = new int[1]; previousState = new int[1]; previousRotation = new int[1]; previousValue = new int[1]; previousWhat[0] = cs.what(to, 0, type); previousWho[0] = cs.who(to, 0, type); previousState[0] = cs.state(to, 0, type); previousRotation[0] = cs.rotation(to, 0, type); previousValue[0] = cs.value(to, 0, type); if(context.game().hiddenInformation()) { previousHidden = new boolean[1][context.players().size()]; previousHiddenWhat = new boolean[1][context.players().size()]; previousHiddenWho = new boolean[1][context.players().size()]; previousHiddenCount = new boolean[1][context.players().size()]; previousHiddenRotation = new boolean[1][context.players().size()]; previousHiddenState = new boolean[1][context.players().size()]; previousHiddenValue = new boolean[1][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHidden[0][pid] = cs.isHidden(pid, to, 0, type); previousHiddenWhat[0][pid] = cs.isHiddenWhat(pid, to, 0, type); previousHiddenWho[0][pid] = cs.isHiddenWho(pid, to, 0, type); previousHiddenCount[0][pid] = cs.isHiddenCount(pid, to, 0, type); previousHiddenState[0][pid] = cs.isHiddenState(pid, to, 0, type); previousHiddenRotation[0][pid] = cs.isHiddenRotation(pid, to, 0, type); previousHiddenValue[0][pid] = cs.isHiddenValue(pid, to, 0, type); } } } else // Stacking game. { final int sizeStackTo = cs.sizeStack(to, type); previousWhat = new int[sizeStackTo]; previousWho = new int[sizeStackTo]; previousState = new int[sizeStackTo]; previousRotation = new int[sizeStackTo]; previousValue = new int[sizeStackTo]; for(int lvl = 0 ; lvl < sizeStackTo; lvl++) { previousWhat[lvl] = cs.what(to, lvl, type); previousWho[lvl] = cs.who(to, lvl, type); previousState[lvl] = cs.state(to, lvl, type); previousRotation[lvl] = cs.rotation(to, lvl, type); previousValue[lvl] = cs.value(to, lvl, type); if(context.game().hiddenInformation()) { previousHidden = new boolean[sizeStackTo][context.players().size()]; previousHiddenWhat = new boolean[sizeStackTo][context.players().size()]; previousHiddenWho = new boolean[sizeStackTo][context.players().size()]; previousHiddenCount = new boolean[sizeStackTo][context.players().size()]; previousHiddenRotation = new boolean[sizeStackTo][context.players().size()]; previousHiddenState = new boolean[sizeStackTo][context.players().size()]; previousHiddenValue = new boolean[sizeStackTo][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHidden[lvl][pid] = cs.isHidden(pid, to, lvl, type); previousHiddenWhat[lvl][pid] = cs.isHiddenWhat(pid, to, lvl, type); previousHiddenWho[lvl][pid] = cs.isHiddenWho(pid, to, lvl, type); previousHiddenCount[lvl][pid] = cs.isHiddenCount(pid, to, lvl, type); previousHiddenState[lvl][pid] = cs.isHiddenState(pid, to, lvl, type); previousHiddenRotation[lvl][pid] = cs.isHiddenRotation(pid, to, lvl, type); previousHiddenValue[lvl][pid] = cs.isHiddenValue(pid, to, lvl, type); } } } } alreadyApplied = true; } // Apply remove level site. final int pieceIdx = cs.remove(context.state(), to, level, type); if (context.game().isStacking()) { if (pieceIdx > 0) { final Component piece = context.components()[pieceIdx]; final int owner = piece.owner(); context.state().owned().remove(owner, pieceIdx, to, level, type); } if (cs.sizeStack(to, type) == 0) cs.addToEmpty(to, type); } else { if (pieceIdx > 0) { final Component piece = context.components()[pieceIdx]; final int owner = piece.owner(); context.state().owned().remove(owner, pieceIdx, to, type); } } // We update the structure about track indices if the game uses track. if (pieceIdx > 0) { final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); if (onTrackIndices != null) { for (final Track track : context.board().tracks()) { final int trackIdx = track.trackIdx(); final TIntArrayList indices = onTrackIndices.locToIndex(trackIdx, to); for (int i = 0; i < indices.size(); i++) onTrackIndices.remove(trackIdx, pieceIdx, 1, indices.getQuick(i)); } } } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final Game game = context.game(); final int contIdTo = type.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csTo = context.state().containerStates()[contIdTo]; final State gameState = context.state(); final boolean requiresStack = context.currentInstanceContext().game().isStacking(); final int sizeStackTo = csTo.sizeStack(to, type); if(requiresStack) // Stacking undo. { // We restore the to site for(int lvl = sizeStackTo -1 ; lvl >= 0; lvl--) csTo.remove(context.state(), to, lvl, type); for(int lvl = 0 ; lvl < previousWhat.length; lvl++) { csTo.addItemGeneric(gameState, to, previousWhat[lvl], previousWho[lvl], previousState[lvl], previousRotation[lvl], previousValue[lvl], game, type); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, lvl, type, previousHidden[lvl][pid]); csTo.setHiddenWhat(gameState, pid, to, lvl, type, previousHiddenWhat[lvl][pid]); csTo.setHiddenWho(gameState, pid, to, lvl, type, previousHiddenWho[lvl][pid]); csTo.setHiddenCount(gameState, pid, to, lvl, type, previousHiddenCount[lvl][pid]); csTo.setHiddenState(gameState, pid, to, lvl, type, previousHiddenState[lvl][pid]); csTo.setHiddenRotation(gameState, pid, to, lvl, type, previousHiddenRotation[lvl][pid]); csTo.setHiddenValue(gameState, pid, to, lvl, type, previousHiddenValue[lvl][pid]); } } } } else // Non stacking undo. { csTo.remove(context.state(), to, type); csTo.setSite(context.state(), to, previousWho[0], previousWhat[0], previousCount, previousState[0], previousRotation[0], previousValue[0], type); if(context.game().hasDominoes()) { if (previousWhat.length > 0 && previousWhat[0] != 0) { Component piece = context.components()[previousWhat[0]]; if (piece.isDomino()) context.state().remainingDominoes().remove(piece.index()); } } if(context.game().hiddenInformation()) { if(previousHidden.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, 0, type, previousHidden[0][pid]); csTo.setHiddenWhat(gameState, pid, to, 0, type, previousHiddenWhat[0][pid]); csTo.setHiddenWho(gameState, pid, to, 0, type, previousHiddenWho[0][pid]); csTo.setHiddenCount(gameState, pid, to, 0, type, previousHiddenCount[0][pid]); csTo.setHiddenState(gameState, pid, to, 0, type, previousHiddenState[0][pid]); csTo.setHiddenRotation(gameState, pid, to, 0, type, previousHiddenRotation[0][pid]); csTo.setHiddenValue(gameState, pid, to, 0, type, previousHiddenValue[0][pid]); } } } if (csTo.sizeStack(to, type) != 0) csTo.removeFromEmpty(to, type); return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + 1231; result = prime * result + to; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionRemoveLevel)) return false; final ActionRemoveLevel other = (ActionRemoveLevel) obj; return (decision == other.decision && to == other.to && type == other.type); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Remove:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); sb.append(",level=" + level); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Remove"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append("/" + level); sb.append("-"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Remove "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append("/" + level); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return level; } @Override public int levelTo() { return level; } @Override public ActionType actionType() { return ActionType.Remove; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final BitSet concepts = new BitSet(); final int contId = type.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contId]; final int what = cs.what(to, type); if (what != 0) { if (isDecision()) concepts.set(Concept.RemoveDecision.id(), true); else concepts.set(Concept.RemoveEffect.id(), true); if (ludemeConcept.get(Concept.ReplacementCapture.id())) concepts.set(Concept.ReplacementCapture.id(), true); if (ludemeConcept.get(Concept.HopCapture.id())) concepts.set(Concept.HopCapture.id(), true); if (ludemeConcept.get(Concept.DirectionCapture.id())) concepts.set(Concept.DirectionCapture.id(), true); if (ludemeConcept.get(Concept.EncloseCapture.id())) concepts.set(Concept.EncloseCapture.id(), true); if (ludemeConcept.get(Concept.CustodialCapture.id())) concepts.set(Concept.CustodialCapture.id(), true); if (ludemeConcept.get(Concept.InterveneCapture.id())) concepts.set(Concept.InterveneCapture.id(), true); if (ludemeConcept.get(Concept.SurroundCapture.id())) concepts.set(Concept.SurroundCapture.id(), true); if (ludemeConcept.get(Concept.CaptureSequence.id())) concepts.set(Concept.CaptureSequence.id(), true); if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.PushEffect.id())) concepts.set(Concept.PushEffect.id(), true); } return concepts; } }
16,484
29.584416
151
java
Ludii
Ludii-master/Core/src/other/action/move/remove/ActionRemoveNonApplied.java
package other.action.move.remove; import java.util.BitSet; import game.rules.play.moves.Moves; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; /** * Remove later a specific site (sequential capture). * * @author Eric.Piette */ public final class ActionRemoveNonApplied extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location where to remove the component(s). */ private final int to; /** The graph element type. */ private SiteType type; //------------------------------------------------------------------------- /** * @param type The graph element type. * @param to Location to remove the component(s). */ public ActionRemoveNonApplied ( final SiteType type, final int to ) { this.type = type; this.to = to; } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { context.state().addSitesToRemove(to); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().removeSitesToRemove(to); return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionRemoveNonApplied)) return false; final ActionRemoveNonApplied other = (ActionRemoveNonApplied) obj; return (decision == other.decision && to == other.to); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Remove:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); sb.append(",applied=" + false); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Remove"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append("-"); sb.append("..."); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Remove "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append(" applied = false"); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return Constants.GROUND_LEVEL; } @Override public int levelTo() { return Constants.GROUND_LEVEL; } @Override public ActionType actionType() { return ActionType.Remove; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final BitSet concepts = new BitSet(); final int contId = type.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contId]; final int what = cs.what(to, type); if (what != 0) { if (isDecision()) concepts.set(Concept.RemoveDecision.id(), true); else concepts.set(Concept.RemoveEffect.id(), true); if (ludemeConcept.get(Concept.ReplacementCapture.id())) concepts.set(Concept.ReplacementCapture.id(), true); if (ludemeConcept.get(Concept.HopCapture.id())) concepts.set(Concept.HopCapture.id(), true); if (ludemeConcept.get(Concept.DirectionCapture.id())) concepts.set(Concept.DirectionCapture.id(), true); if (ludemeConcept.get(Concept.EncloseCapture.id())) concepts.set(Concept.EncloseCapture.id(), true); if (ludemeConcept.get(Concept.CustodialCapture.id())) concepts.set(Concept.CustodialCapture.id(), true); if (ludemeConcept.get(Concept.InterveneCapture.id())) concepts.set(Concept.InterveneCapture.id(), true); if (ludemeConcept.get(Concept.SurroundCapture.id())) concepts.set(Concept.SurroundCapture.id(), true); if (ludemeConcept.get(Concept.CaptureSequence.id())) concepts.set(Concept.CaptureSequence.id(), true); if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); } return concepts; } }
6,516
22.192171
108
java
Ludii
Ludii-master/Core/src/other/action/move/remove/ActionRemoveTopPiece.java
package other.action.move.remove; import java.util.BitSet; import game.Game; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.SiteType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; /** * Removes one or more component(s) from a location (always the top piece). * * @author Eric.Piette */ public class ActionRemoveTopPiece extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Location where to remove the component(s). */ private final int to; /** The graph element type. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** Previous What value of the site. */ private int[] previousWhat; /** Previous Who value of the site. */ private int[] previousWho; /** Previous Site state value of the site. */ private int[] previousState; /** Previous Rotation value of the site. */ private int[] previousRotation; /** Previous Piece value of the site. */ private int[] previousValue; /** Previous Piece count of the site. */ private int previousCount; /** The previous hidden info values of the site before to be removed. */ private boolean[][] previousHidden; /** The previous hidden what info values of the site before to be removed. */ private boolean[][] previousHiddenWhat; /** The previous hidden who info values of the site before to be removed. */ private boolean[][] previousHiddenWho; /** The previous hidden count info values of the site before to be removed. */ private boolean[][] previousHiddenCount; /** The previous hidden rotation info values of the site before to be removed. */ private boolean[][] previousHiddenRotation; /** The previous hidden State info values of the site before to be removed. */ private boolean[][] previousHiddenState; /** The previous hidden Value info values of the site before to be removed. */ private boolean[][] previousHiddenValue; //------------------------------------------------------------------------- /** * @param type The graph element type. * @param to Location to remove the component(s). */ public ActionRemoveTopPiece ( final SiteType type, final int to ) { this.to = to; this.type = type; } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { final Game game = context.game(); type = (type == null) ? context.board().defaultSite() : type; final int contID = to >= context.containerId().length ? 0 : context.containerId()[to]; final ContainerState cs = context.state().containerStates()[contID]; final boolean requiresStack = game.isStacking(); // Keep in memory the data of the site from and to (for undo method) if(!alreadyApplied) { if(!requiresStack) { previousCount = cs.count(to, type); previousWhat = new int[1]; previousWho = new int[1]; previousState = new int[1]; previousRotation = new int[1]; previousValue = new int[1]; previousWhat[0] = cs.what(to, 0, type); previousWho[0] = cs.who(to, 0, type); previousState[0] = cs.state(to, 0, type); previousRotation[0] = cs.rotation(to, 0, type); previousValue[0] = cs.value(to, 0, type); if(context.game().hiddenInformation()) { previousHidden = new boolean[1][context.players().size()]; previousHiddenWhat = new boolean[1][context.players().size()]; previousHiddenWho = new boolean[1][context.players().size()]; previousHiddenCount = new boolean[1][context.players().size()]; previousHiddenRotation = new boolean[1][context.players().size()]; previousHiddenState = new boolean[1][context.players().size()]; previousHiddenValue = new boolean[1][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHidden[0][pid] = cs.isHidden(pid, to, 0, type); previousHiddenWhat[0][pid] = cs.isHiddenWhat(pid, to, 0, type); previousHiddenWho[0][pid] = cs.isHiddenWho(pid, to, 0, type); previousHiddenCount[0][pid] = cs.isHiddenCount(pid, to, 0, type); previousHiddenState[0][pid] = cs.isHiddenState(pid, to, 0, type); previousHiddenRotation[0][pid] = cs.isHiddenRotation(pid, to, 0, type); previousHiddenValue[0][pid] = cs.isHiddenValue(pid, to, 0, type); } } } else // Stacking game. { final int sizeStackTo = cs.sizeStack(to, type); previousWhat = new int[sizeStackTo]; previousWho = new int[sizeStackTo]; previousState = new int[sizeStackTo]; previousRotation = new int[sizeStackTo]; previousValue = new int[sizeStackTo]; for(int lvl = 0 ; lvl < sizeStackTo; lvl++) { previousWhat[lvl] = cs.what(to, lvl, type); previousWho[lvl] = cs.who(to, lvl, type); previousState[lvl] = cs.state(to, lvl, type); previousRotation[lvl] = cs.rotation(to, lvl, type); previousValue[lvl] = cs.value(to, lvl, type); if(context.game().hiddenInformation()) { previousHidden = new boolean[sizeStackTo][context.players().size()]; previousHiddenWhat = new boolean[sizeStackTo][context.players().size()]; previousHiddenWho = new boolean[sizeStackTo][context.players().size()]; previousHiddenCount = new boolean[sizeStackTo][context.players().size()]; previousHiddenRotation = new boolean[sizeStackTo][context.players().size()]; previousHiddenState = new boolean[sizeStackTo][context.players().size()]; previousHiddenValue = new boolean[sizeStackTo][context.players().size()]; for (int pid = 1; pid < context.players().size(); pid++) { previousHidden[lvl][pid] = cs.isHidden(pid, to, lvl, type); previousHiddenWhat[lvl][pid] = cs.isHiddenWhat(pid, to, lvl, type); previousHiddenWho[lvl][pid] = cs.isHiddenWho(pid, to, lvl, type); previousHiddenCount[lvl][pid] = cs.isHiddenCount(pid, to, lvl, type); previousHiddenState[lvl][pid] = cs.isHiddenState(pid, to, lvl, type); previousHiddenRotation[lvl][pid] = cs.isHiddenRotation(pid, to, lvl, type); previousHiddenValue[lvl][pid] = cs.isHiddenValue(pid, to, lvl, type); } } } } alreadyApplied = true; } // We remove the piece. final int pieceIdx = cs.remove(context.state(), to, type); // We update the owned structure and the empty bitsets. if (context.game().isStacking()) { if (pieceIdx > 0) { final int levelRemoved = cs.sizeStack(to, type); final Component piece = context.components()[pieceIdx]; final int owner = piece.owner(); context.state().owned().remove(owner, pieceIdx, to, levelRemoved, type); } if (cs.sizeStack(to, type) == 0) cs.addToEmpty(to, type); } else { if (pieceIdx > 0) { final Component piece = context.components()[pieceIdx]; final int owner = piece.owner(); context.state().owned().remove(owner, pieceIdx, to, type); } } // We update the structure about track indices if the game uses track. if (pieceIdx > 0) { final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); if (onTrackIndices != null) { for (final Track track : context.board().tracks()) { final int trackIdx = track.trackIdx(); final TIntArrayList indices = onTrackIndices.locToIndex(trackIdx, to); for (int i = 0; i < indices.size(); i++) onTrackIndices.remove(trackIdx, pieceIdx, 1, indices.getQuick(i)); } } } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final Game game = context.game(); final int contIdTo = type.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState csTo = context.state().containerStates()[contIdTo]; final State gameState = context.state(); final boolean requiresStack = context.currentInstanceContext().game().isStacking(); final int sizeStackTo = csTo.sizeStack(to, type); if(requiresStack) // Stacking undo. { // We restore the to site for(int lvl = sizeStackTo -1 ; lvl >= 0; lvl--) csTo.remove(context.state(), to, lvl, type); for(int lvl = 0 ; lvl < previousWhat.length; lvl++) { csTo.addItemGeneric(gameState, to, previousWhat[lvl], previousWho[lvl], previousState[lvl], previousRotation[lvl], previousValue[lvl], game, type); if(context.game().hiddenInformation()) { for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, lvl, type, previousHidden[lvl][pid]); csTo.setHiddenWhat(gameState, pid, to, lvl, type, previousHiddenWhat[lvl][pid]); csTo.setHiddenWho(gameState, pid, to, lvl, type, previousHiddenWho[lvl][pid]); csTo.setHiddenCount(gameState, pid, to, lvl, type, previousHiddenCount[lvl][pid]); csTo.setHiddenState(gameState, pid, to, lvl, type, previousHiddenState[lvl][pid]); csTo.setHiddenRotation(gameState, pid, to, lvl, type, previousHiddenRotation[lvl][pid]); csTo.setHiddenValue(gameState, pid, to, lvl, type, previousHiddenValue[lvl][pid]); } } } } else // Non stacking undo. { csTo.remove(context.state(), to, type); csTo.setSite(context.state(), to, previousWho[0], previousWhat[0], previousCount, previousState[0], previousRotation[0], previousValue[0], type); if(context.game().hasDominoes()) { if (previousWhat.length > 0 && previousWhat[0] != 0) { Component piece = context.components()[previousWhat[0]]; if (piece.isDomino()) context.state().remainingDominoes().remove(piece.index()); } } if(context.game().hiddenInformation()) { if(previousHidden.length > 0) for (int pid = 1; pid < context.players().size(); pid++) { csTo.setHidden(gameState, pid, to, 0, type, previousHidden[0][pid]); csTo.setHiddenWhat(gameState, pid, to, 0, type, previousHiddenWhat[0][pid]); csTo.setHiddenWho(gameState, pid, to, 0, type, previousHiddenWho[0][pid]); csTo.setHiddenCount(gameState, pid, to, 0, type, previousHiddenCount[0][pid]); csTo.setHiddenState(gameState, pid, to, 0, type, previousHiddenState[0][pid]); csTo.setHiddenRotation(gameState, pid, to, 0, type, previousHiddenRotation[0][pid]); csTo.setHiddenValue(gameState, pid, to, 0, type, previousHiddenValue[0][pid]); } } } if (csTo.sizeStack(to, type) != 0) csTo.removeFromEmpty(to, type); return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + 1231; result = prime * result + to; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionRemoveTopPiece)) return false; final ActionRemoveTopPiece other = (ActionRemoveTopPiece) obj; return (decision == other.decision && to == other.to && type == other.type); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Remove:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Remove"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append("-"); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Remove "); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public int from() { return to; } @Override public int to() { return to; } @Override public int levelFrom() { return Constants.GROUND_LEVEL; } @Override public int levelTo() { return Constants.GROUND_LEVEL; } @Override public ActionType actionType() { return ActionType.Remove; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet ludemeConcept = (movesLudeme != null) ? movesLudeme.concepts(context.game()) : new BitSet(); final BitSet concepts = new BitSet(); final int contId = type.equals(SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contId]; final int what = cs.what(to, type); if (what != 0) { if (isDecision()) concepts.set(Concept.RemoveDecision.id(), true); else concepts.set(Concept.RemoveEffect.id(), true); if (ludemeConcept.get(Concept.ReplacementCapture.id())) concepts.set(Concept.ReplacementCapture.id(), true); if (ludemeConcept.get(Concept.HopCapture.id())) concepts.set(Concept.HopCapture.id(), true); if (ludemeConcept.get(Concept.DirectionCapture.id())) concepts.set(Concept.DirectionCapture.id(), true); if (ludemeConcept.get(Concept.EncloseCapture.id())) concepts.set(Concept.EncloseCapture.id(), true); if (ludemeConcept.get(Concept.CustodialCapture.id())) concepts.set(Concept.CustodialCapture.id(), true); if (ludemeConcept.get(Concept.InterveneCapture.id())) concepts.set(Concept.InterveneCapture.id(), true); if (ludemeConcept.get(Concept.SurroundCapture.id())) concepts.set(Concept.SurroundCapture.id(), true); if (ludemeConcept.get(Concept.CaptureSequence.id())) concepts.set(Concept.CaptureSequence.id(), true); if (ludemeConcept.get(Concept.SowCapture.id())) concepts.set(Concept.SowCapture.id(), true); if (ludemeConcept.get(Concept.SowRemove.id())) concepts.set(Concept.SowRemove.id(), true); if (ludemeConcept.get(Concept.PushEffect.id())) concepts.set(Concept.PushEffect.id(), true); } return concepts; } }
16,411
29.966038
151
java
Ludii
Ludii-master/Core/src/other/action/others/ActionForfeit.java
package other.action.others; import game.functions.booleans.BooleanConstant; import game.rules.end.End; import game.rules.end.If; import game.rules.end.Result; import game.types.play.ResultType; import game.types.play.RoleType; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; /** * Forfeits a player. * * @author Eric.Piette */ public final class ActionForfeit extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The player. */ private final RoleType player; /** * * @param player The player who forfeits. */ public ActionForfeit(final RoleType player) { this.player = player; } /** * Reconstructs an ActionForfeit object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionForfeit(final String detailedString) { assert (detailedString.startsWith("[Forfeit:")); final String strPlayer = Action.extractData(detailedString, "player"); player = RoleType.valueOf(strPlayer); decision = true; } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { // To forfeit a player has to lose directly. new End(new If(new BooleanConstant(true), null, null, new Result(player, ResultType.Loss)), null).eval(context); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Forfeit:"); sb.append("player=" + player); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionForfeit)) return false; final ActionForfeit other = (ActionForfeit) obj; return player.equals(other.player); } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Forfeit " + player; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Forfeit " + player + ")"; } //------------------------------------------------------------------------- @Override public String getDescription() { return "Forfeit"; } //------------------------------------------------------------------------- @Override public ActionType actionType() { return ActionType.Forfeit; } @Override public boolean isForfeit() { return true; } }
3,049
20.328671
114
java
Ludii
Ludii-master/Core/src/other/action/others/ActionNextInstance.java
package other.action.others; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; /** * Moves the state on to the next instance in a Match. * * @author Eric.Piette */ public final class ActionNextInstance extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * Constructor. */ public ActionNextInstance() { // ... } /** * Reconstructs an ActionNextInstance object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionNextInstance(final String detailedString) { assert (detailedString.startsWith("[NextInstance:")); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { // Nothing to do return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[NextInstance:"); if (decision) sb.append("decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionNextInstance)) return false; final ActionNextInstance other = (ActionNextInstance) obj; return decision == other.decision; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Next Game"; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Next Game)"; } //------------------------------------------------------------------------- @Override public String getDescription() { return "NextInstance"; } //------------------------------------------------------------------------- @Override public boolean containsNextInstance() { return true; } @Override public ActionType actionType() { return ActionType.NextInstance; } }
2,664
19.5
81
java
Ludii
Ludii-master/Core/src/other/action/others/ActionNote.java
package other.action.others; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; /** * Sends a message to a player. * * @author Eric.Piette */ public final class ActionNote extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The message. */ private final String message; /** The player index. */ private final int player; /** * @param message The message to send. * @param player The player to send the message. */ public ActionNote ( final String message, final int player ) { this.message = message; this.player = player; } /** * Reconstructs an ActionNote object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionNote(final String detailedString) { assert (detailedString.startsWith("[Note:")); final String strMessage = Action.extractData(detailedString, "message"); message = strMessage; final String strPlayer = Action.extractData(detailedString, "to"); player = Integer.parseInt(strPlayer); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { context.state().addNote(context.trial().moveNumber(), player, message); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { // No need to undo. return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Note:"); sb.append("message=" + message); sb.append(",to=" + player); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + message.hashCode(); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionNote)) return false; final ActionNote other = (ActionNote) obj; return decision == other.decision && message.equals(other.message) && player == other.player; } @Override public String getDescription() { return "Note"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Note P" + player + " \"" + message + "\""; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Note \"" + message + "\" to " + player + ")"; } //------------------------------------------------------------------------- @Override public int who() { return player; } @Override public String message() { return message; } @Override public ActionType actionType() { return ActionType.Note; } }
3,303
20.316129
95
java
Ludii
Ludii-master/Core/src/other/action/others/ActionPass.java
package other.action.others; import java.util.BitSet; import game.rules.play.moves.Moves; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Pass the turn. * * @author Eric.Piette */ public final class ActionPass extends BaseAction { private static final long serialVersionUID = 1L; /** To specify if that pass action is forced. */ private final boolean forced; //------------------------------------------------------------------------- /** * Constructor. * @param forced True if forced pass */ public ActionPass ( final boolean forced ) { this.forced = forced; } /** * Reconstructs an ActionPass object from a detailed String * (generated using toDetailedString()) * @param detailedString */ public ActionPass(final String detailedString) { assert (detailedString.startsWith("[Pass:")); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); final String strForced = Action.extractData(detailedString, "forced"); forced = (strForced.isEmpty()) ? false : Boolean.parseBoolean(strForced); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { // Nothing to do return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Pass:"); if (decision) sb.append("decision=" + decision); if (forced) sb.append(",forced=" + forced); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionPass)) return false; final ActionPass other = (ActionPass) obj; return decision == other.decision && forced == other.forced; } //------------------------------------------------------------------------- @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Pass"; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Pass)"; } //------------------------------------------------------------------------- @Override public String getDescription() { return "Pass"; } @Override public boolean isPass() { return true; } @Override public ActionType actionType() { return ActionType.Pass; } @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); if (decision) concepts.set(Concept.PassDecision.id(), true); else concepts.set(Concept.PassEffect.id(), true); return concepts; } @Override public boolean isForced() { return forced; } }
3,325
19.157576
81
java
Ludii
Ludii-master/Core/src/other/action/others/ActionPropose.java
package other.action.others; import java.util.BitSet; import game.rules.play.moves.Moves; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Proposes a subject to vote. * * @author Eric.Piette */ public final class ActionPropose extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The proposition. */ private final String proposition; /** The proposition represented as an int */ private final int propositionInt; /** * @param proposition The proposition. * @param propositionInt The proposition represented by a simple int */ public ActionPropose ( final String proposition, final int propositionInt ) { this.proposition = proposition; this.propositionInt = propositionInt; } /** * Reconstructs an ActionPropose object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionPropose(final String detailedString) { assert (detailedString.startsWith("[Propose:")); final String strProposition = Action.extractData(detailedString, "proposition"); proposition = strProposition; final String strPropositionInt = Action.extractData(detailedString, "propositionInt"); propositionInt = Integer.parseInt(strPropositionInt); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { context.state().propositions().add(propositionInt); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().propositions().remove(propositionInt); return this; } //------------------------------------------------------------------------- @Override public boolean isPropose() { return true; } @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Propose:"); sb.append("proposition=" + proposition); sb.append(",propositionInt=" + propositionInt); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + proposition.hashCode(); result = prime * result + propositionInt; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionPropose)) return false; final ActionPropose other = (ActionPropose) obj; return decision == other.decision && proposition.equals(other.proposition) && propositionInt == other.propositionInt; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Propose \"" + proposition + "\""; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Propose \"" + proposition + "\")"; } //------------------------------------------------------------------------- @Override public String getDescription() { return "Propose"; } //------------------------------------------------------------------------- @Override public String proposition() { return proposition; } /** * @return Int representation of proposition */ public int propositionInt() { return propositionInt; } @Override public boolean isOtherMove() { return true; } @Override public ActionType actionType() { return ActionType.Propose; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); if (decision) concepts.set(Concept.ProposeDecision.id(), true); else concepts.set(Concept.ProposeEffect.id(), true); return concepts; } }
4,300
21.756614
119
java
Ludii
Ludii-master/Core/src/other/action/others/ActionSetValueOfPlayer.java
package other.action.others; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; /** * Sets the value of a player in the state. * * @author Eric.Piette */ public final class ActionSetValueOfPlayer extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The player. */ private final int player; /** The value */ private final int value; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private int previousValue; //------------------------------------------------------------------------- /** * @param player The index of the player. * @param value The value. */ public ActionSetValueOfPlayer ( final int player, final int value ) { this.player = player; this.value = value; } /** * Reconstructs an ActionSetValueOfPlayer object from a detailed String * (generated using toDetailedString()) * * @param detailedString */ public ActionSetValueOfPlayer(final String detailedString) { assert (detailedString.startsWith("[SetValueOfPlayer:")); final String strPlayer = Action.extractData(detailedString, "player"); player = Integer.parseInt(strPlayer); final String strValue = Action.extractData(detailedString, "value"); value = Integer.parseInt(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if(!alreadyApplied) { previousValue = context.state().getValue(player); alreadyApplied = true; } context.state().setValueForPlayer(player, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().setValueForPlayer(player, previousValue); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetValueOfPlayer:"); sb.append("player=" + player); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + player; result = prime * result + value; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetValueOfPlayer)) return false; final ActionSetValueOfPlayer other = (ActionSetValueOfPlayer) obj; return decision == other.decision && player == other.player && value == other.value; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "P" + player + " value=" + value; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(value " + "P" + player + "=" + value + ")"; } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetValueOfPlayer"; } @Override public ActionType actionType() { return ActionType.SetValueOfPlayer; } }
3,817
22.8625
123
java
Ludii
Ludii-master/Core/src/other/action/others/ActionSwap.java
package other.action.others; import java.util.BitSet; import game.rules.play.moves.Moves; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Swap two players. * * @author Eric.Piette */ public final class ActionSwap extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The first player to swap.*/ private final int player1; /** The second player to swap.*/ private final int player2; /** * @param player1 The index of the first player. * @param player2 The index of the second player. */ public ActionSwap ( final int player1, final int player2 ) { this.player1 = player1; this.player2 = player2; } /** * Reconstructs an ActionSwap object from a detailed String * (generated using toDetailedString()) * @param detailedString */ public ActionSwap(final String detailedString) { assert (detailedString.startsWith("[Swap:")); final String strPlayer1 = Action.extractData(detailedString, "player1"); player1 = Integer.parseInt(strPlayer1); final String strPlayer2 = Action.extractData(detailedString, "player2"); player2 = Integer.parseInt(strPlayer2); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { context.state().swapPlayerOrder(player1, player2); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().swapPlayerOrder(player2, player1); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Swap:"); sb.append("player1=" + player1); sb.append(",player2=" + player2); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + player1; result = prime * result + player2; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSwap)) return false; final ActionSwap other = (ActionSwap) obj; return (decision == other.decision && player1 == other.player1 && player2 == other.player2); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Swap"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Swap " + "P" + player1 + " P" + player2; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Swap " + "P" + player1 + " P" + player2 + ")"; } //------------------------------------------------------------------------- @Override public boolean isOtherMove() { return true; } @Override public boolean isSwap() { return true; } /** * @return player1 */ public int player1() { return player1; } /** * @return player2 */ public int player2() { return player2; } @Override public ActionType actionType() { return ActionType.Swap; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); if (decision) concepts.set(Concept.SwapPlayersDecision.id(), true); else concepts.set(Concept.SwapPlayersEffect.id(), true); return concepts; } }
4,081
20.484211
94
java
Ludii
Ludii-master/Core/src/other/action/others/ActionVote.java
package other.action.others; import java.util.BitSet; import game.rules.play.moves.Moves; import gnu.trove.list.array.TIntArrayList; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Votes on a proposition done previously. * * @author Eric.Piette */ public final class ActionVote extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The vote. */ private final String vote; /** The vote represented as an int. */ private final int voteInt; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous votes. */ private TIntArrayList previousVotes; /** The previous propositions. */ private TIntArrayList previousPropositions; /** The decision previously done. */ private int previousIsDecided; //------------------------------------------------------------------------- /** * @param vote The vote. * @param voteInt The vote represented by a simple int */ public ActionVote(final String vote, final int voteInt) { this.vote = vote; this.voteInt = voteInt; } /** * Reconstructs an ActionVote object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionVote(final String detailedString) { assert (detailedString.startsWith("[Vote:")); final String strVote = Action.extractData(detailedString, "vote"); vote = strVote; final String strVoteInt = Action.extractData(detailedString, "voteInt"); voteInt = Integer.parseInt(strVoteInt); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { context.state().votes().add(voteInt); final TIntArrayList votes = context.state().votes(); final int nbPlayers = context.game().players().count(); // If the vote is over we get the result. if (votes.size() == nbPlayers) { if(!alreadyApplied) { previousIsDecided = context.state().isDecided(); previousVotes = new TIntArrayList(); for(int i = 0; i < context.state().votes().size()-1; i++) previousVotes.add(context.state().votes().get(i)); previousPropositions = new TIntArrayList(context.state().propositions()); alreadyApplied = true; } final TIntArrayList votesChecked = new TIntArrayList(); int countForDecision = 0; int decisionindex = 0; for (int i = 0; i < votes.size(); i++) { final int v = votes.getQuick(i); int currentCount = 0; if (!votesChecked.contains(v)) { votesChecked.add(v); for (int j = i; j < votes.size(); j++) { if (votes.getQuick(j) == v) currentCount++; } if (currentCount > countForDecision) { countForDecision = currentCount; decisionindex = i; } } } // Decision takes only by a majority of player. if (countForDecision > (nbPlayers / 2)) context.state().setIsDecided(votes.get(decisionindex)); context.state().clearPropositions(); context.state().clearVotes(); } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final TIntArrayList votes = context.state().votes(); // If the vote is over we get the result. if (votes.isEmpty()) { context.state().setIsDecided(previousIsDecided); for(int i = 0; i < previousVotes.size(); i++) context.state().votes().add(previousVotes.get(i)); for(int i = 0; i < previousPropositions.size(); i++) context.state().propositions().add(previousPropositions.get(i)); } else { context.state().votes().remove(voteInt); } return this; } //------------------------------------------------------------------------- @Override public boolean isVote() { return true; } @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Vote:"); sb.append("vote=" + vote); sb.append(",voteInt=" + voteInt); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + vote.hashCode(); result = prime * result + voteInt; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionVote)) return false; final ActionVote other = (ActionVote) obj; return decision == other.decision && vote.equals(other.vote) && voteInt == other.voteInt; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Vote \"" + vote + "\""; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Vote \"" + vote + "\")"; } //------------------------------------------------------------------------- @Override public String getDescription() { return "Vote"; } //------------------------------------------------------------------------- @Override public String vote() { return vote; } /** * @return Int representation of vote */ public int voteInt() { return voteInt; } @Override public boolean isOtherMove() { return true; } @Override public ActionType actionType() { return ActionType.Vote; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); if (decision) concepts.set(Concept.VoteDecision.id(), true); else concepts.set(Concept.VoteEffect.id(), true); return concepts; } }
6,306
22.621723
123
java
Ludii
Ludii-master/Core/src/other/action/puzzle/ActionReset.java
package other.action.puzzle; import game.types.board.SiteType; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; import other.state.container.ContainerState; import other.state.puzzle.ContainerDeductionPuzzleState; /** * Resets all the values of a variable to not set in a deduction puzzle. * * @author Matthew.Stephenson and Eric.piette */ public class ActionReset extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The graph element type. */ private SiteType type; /** Index of the site (the variable) to reset. */ private final int var; /** Maximum number of values. */ private final int max; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private boolean previousValues[]; //------------------------------------------------------------------------- /** * @param var The index of the site. * @param whatMax The max variable. * @param type The graph element type. */ public ActionReset ( final SiteType type, final int var, final int whatMax ) { this.type = type; this.var = var; this.max = whatMax; } /** * Reconstructs an ActionReset object from a detailed String * (generated using toDetailedString()) * @param detailedString */ public ActionReset(final String detailedString) { assert (detailedString.startsWith("[Reset:")); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "var"); var = Integer.parseInt(strTo); final String strMax = Action.extractData(detailedString, "max"); max = Integer.parseInt(strMax); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; final int contID = context.containerId()[0]; final ContainerState sc = context.state().containerStates()[contID]; final ContainerDeductionPuzzleState ps = (ContainerDeductionPuzzleState) sc; if(!alreadyApplied) { final int maxValue = context.board().getRange(type).max(context); final int minValue = context.board().getRange(type).min(context); previousValues = new boolean[maxValue - minValue + 1]; for(int i = 0; i < previousValues.length; i++) previousValues[i] = ps.bit(var, i, type); alreadyApplied = true; } if (type.equals(SiteType.Vertex)) ps.resetVariable(SiteType.Vertex, var, max); if (type.equals(SiteType.Edge)) ps.resetVariable(SiteType.Edge, var, max); if (type.equals(SiteType.Cell)) ps.resetVariable(SiteType.Cell, var, max); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { type = (type == null) ? context.board().defaultSite() : type; final int contID = context.containerId()[0]; final ContainerState sc = context.state().containerStates()[contID]; final ContainerDeductionPuzzleState ps = (ContainerDeductionPuzzleState) sc; if (type.equals(SiteType.Vertex)) { for(int i = 0; i < previousValues.length; i++) if(ps.bit(var, i, type) != previousValues[i]) ps.toggleVerts(var, i); } else if(type.equals(SiteType.Edge)) { for(int i = 0; i < previousValues.length; i++) if(ps.bit(var, i, type) != previousValues[i]) ps.toggleEdges(var, i); } else { for(int i = 0; i < previousValues.length; i++) if(ps.bit(var, i, type) != previousValues[i]) ps.toggleCells(var, i); } return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Reset:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",var=" + var); } else sb.append("var=" + var); sb.append(",max=" + max); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + var; result = prime * result + max; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionReset)) return false; final ActionReset other = (ActionReset) obj; return (decision == other.decision && var == other.var && max == other.max && type == other.type); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Reset"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("Reset "); String newTo = var + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[var] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(var) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Reset "); String newTo = var + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[var] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(var) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public int from() { return var; } @Override public int to() { return var; } @Override public int count() { return 1; } @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public boolean isAlwaysGUILegal() { return true; } @Override public ActionType actionType() { return ActionType.Reset; } }
7,411
23.064935
123
java
Ludii
Ludii-master/Core/src/other/action/puzzle/ActionSet.java
package other.action.puzzle; import game.types.board.SiteType; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; import other.state.container.ContainerState; import other.state.puzzle.ContainerDeductionPuzzleState; /** * Sets a value to a variable in a deduction puzzle. * * @author Eric.Piette */ public class ActionSet extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Graph element type. */ private SiteType type; /** Index of the site (the variable) to set. */ private final int var; /** Value to set to the variable. */ private final int value; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous value. */ private boolean previousValues[]; //------------------------------------------------------------------------- /** * @param var The index of the site. * @param what The value to set to the variable. * @param type The graph element type. */ public ActionSet ( final SiteType type, final int var, final int what ) { this.var = var; this.value = what; this.type = type; } /** * Reconstructs an ActionSet object from a detailed String * (generated using toDetailedString()) * @param detailedString */ public ActionSet(final String detailedString) { assert (detailedString.startsWith("[Set:")); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "var"); var = Integer.parseInt(strTo); final String strValue = Action.extractData(detailedString, "value"); value = Integer.parseInt(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; final int contID = context.containerId()[0]; final ContainerState sc = context.state().containerStates()[contID]; final ContainerDeductionPuzzleState ps = (ContainerDeductionPuzzleState) sc; if(!alreadyApplied) { final int maxValue = context.board().getRange(type).max(context); final int minValue = context.board().getRange(type).min(context); previousValues = new boolean[maxValue - minValue + 1]; for(int i = 0; i < previousValues.length; i++) previousValues[i] = ps.bit(var, i, type); alreadyApplied = true; } if (type.equals(SiteType.Vertex)) ps.setVert(var, value); else if(type.equals(SiteType.Edge)) ps.setEdge(var, value); else ps.setCell(var, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { type = (type == null) ? context.board().defaultSite() : type; final int contID = context.containerId()[0]; final ContainerState sc = context.state().containerStates()[contID]; final ContainerDeductionPuzzleState ps = (ContainerDeductionPuzzleState) sc; if (type.equals(SiteType.Vertex)) { for(int i = 0; i < previousValues.length; i++) if(ps.bit(var, i, type) != previousValues[i]) ps.toggleVerts(var, i); } else if(type.equals(SiteType.Edge)) { for(int i = 0; i < previousValues.length; i++) if(ps.bit(var, i, type) != previousValues[i]) ps.toggleEdges(var, i); } else { for(int i = 0; i < previousValues.length; i++) if(ps.bit(var, i, type) != previousValues[i]) ps.toggleCells(var, i); } return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + var; result = prime * result + value; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSet)) return false; final ActionSet other = (ActionSet) obj; // Eric: Decision member is not checked, all the atomic action for puzzle are // decision. // return (decision == other.decision && // loc == other.loc && // what == other.what && type == other.type); return (var == other.var && value == other.value && type == other.type); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Set:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",var=" + var); } else sb.append("var" + var); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Set"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = var + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[var] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(var) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append("=" + value); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("("); String newTo = var + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[var] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(var) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append(" = " + value); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public int from() { return var; } @Override public int to() { return var; } @Override public int what() { return value; } @Override public int count() { return 1; } @Override public ActionType actionType() { return ActionType.SetValuePuzzle; } }
7,565
23.019048
123
java
Ludii
Ludii-master/Core/src/other/action/puzzle/ActionToggle.java
package other.action.puzzle; import game.types.board.SiteType; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; import other.state.container.ContainerState; import other.state.puzzle.ContainerDeductionPuzzleState; /** * Excludes a value from the possible values of a variable in a deduction * puzzle. * * @author Eric.Piette */ public class ActionToggle extends BaseAction //implements ActionAtomic { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The index of the site (the variable). */ private final int var; /** The value to toggle to the variable. */ private final int value; /** The graph element type. */ private SiteType type; //------------------------------------------------------------------------- /** * @param to The index of the site (the variable). * @param value The value to toggle. * @param type The graph element type. */ public ActionToggle ( final SiteType type, final int to, final int value ) { this.var = to; this.value = value; this.type = type; } /** * Reconstructs an ActionToggle object from a detailed String * (generated using toDetailedString()) * @param detailedString */ public ActionToggle(final String detailedString) { assert (detailedString.startsWith("[Toggle:")); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strVar = Action.extractData(detailedString, "var"); var = Integer.parseInt(strVar); final String strValue = Action.extractData(detailedString, "value"); value = Integer.parseInt(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; final int contID = context.containerId()[0]; final ContainerState sc = context.state().containerStates()[contID]; final ContainerDeductionPuzzleState ps = (ContainerDeductionPuzzleState) sc; if(type.equals(SiteType.Vertex)) ps.toggleVerts(var, value); else if(type.equals(SiteType.Edge)) ps.toggleEdges(var, value); else // Cell ps.toggleCells(var, value); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { type = (type == null) ? context.board().defaultSite() : type; final int contID = context.containerId()[0]; final ContainerState sc = context.state().containerStates()[contID]; final ContainerDeductionPuzzleState ps = (ContainerDeductionPuzzleState) sc; if(type.equals(SiteType.Vertex)) ps.toggleVerts(var, value); else if(type.equals(SiteType.Edge)) ps.toggleEdges(var, value); else // Cell ps.toggleCells(var, value); return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + var; result = prime * result + value; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionToggle)) return false; final ActionToggle other = (ActionToggle) obj; return (decision == other.decision && var == other.var && value == other.value && type == other.type); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Toggle:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",var=" + var); } else sb.append("var=" + var); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Toggle"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = var + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[var] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(var) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append("^=" + value); return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Toggle "); String newTo = var + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[var] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(var) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append(" on " + value); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public int from() { return var; } @Override public int to() { return var; } @Override public int count() { return 1; } @Override public ActionType actionType() { return ActionType.Toggle; } }
6,478
22.819853
108
java
Ludii
Ludii-master/Core/src/other/action/state/ActionAddPlayerToTeam.java
package other.action.state; import java.util.BitSet; import game.rules.play.moves.Moves; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Adds a player to a team. * * @author Eric.Piette */ public final class ActionAddPlayerToTeam extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The team. */ private final int team; /** The player. */ private final int player; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous team. */ private int previousTeam; //------------------------------------------------------------------------- /** * Constructor. * * @param team The index of the team. * @param player The index of the player. */ public ActionAddPlayerToTeam ( final int team, final int player ) { this.team = team; this.player = player; } /** * Reconstructs an ActionAddPlayerToTeam object from a detailed String * (generated using toDetailedString()) * * @param detailedString */ public ActionAddPlayerToTeam(final String detailedString) { assert (detailedString.startsWith("[AddPlayerToTeam:")); final String strPlayer = Action.extractData(detailedString, "player"); player = Integer.parseInt(strPlayer); final String strTeam = Action.extractData(detailedString, "team"); team = Integer.parseInt(strTeam); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if(!alreadyApplied) { previousTeam = context.state().getTeam(player); alreadyApplied = true; } context.state().setPlayerToTeam(player, team); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().setPlayerToTeam(player, previousTeam); return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[AddPlayerToTeam:"); sb.append("team=" + team); sb.append(",player=" + player); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + player; result = prime * result + team; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionAddPlayerToTeam)) return false; final ActionAddPlayerToTeam other = (ActionAddPlayerToTeam) obj; return team == other.team && player == other.player; } //------------------------------------------------------------------------- @Override public String getDescription() { return "AddPlayerToTeam"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Team" + team + " + P" + player; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Add P" + player + " to Team" + team + ")"; } @Override public ActionType actionType() { return ActionType.AddPlayerToTeam; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.Coalition.id(), true); return concepts; } }
4,136
22.372881
123
java
Ludii
Ludii-master/Core/src/other/action/state/ActionBet.java
package other.action.state; import java.util.BitSet; import game.rules.play.moves.Moves; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Makes a bet for a player. * * @author Eric.Piette */ public final class ActionBet extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The player who bet. */ private final int player; /** The bet. */ private final int bet; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous amount. */ private int previousBet; //------------------------------------------------------------------------- /** * @param player The index of the player. * @param bet The bet. */ public ActionBet ( final int player, final int bet ) { this.player = player; this.bet = bet; } /** * Reconstructs an ActionBet object from a detailed String (generated using * toDetailedString()) * * @param detailedString */ public ActionBet(final String detailedString) { assert (detailedString.startsWith("[Bet:")); final String strPlayer = Action.extractData(detailedString, "player"); player = Integer.parseInt(strPlayer); final String strBet = Action.extractData(detailedString, "bet"); bet = Integer.parseInt(strBet); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if(!alreadyApplied) { previousBet = context.state().amount(player); alreadyApplied = true; } context.state().setAmount(player, bet); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().setAmount(player, previousBet); return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + player; result = prime * result + bet; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionBet)) return false; final ActionBet other = (ActionBet) obj; return (decision == other.decision && bet == other.bet && player == other.player); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[Bet:"); sb.append("player=" + player); sb.append(",bet=" + bet); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Bet"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "Bet P" + player + " $" + bet; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(P" + player + " Bet = " + bet + ")"; } //------------------------------------------------------------------------- @Override public boolean isOtherMove() { return true; } @Override public int who() { return player; } @Override public int count() { return bet; } @Override public ActionType actionType() { return ActionType.Bet; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); if (decision) concepts.set(Concept.BetDecision.id(), true); else concepts.set(Concept.BetEffect.id(), true); return concepts; } }
4,371
20.751244
123
java
Ludii
Ludii-master/Core/src/other/action/state/ActionForgetValue.java
package other.action.state; import java.util.BitSet; import game.rules.play.moves.Moves; import main.collections.FastTIntArrayList; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Forgets a value remembered before. * * @author Eric.Piette */ public class ActionForgetValue extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The value to forget. */ private final int value; /** The name of the remembering values. */ private final String name; /** * @param name The name of the remembering values. * @param value The value to forget. */ public ActionForgetValue(final String name, final int value) { this.name = name; this.value = value; } /** * Reconstructs an ActionForgetValue object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionForgetValue(final String detailedString) { assert (detailedString.startsWith("[ForgetValue:")); final String strName = Action.extractData(detailedString, "name"); name = strName; final String strValue = Action.extractData(detailedString, "value"); value = Integer.parseInt(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if (name == null) { context.state().rememberingValues().remove(value); } else { final FastTIntArrayList rememberingValues = context.state().mapRememberingValues().get(name); if (rememberingValues != null) { rememberingValues.remove(value); if (rememberingValues.isEmpty()) context.state().mapRememberingValues().remove(name); } } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { if (name == null) { context.state().rememberingValues().insert(0,value); } else { FastTIntArrayList rememberingValues = context.state().mapRememberingValues().get(name); if (rememberingValues == null) { rememberingValues = new FastTIntArrayList(); context.state().mapRememberingValues().put(name, rememberingValues); } rememberingValues.insert(0,value); } return this; } @Override public ActionType actionType() { return ActionType.Forget; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[ForgetValue:"); sb.append("name=" + name); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + value; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionForgetValue)) return false; final ActionForgetValue other = (ActionForgetValue) obj; if (name != null && other.name != null) if (!name.equals(other.name)) return false; return (decision == other.decision && value == other.value); } //------------------------------------------------------------------------- @Override public String getDescription() { return "ForgetValue"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "RememberedValues-=" + value; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Forget Value " + ((name != null) ? "'" + name + "' " : "") + value + ")"; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.ForgetValues.id(), true); return concepts; } }
4,341
22.219251
96
java
Ludii
Ludii-master/Core/src/other/action/state/ActionRememberValue.java
package other.action.state; import java.util.BitSet; import game.rules.play.moves.Moves; import main.collections.FastTIntArrayList; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; /** * Remember a value. * * @author Eric.Piette */ public class ActionRememberValue extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The value to remember. */ private final int value; /** The name of the remembering values. */ private final String name; /** * @param name The name of the remembering values. * @param value The value to forget. */ public ActionRememberValue(final String name, final int value) { this.name = name; this.value = value; } /** * Reconstructs an ActionForgetValue object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionRememberValue(final String detailedString) { assert (detailedString.startsWith("[RememberValue:")); final String strName = Action.extractData(detailedString, "name"); name = strName; final String strValue = Action.extractData(detailedString, "value"); value = Integer.parseInt(strValue); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if (name == null) { context.state().rememberingValues().add(value); } else { FastTIntArrayList rememberingValues = context.state().mapRememberingValues().get(name); if (rememberingValues == null) { rememberingValues = new FastTIntArrayList(); context.state().mapRememberingValues().put(name, rememberingValues); } rememberingValues.add(value); } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { if (name == null) { context.state().rememberingValues().remove(value); } else { FastTIntArrayList rememberingValues = context.state().mapRememberingValues().get(name); if (rememberingValues != null) { rememberingValues.remove(value); if (rememberingValues.isEmpty()) context.state().mapRememberingValues().remove(name); } } return this; } @Override public ActionType actionType() { return ActionType.Remember; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[RememberValue:"); sb.append("name=" + name); sb.append(",value=" + value); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + value; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionRememberValue)) return false; final ActionRememberValue other = (ActionRememberValue) obj; if (name != null && other.name != null) if (!name.equals(other.name)) return false; return (decision == other.decision && value == other.value); } //------------------------------------------------------------------------- @Override public String getDescription() { return "RememberValue"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "RememberedValues+=" + value; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Remember Value " + ((name != null) ? "'" + name + "' " : "") + value + ")"; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.RememberValues.id(), true); return concepts; } }
4,336
22.069149
90
java
Ludii
Ludii-master/Core/src/other/action/state/ActionSetAmount.java
package other.action.state; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.context.Context; /** * Sets the amount of a player. * * @author Eric.Piette */ public final class ActionSetAmount extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** The player index. */ private final int player; /** The new amount. */ private final int amount; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous amount. */ private int previousAmount; //------------------------------------------------------------------------- /** * @param player The index of the player. * @param amount The amount. */ public ActionSetAmount ( final int player, final int amount ) { this.player = player; this.amount = amount; } /** * Reconstructs an ActionSetAmount object from a detailed String (generated * using toDetailedString()) * * @param detailedString */ public ActionSetAmount(final String detailedString) { assert (detailedString.startsWith("[SetAmount:")); final String strPlayer = Action.extractData(detailedString, "player"); player = Integer.parseInt(strPlayer); final String strAmount = Action.extractData(detailedString, "amount"); amount = Integer.parseInt(strAmount); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { if(!alreadyApplied) { previousAmount = context.state().amount(player); alreadyApplied = true; } context.state().setAmount(player, amount); return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { context.state().setAmount(player, previousAmount); return this; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (decision ? 1231 : 1237); result = prime * result + player; result = prime * result + amount; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetAmount)) return false; final ActionSetAmount other = (ActionSetAmount) obj; return (decision == other.decision && amount == other.amount && player == other.player); } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetAmount:"); sb.append("player=" + player); sb.append(",amount=" + amount); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } //------------------------------------------------------------------------- @Override public String getDescription() { return "Amount"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { return "P" + player + "=$" + amount; } @Override public String toMoveFormat(final Context context, final boolean useCoords) { return "(Amount P" + player + " = " + amount + ")"; } @Override public int who() { return player; } @Override public ActionType actionType() { return ActionType.SetAmount; } }
3,870
21.905325
123
java
Ludii
Ludii-master/Core/src/other/action/state/ActionSetCount.java
package other.action.state; import java.util.BitSet; import game.equipment.component.Component; import game.equipment.container.board.Track; import game.rules.play.moves.Moves; import game.types.board.SiteType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.action.Action; import other.action.ActionType; import other.action.BaseAction; import other.concept.Concept; import other.context.Context; import other.state.container.ContainerState; import other.state.track.OnTrackIndices; /** * Sets the count of a site. * * @author Eric.Piette */ public class ActionSetCount extends BaseAction { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** What index. */ private final int what; /** Site index. */ private final int to; /** Count. */ private final int count; /** The Graph element type. */ private SiteType type; //------------------------------------------------------------------------- /** A variable to know that we already applied this action so we do not want to modify the data to undo if apply again. */ private boolean alreadyApplied = false; /** The previous count. */ private int previousCount; /** The previous site type. */ private SiteType previousType; //------------------------------------------------------------------------- /** * @param type The graph element type. * @param to Site to modify the count. * @param what The index of the component. * @param count the number of item to place */ public ActionSetCount ( final SiteType type, final int to, final int what, final int count ) { this.to = to; this.count = count; this.type = type; this.what = what; } /** * Reconstructs an ActionSetCount object from a detailed String * (generated using toDetailedString()) * @param detailedString */ public ActionSetCount(final String detailedString) { assert (detailedString.startsWith("[SetCount:")); final String strType = Action.extractData(detailedString, "type"); type = (strType.isEmpty()) ? null : SiteType.valueOf(strType); final String strTo = Action.extractData(detailedString, "to"); to = Integer.parseInt(strTo); final String strWhat = Action.extractData(detailedString, "what"); what = Integer.parseInt(strWhat); final String strCount = Action.extractData(detailedString, "count"); count = Integer.parseInt(strCount); final String strDecision = Action.extractData(detailedString, "decision"); decision = (strDecision.isEmpty()) ? false : Boolean.parseBoolean(strDecision); } //------------------------------------------------------------------------- @Override public Action apply(final Context context, final boolean store) { type = (type == null) ? context.board().defaultSite() : type; // If the site is not supported by the type, that's a cell of another container. if (to >= context.board().topology().getGraphElements(type).size()) type = SiteType.Cell; final int contID = (type == SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contID]; if (what != 0 && cs.count(to, type) == 0 && count > 0) { final Component piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, type); } if(!alreadyApplied) { previousCount = cs.count(to, type); previousType = type; alreadyApplied = true; } if (count > 0) { cs.setSite(context.state(), to, Constants.UNDEFINED, what, count, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, type); } else { final int pieceIdx = cs.remove(context.state(), to, type); if (pieceIdx > 0) // a piece was removed. { final Component piece = context.components()[pieceIdx]; final int owner = piece.owner(); context.state().owned().remove(owner, pieceIdx, to, type); // We update the structure about track indices if the game uses track. final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); if (onTrackIndices != null) { for (final Track track : context.board().tracks()) { final int trackIdx = track.trackIdx(); final TIntArrayList indices = onTrackIndices.locToIndex(trackIdx, to); for (int i = 0; i < indices.size(); i++) onTrackIndices.remove(trackIdx, pieceIdx, 1, indices.getQuick(i)); } } } } return this; } //------------------------------------------------------------------------- @Override public Action undo(final Context context, boolean discard) { final int contID = (previousType == SiteType.Cell) ? context.containerId()[to] : 0; final ContainerState cs = context.state().containerStates()[contID]; if (what != 0 && cs.count(to, type) == 0 && previousCount > 0) { final Component piece = context.components()[what]; final int owner = piece.owner(); context.state().owned().add(owner, what, to, previousType); } if (previousCount > 0) { cs.setSite(context.state(), to, Constants.UNDEFINED, what, previousCount, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, previousType); } else { final int pieceIdx = cs.remove(context.state(), to, previousType); if (pieceIdx > 0) // a piece was removed. { final Component piece = context.components()[pieceIdx]; final int owner = piece.owner(); context.state().owned().remove(owner, pieceIdx, to, previousType); // We update the structure about track indices if the game uses track. final OnTrackIndices onTrackIndices = context.state().onTrackIndices(); if (onTrackIndices != null) { for (final Track track : context.board().tracks()) { final int trackIdx = track.trackIdx(); final TIntArrayList indices = onTrackIndices.locToIndex(trackIdx, to); for (int i = 0; i < indices.size(); i++) onTrackIndices.remove(trackIdx, pieceIdx, 1, indices.getQuick(i)); } } } } return this; } //------------------------------------------------------------------------- @Override public String toTrialFormat(final Context context) { final StringBuilder sb = new StringBuilder(); sb.append("[SetCount:"); if (type != null || (context != null && type != context.board().defaultSite())) { sb.append("type=" + type); sb.append(",to=" + to); } else sb.append("to=" + to); sb.append(",what=" + what); sb.append(",count=" + count); if (decision) sb.append(",decision=" + decision); sb.append(']'); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + count; result = prime * result + (decision ? 1231 : 1237); result = prime * result + to; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ActionSetCount)) return false; final ActionSetCount other = (ActionSetCount) obj; return (decision == other.decision && to == other.to && count == other.count && type == other.type); } //------------------------------------------------------------------------- @Override public String getDescription() { return "SetCount"; } @Override public String toTurnFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(type + " " + newTo); else sb.append(newTo); sb.append("+"); if (what > 0 && what < context.components().length) { sb.append(context.components()[what].name()); if (count > 1) sb.append("x" + count); } return sb.toString(); } @Override public String toMoveFormat(final Context context, final boolean useCoords) { final StringBuilder sb = new StringBuilder(); sb.append("(Add "); if (what > 0 && what < context.components().length) { sb.append(context.components()[what].name()); if (count > 1) sb.append("x" + count); } String newTo = to + ""; if (useCoords) { final int cid = (type == SiteType.Cell || type == null && context.board().defaultSite() == SiteType.Cell) ? context.containerId()[to] : 0; if (cid == 0) { final SiteType realType = (type != null) ? type : context.board().defaultSite(); newTo = context.game().equipment().containers()[cid].topology().getGraphElements(realType).get(to) .label(); } } if (type != null && !type.equals(context.board().defaultSite())) sb.append(" to " + type + " " + newTo); else sb.append(" to " + newTo); sb.append(')'); return sb.toString(); } //------------------------------------------------------------------------- @Override public SiteType fromType() { return type; } @Override public SiteType toType() { return type; } @Override public int from() { return to; } @Override public int to() { return to; } @Override public int what() { return what; } @Override public int count() { return count; } @Override public ActionType actionType() { return ActionType.SetCount; } //------------------------------------------------------------------------- @Override public BitSet concepts(final Context context, final Moves movesLudeme) { final BitSet concepts = new BitSet(); concepts.set(Concept.SetCount.id(), true); return concepts; } }
10,027
24.07
123
java