Miscallaneous Cleanup Part 2 - Lambdas and Method References (#5737)

* Cleanup - Unnecessary Boxing

* Cleanup - Unnecessary Unboxing

* Cleanup - For-Each Loops

* Cleanup - `indexOf != -1` -> `contains`

* Cleanup - Merge identical catch blocks

* Cleanup - Try-with-resources

* Cleanup - System.lineSeparator

* Cleanup - Reference types to primitives
Some loops over Integers were switched to IntStreams to hopefully cut down on overall boxing.

* Cleanup - Manually filling and copying arrays

* Remove unused imports

* Switch a lambda to a method reference

* Cleanup - CardPredicate Aggregates to method references

* Cleanup - Other static functions to method references

* Cleanup - Ambiguous class reference
Unclear when or how this happened...

* Cleanup - Anonymous -> Method reference

* Cleanup - Anonymous -> Lambda

* Cleanup - Comparator helper methods

* Cleanup - final method in final class

* Cleanup - private final methods

* Remove unused imports

* Convert a couple more lambdas to comparators.

* Simplify creature type list comparison.

---------

Co-authored-by: Jetz <Jetz722@gmail.com>
Co-authored-by: tool4ever <therealtoolkit@hotmail.com>
This commit is contained in:
Jetz72
2024-08-02 01:23:58 -04:00
committed by GitHub
parent 86ac0349ca
commit d62dfe1c8c
490 changed files with 6692 additions and 13091 deletions

View File

@@ -74,7 +74,7 @@ public final class CardRelationMatrixGenerator {
true);
final Iterable<PaperCard> cards = Iterables.filter(format.getAllCards()
, Predicates.compose(Predicates.not(CardRulesPredicates.Presets.IS_BASIC_LAND_NOT_WASTES), PaperCard.FN_GET_RULES));
, Predicates.compose(Predicates.not(CardRulesPredicates.Presets.IS_BASIC_LAND_NOT_WASTES), PaperCard::getRules));
List<PaperCard> cardList = Lists.newArrayList(cards);
cardList.add(FModel.getMagicDb().getCommonCards().getCard("Wastes"));
Map<String, Integer> cardIntegerMap = new HashMap<>();
@@ -90,7 +90,7 @@ public final class CardRelationMatrixGenerator {
for (Deck deck:decks){
if (deck.getMain().contains(card)){
for (PaperCard pairCard:Iterables.filter(deck.getMain().toFlatList(),
Predicates.compose(Predicates.not(CardRulesPredicates.Presets.IS_BASIC_LAND_NOT_WASTES), PaperCard.FN_GET_RULES))){
Predicates.compose(Predicates.not(CardRulesPredicates.Presets.IS_BASIC_LAND_NOT_WASTES), PaperCard::getRules))){
if (!pairCard.getName().equals(card.getName())){
try {
int old = matrix[cardIntegerMap.get(card.getName())][cardIntegerMap.get(pairCard.getName())];
@@ -143,7 +143,7 @@ public final class CardRelationMatrixGenerator {
//get all cards
final Iterable<PaperCard> cards = Iterables.filter(FModel.getMagicDb().getCommonCards().getUniqueCards()
, Predicates.compose(Predicates.not(CardRulesPredicates.Presets.IS_BASIC_LAND_NOT_WASTES), PaperCard.FN_GET_RULES));
, Predicates.compose(Predicates.not(CardRulesPredicates.Presets.IS_BASIC_LAND_NOT_WASTES), PaperCard::getRules));
List<PaperCard> cardList = Lists.newArrayList(cards);
cardList.add(FModel.getMagicDb().getCommonCards().getCard("Wastes"));
Map<String, Integer> cardIntegerMap = new HashMap<>();
@@ -200,7 +200,7 @@ public final class CardRelationMatrixGenerator {
public static void updateLegendMatrix(Deck deck, PaperCard legend, Map<String, Integer> cardIntegerMap,
Map<String, Integer> legendIntegerMap, int[][] matrix){
for (PaperCard pairCard:Iterables.filter(deck.getMain().toFlatList(),
Predicates.compose(Predicates.not(CardRulesPredicates.Presets.IS_BASIC_LAND_NOT_WASTES), PaperCard.FN_GET_RULES))){
Predicates.compose(Predicates.not(CardRulesPredicates.Presets.IS_BASIC_LAND_NOT_WASTES), PaperCard::getRules))){
if (!pairCard.getName().equals(legend.getName())){
try {
int old = matrix[legendIntegerMap.get(legend.getName())][cardIntegerMap.get(pairCard.getName())];

View File

@@ -42,7 +42,7 @@ public class CommanderDeckGenerator extends DeckProxy implements Comparable<Comm
Predicate<CardRules> canPlay = isForAi ? DeckGeneratorBase.AI_CAN_PLAY : CardRulesPredicates.IS_KEPT_IN_RANDOM_DECKS;
@SuppressWarnings("unchecked")
Iterable<PaperCard> legends = Iterables.filter(uniqueCards.toFlatList(), Predicates.and(format.isLegalCommanderPredicate(), Predicates.compose(
canPlay, PaperCard.FN_GET_RULES)));
canPlay, PaperCard::getRules)));
final List<DeckProxy> decks = new ArrayList<>();
for (PaperCard legend: legends) {
decks.add(new CommanderDeckGenerator(legend, format, isForAi, isCardGen));
@@ -68,7 +68,7 @@ public class CommanderDeckGenerator extends DeckProxy implements Comparable<Comm
Iterable<PaperCard> legends = Iterables.filter(uniqueCards.toFlatList(), Predicates.and(format.isLegalCardPredicate(),
Predicates.compose(Predicates.and(
CardRulesPredicates.Presets.CAN_BE_BRAWL_COMMANDER,
canPlay), PaperCard.FN_GET_RULES)));
canPlay), PaperCard::getRules)));
final List<DeckProxy> decks = new ArrayList<>();
for (PaperCard legend: legends) {
decks.add(new CommanderDeckGenerator(legend, format, isForAi, isCardGen));

View File

@@ -1,6 +1,5 @@
package forge.deck;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
@@ -28,6 +27,7 @@ import org.apache.commons.lang3.tuple.Pair;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
// Adding a generic to this class creates compile problems in ItemManager (that I can not fix)
public class DeckProxy implements InventoryItem {
@@ -364,7 +364,7 @@ public class DeckProxy implements InventoryItem {
public String getFormatsString() {
Set<GameFormat> formats = getFormats();
if (formats.size() > 1)
return StringUtils.join(Iterables.transform(formats, GameFormat.FN_GET_NAME), ", ");
return StringUtils.join(Iterables.transform(formats, GameFormat::getName), ", ");
Object[] formatArray = formats.toArray();
GameFormat format = (GameFormat)formatArray[0];
if (format != GameFormat.NoFormat)
@@ -610,7 +610,7 @@ public class DeckProxy implements InventoryItem {
public static List<DeckProxy> getAllPreconstructedDecks(final IStorage<PreconDeck> iStorage) {
final List<DeckProxy> decks = new ArrayList<>();
for (final PreconDeck preconDeck : iStorage) {
decks.add(new DeckProxy(preconDeck, "Precon", (Function<IHasName, Deck>)(Object)PreconDeck.FN_GET_DECK, null, iStorage));
decks.add(new DeckProxy(preconDeck, "Precon", (Function<IHasName, Deck>)(Object) (Function<PreconDeck, Deck>) PreconDeck::getDeck, null, iStorage));
}
return decks;
}
@@ -674,8 +674,8 @@ public class DeckProxy implements InventoryItem {
// Since AI decks are tied directly to the human choice,
// they're just mapped in a parallel map and grabbed when the game starts.
for (final DeckGroup d : sealed) {
humanDecks.add(new DeckProxy(d, "Sealed", (Function<IHasName, Deck>)(Object)DeckGroup.FN_HUMAN_DECK, GameType.Sealed, sealed));
for (final DeckGroup d : sealed) { //TODO: Simplify the method references used by this constructor.
humanDecks.add(new DeckProxy(d, "Sealed", (Function<IHasName, Deck>)(Object) (Function<DeckGroup, Deck>) DeckGroup::getHumanDeck, GameType.Sealed, sealed));
}
return humanDecks;
}
@@ -695,7 +695,7 @@ public class DeckProxy implements InventoryItem {
final List<DeckProxy> decks = new ArrayList<>();
final IStorage<DeckGroup> draft = FModel.getDecks().getDraft();
for (final DeckGroup d : draft) {
decks.add(new DeckProxy(d, "Draft", ((Function<IHasName, Deck>)(Object)DeckGroup.FN_HUMAN_DECK), GameType.Draft, draft));
decks.add(new DeckProxy(d, "Draft", ((Function<IHasName, Deck>)(Object) (Function<DeckGroup, Deck>) DeckGroup::getHumanDeck), GameType.Draft, draft));
}
return decks;
}
@@ -704,7 +704,7 @@ public class DeckProxy implements InventoryItem {
public static List<DeckProxy> getWinstonDecks(final IStorage<DeckGroup> draft) {
final List<DeckProxy> decks = new ArrayList<>();
for (final DeckGroup d : draft) {
decks.add(new DeckProxy(d, "Winston", ((Function<IHasName, Deck>)(Object)DeckGroup.FN_HUMAN_DECK), GameType.Winston, draft));
decks.add(new DeckProxy(d, "Winston", ((Function<IHasName, Deck>)(Object) (Function<DeckGroup, Deck>) DeckGroup::getHumanDeck), GameType.Winston, draft));
}
return decks;
}

View File

@@ -218,8 +218,8 @@ public class DeckgenUtil {
System.out.println("Wrong card count "+deck.getMain().countAll());
deck=buildLDACArchetypeDeck(format,isForAI);
}
if(deck.getMain().countAll(Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard.FN_GET_RULES))>27){
System.out.println("Too many lands "+deck.getMain().countAll(Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard.FN_GET_RULES)));
if(deck.getMain().countAll(Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard::getRules))>27){
System.out.println("Too many lands "+deck.getMain().countAll(Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard::getRules)));
deck=buildLDACArchetypeDeck(format,isForAI);
}
while(deck.get(DeckSection.Sideboard).countAll()>15){
@@ -317,8 +317,8 @@ public class DeckgenUtil {
System.out.println("Wrong card count "+deck.getMain().countAll());
deck=buildLDACArchetypeDeck(format,isForAI);
}
if(deck.getMain().countAll(Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard.FN_GET_RULES))>27){
System.out.println("Too many lands "+deck.getMain().countAll(Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard.FN_GET_RULES)));
if(deck.getMain().countAll(Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard::getRules))>27){
System.out.println("Too many lands "+deck.getMain().countAll(Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard::getRules)));
deck=buildLDACArchetypeDeck(format,isForAI);
}
while(deck.get(DeckSection.Sideboard).countAll()>15){
@@ -392,9 +392,7 @@ public class DeckgenUtil {
}
}
QuestEventDuel duel = Iterables.find(qCtrl.getDuelsManager().getAllDuels(), new Predicate<QuestEventDuel>() {
@Override public boolean apply(QuestEventDuel in) { return in.getName().equals(name); }
});
QuestEventDuel duel = Iterables.find(qCtrl.getDuelsManager().getAllDuels(), in -> in.getName().equals(name));
return duel;
}
@@ -671,7 +669,7 @@ public class DeckgenUtil {
Predicate<CardRules> canPlay = forAi ? DeckGeneratorBase.AI_CAN_PLAY : CardRulesPredicates.IS_KEPT_IN_RANDOM_DECKS;
@SuppressWarnings("unchecked")
Iterable<PaperCard> legends = cardDb.getAllCards(Predicates.and(format.isLegalCardPredicate(), format.isLegalCommanderPredicate(),
Predicates.compose(canPlay, PaperCard.FN_GET_RULES)));
Predicates.compose(canPlay, PaperCard::getRules)));
commander = Aggregates.random(legends);
return generateRandomCommanderDeck(commander, format, forAi, false);
@@ -767,7 +765,7 @@ public class DeckgenUtil {
Iterable<PaperCard> colorList = Iterables.filter(format.getCardPool(cardDb).getAllCards(),
Predicates.and(format.isLegalCardPredicate(),Predicates.compose(Predicates.or(
new CardThemedDeckBuilder.MatchColorIdentity(commander.getRules().getColorIdentity()),
DeckGeneratorBase.COLORLESS_CARDS), PaperCard.FN_GET_RULES)));
DeckGeneratorBase.COLORLESS_CARDS), PaperCard::getRules)));
switch (format) {
case Brawl: //for Brawl - add additional filterprinted rule to remove old reprints for a consistent look
colorList = Iterables.filter(colorList,FModel.getFormats().getStandard().getFilterPrinted());
@@ -845,7 +843,7 @@ public class DeckgenUtil {
// determine how many additional lands we need, but don't take lands already in deck into consideration,
// or we risk incorrectly determining the target deck size
int numLands = Iterables.size(Iterables.filter(cards, Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard.FN_GET_RULES)));
int numLands = Iterables.size(Iterables.filter(cards, Predicates.compose(CardRulesPredicates.Presets.IS_LAND, PaperCard::getRules)));
int sizeNoLands = cards.size() - numLands;
// attempt to determine if building for sealed, constructed or EDH

View File

@@ -3,7 +3,6 @@ package forge.deck;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import forge.game.GameFormat;
@@ -203,12 +202,7 @@ public class RandomDeckGenerator extends DeckProxy implements Comparable<RandomD
decks = DeckProxy.getAllConstructedDecks();
break;
}
decks = Iterables.filter(decks, new Predicate<DeckProxy>() {
@Override
public boolean apply(final DeckProxy deck) {
return deck.isFavoriteDeck();
}
});
decks = Iterables.filter(decks, DeckProxy::isFavoriteDeck);
if (Iterables.isEmpty(decks)) {
return getGeneratedDeck(); //fall back to generated deck if no favorite decks
}

View File

@@ -83,24 +83,14 @@ public class GauntletIO {
}
public static File[] getGauntletFilesUnlocked(final String prefix) {
final FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return ((prefix == null || name.startsWith(prefix)) && name.endsWith(SUFFIX_DATA));
}
};
final FilenameFilter filter = (dir, name) -> ((prefix == null || name.startsWith(prefix)) && name.endsWith(SUFFIX_DATA));
final File folder = new File(ForgeConstants.GAUNTLET_DIR.userPrefLoc);
return folder.listFiles(filter);
}
public static File[] getGauntletFilesLocked() {
final FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return (name.startsWith(PREFIX_LOCKED) && name.endsWith(SUFFIX_DATA));
}
};
final FilenameFilter filter = (dir, name) -> (name.startsWith(PREFIX_LOCKED) && name.endsWith(SUFFIX_DATA));
final File folder = new File(ForgeConstants.GAUNTLET_DIR.defaultLoc);
return folder.listFiles(filter);

View File

@@ -24,6 +24,7 @@ import forge.StaticData;
import forge.card.CardEdition;
import forge.deck.CardPool;
import forge.deck.Deck;
import forge.deck.DeckBase;
import forge.gui.util.SGuiChoose;
import forge.gui.util.SOptionPane;
import forge.item.PaperCard;
@@ -172,12 +173,7 @@ public class BoosterDraft implements IBoosterDraft {
if (myDrafts.isEmpty()) {
SOptionPane.showMessageDialog(Localizer.getInstance().getMessage("lblNotFoundCustomDraftFiles"));
} else {
Collections.sort(myDrafts, new Comparator<CustomLimited>() {
@Override
public int compare(CustomLimited o1, CustomLimited o2) {
return o1.getName().compareTo(o2.getName());
}
});
Collections.sort(myDrafts, Comparator.comparing(DeckBase::getName));
final CustomLimited customDraft = SGuiChoose.oneOrNone(Localizer.getInstance().getMessage("lblChooseCustomDraft"), myDrafts);
if (customDraft == null) {

View File

@@ -26,7 +26,7 @@ public class CardThemedCommanderDeckBuilder extends CardThemedDeckBuilder {
// remove Unplayables
if(isForAI) {
final Iterable<PaperCard> playables = Iterables.filter(availableList,
Predicates.compose(CardRulesPredicates.IS_KEPT_IN_AI_DECKS, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.IS_KEPT_IN_AI_DECKS, PaperCard::getRules));
this.aiPlayables = Lists.newArrayList(playables);
}else{
this.aiPlayables = Lists.newArrayList(availableList);

View File

@@ -30,7 +30,7 @@ public class CardThemedConquestDeckBuilder extends CardThemedDeckBuilder {
// remove Unplayables
if(isForAI) {
final Iterable<PaperCard> playables = Iterables.filter(availableList,
Predicates.compose(CardRulesPredicates.IS_KEPT_IN_AI_DECKS, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.IS_KEPT_IN_AI_DECKS, PaperCard::getRules));
this.aiPlayables = Lists.newArrayList(playables);
}else{
this.aiPlayables = Lists.newArrayList(availableList);

View File

@@ -105,7 +105,7 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
// remove Unplayables
if(isForAI) {
final Iterable<PaperCard> playables = Iterables.filter(availableList,
Predicates.compose(CardRulesPredicates.IS_KEPT_IN_AI_DECKS, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.IS_KEPT_IN_AI_DECKS, PaperCard::getRules));
this.aiPlayables = Lists.newArrayList(playables);
}else{
this.aiPlayables = Lists.newArrayList(availableList);
@@ -189,11 +189,11 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
System.out.println("Colors: " + colors.toEnumSet().toString());
}
Iterable<PaperCard> colorList = Iterables.filter(aiPlayables,
Predicates.compose(hasColor, PaperCard.FN_GET_RULES));
Predicates.compose(hasColor, PaperCard::getRules));
rankedColorList = Lists.newArrayList(colorList);
onColorCreaturesAndSpells = Iterables.filter(rankedColorList,
Predicates.compose(Predicates.or(CardRulesPredicates.Presets.IS_CREATURE,
CardRulesPredicates.Presets.IS_NON_CREATURE_SPELL), PaperCard.FN_GET_RULES));
CardRulesPredicates.Presets.IS_NON_CREATURE_SPELL), PaperCard::getRules));
// Guava iterables do not copy the collection contents, instead they act
// as filters and iterate over _source_ collection each time. So even if
@@ -319,8 +319,8 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
//Add remaining non-land colour matching cards to sideboard
final CardPool cp = result.getOrCreate(DeckSection.Sideboard);
Iterable<PaperCard> potentialSideboard = Iterables.filter(aiPlayables,
Predicates.and(Predicates.compose(hasColor, PaperCard.FN_GET_RULES),
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard.FN_GET_RULES)));
Predicates.and(Predicates.compose(hasColor, PaperCard::getRules),
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard::getRules)));
int i=0;
while(i<15 && potentialSideboard.iterator().hasNext()){
PaperCard sbCard = potentialSideboard.iterator().next();
@@ -462,7 +462,7 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
protected void addThirdColorCards(int num) {
if (num > 0) {
final Iterable<PaperCard> others = Iterables.filter(aiPlayables,
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard::getRules));
// We haven't yet ranked the off-color cards.
// Compare them to the cards already in the deckList.
//List<PaperCard> rankedOthers = CardRanker.rankCardsInPack(others, deckList, colors, true);
@@ -479,7 +479,7 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
hasColor = Predicates.and(CardRulesPredicates.Presets.IS_NON_LAND,Predicates.or(new MatchColorIdentity(colors),
DeckGeneratorBase.COLORLESS_CARDS));
final Iterable<PaperCard> threeColorList = Iterables.filter(aiPlayables,
Predicates.compose(hasColor, PaperCard.FN_GET_RULES));
Predicates.compose(hasColor, PaperCard::getRules));
for (final PaperCard card : threeColorList) {
if (num > 0) {
toAdd.add(card);
@@ -499,7 +499,7 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
protected void addLowCMCCard(){
final Iterable<PaperCard> nonLands = Iterables.filter(rankedColorList,
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard::getRules));
final PaperCard card = Iterables.getFirst(nonLands, null);
if (card != null) {
deckList.add(card);
@@ -522,9 +522,9 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
Predicate<PaperCard> isSetBasicLand;
if (edition !=null){
isSetBasicLand = Predicates.and(IPaperCard.Predicates.printedInSet(edition),
Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard::getRules));
}else{
isSetBasicLand = Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard.FN_GET_RULES);
isSetBasicLand = Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard::getRules);
}
landPool = new DeckGenPool(format.getCardPool(fullCardDB).getAllCards(isSetBasicLand));
@@ -667,7 +667,7 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
*/
private void addLands(final int[] clrCnts) {
// basic lands that are available in the deck
final Iterable<PaperCard> basicLands = Iterables.filter(aiPlayables, Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard.FN_GET_RULES));
final Iterable<PaperCard> basicLands = Iterables.filter(aiPlayables, Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard::getRules));
// total of all ClrCnts
int totalColor = 0;
@@ -809,7 +809,7 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
*/
private void addNonBasicLands() {
Iterable<PaperCard> lands = Iterables.filter(aiPlayables,
Predicates.compose(CardRulesPredicates.Presets.IS_NONBASIC_LAND, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_NONBASIC_LAND, PaperCard::getRules));
List<PaperCard> landsToAdd = new ArrayList<>();
int minBasics;//Keep a minimum number of basics to ensure playable decks
if(colors.isColorless()) {
@@ -823,7 +823,7 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
}
lands = Iterables.filter(aiPlayables,
Predicates.compose(CardRulesPredicates.Presets.IS_NONBASIC_LAND, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_NONBASIC_LAND, PaperCard::getRules));
for (final PaperCard card : lands) {
if (landsNeeded > minBasics) {
@@ -849,17 +849,13 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
*/
private void addRandomCards(int num) {
final Set<String> deckListNames = getDeckListNames();
Predicate<PaperCard> possibleFromFullPool = new Predicate<PaperCard>() {
@Override
public boolean apply(PaperCard card) {
return format.isLegalCard(card)
&& card.getRules().getColorIdentity().hasNoColorsExcept(colors)
&& !deckListNames.contains(card.getName())
&&!card.getRules().getAiHints().getRemAIDecks()
&&!card.getRules().getAiHints().getRemRandomDecks()
&&!card.getRules().getMainPart().getType().isLand();
}
};
Predicate<PaperCard> possibleFromFullPool = card -> format.isLegalCard(card)
&& card.getRules().getColorIdentity().hasNoColorsExcept(colors)
&& !deckListNames.contains(card.getName())
&& !card.getRules().getAiHints().getRemAIDecks()
&& !card.getRules().getAiHints().getRemRandomDecks()
&& !card.getRules().getMainPart().getType().isLand();
List<PaperCard> possibleList = Lists.newArrayList(pool.getAllCards(possibleFromFullPool));
//ensure we do not add more keycards in case they are commanders
if (keyCard != null) {
@@ -928,7 +924,7 @@ public class CardThemedDeckBuilder extends DeckGeneratorBase {
creatureCosts.put(i, 0);
}
final Predicate<PaperCard> filter = Predicates.compose(CardRulesPredicates.Presets.IS_CREATURE,
PaperCard.FN_GET_RULES);
PaperCard::getRules);
for (final IPaperCard creature : Iterables.filter(deckList, filter)) {
int cmc = creature.getRules().getManaCost().getCMC();
if (cmc < 1) {

View File

@@ -83,13 +83,13 @@ public class LimitedDeckBuilder extends DeckGeneratorBase {
// remove Unplayables
final Iterable<PaperCard> playables = Iterables.filter(availableList,
Predicates.compose(CardRulesPredicates.IS_KEPT_IN_AI_LIMITED_DECKS, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.IS_KEPT_IN_AI_LIMITED_DECKS, PaperCard::getRules));
this.aiPlayables = Lists.newArrayList(playables);
this.availableList.removeAll(aiPlayables);
// keep Conspiracies in a separate list
final Iterable<PaperCard> conspiracies = Iterables.filter(aiPlayables,
Predicates.compose(CardRulesPredicates.coreType(true, "Conspiracy"), PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.coreType(true, "Conspiracy"), PaperCard::getRules));
this.draftedConspiracies = Lists.newArrayList(conspiracies);
this.aiPlayables.removeAll(draftedConspiracies);
@@ -136,19 +136,19 @@ public class LimitedDeckBuilder extends DeckGeneratorBase {
// 1. Prepare
hasColor = Predicates.or(new MatchColorIdentity(colors), COLORLESS_CARDS);
Iterable<PaperCard> colorList = Iterables.filter(aiPlayables,
Predicates.compose(hasColor, PaperCard.FN_GET_RULES));
Predicates.compose(hasColor, PaperCard::getRules));
rankedColorList = CardRanker.rankCardsInDeck(colorList);
onColorCreatures = Iterables.filter(rankedColorList,
Predicates.compose(CardRulesPredicates.Presets.IS_CREATURE, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_CREATURE, PaperCard::getRules));
onColorNonCreatures = Iterables.filter(rankedColorList,
Predicates.compose(CardRulesPredicates.Presets.IS_NON_CREATURE_SPELL, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_NON_CREATURE_SPELL, PaperCard::getRules));
// Guava iterables do not copy the collection contents, instead they act
// as filters and iterate over _source_ collection each time. So even if
// aiPlayable has changed, there is no need to create a new iterable.
// 2. Add any planeswalkers
final Iterable<PaperCard> onColorWalkers = Iterables.filter(colorList,
Predicates.compose(CardRulesPredicates.Presets.IS_PLANESWALKER, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_PLANESWALKER, PaperCard::getRules));
final List<PaperCard> walkers = Lists.newArrayList(onColorWalkers);
deckList.addAll(walkers);
aiPlayables.removeAll(walkers);
@@ -171,7 +171,7 @@ public class LimitedDeckBuilder extends DeckGeneratorBase {
// an extra.
if (deckList.size() == numSpellsNeeded && getAverageCMC(deckList) < 4) {
final Iterable<PaperCard> nonLands = Iterables.filter(rankedColorList,
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard::getRules));
final PaperCard card = Iterables.getFirst(nonLands, null);
if (card != null) {
deckList.add(card);
@@ -342,7 +342,7 @@ public class LimitedDeckBuilder extends DeckGeneratorBase {
*/
private void addLands(final int[] clrCnts, final String landSetCode) {
// basic lands that are available in the deck
final Iterable<PaperCard> basicLands = Iterables.filter(aiPlayables, Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard.FN_GET_RULES));
final Iterable<PaperCard> basicLands = Iterables.filter(aiPlayables, Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard::getRules));
final Set<PaperCard> snowLands = new HashSet<>();
// total of all ClrCnts
@@ -455,7 +455,7 @@ public class LimitedDeckBuilder extends DeckGeneratorBase {
*/
private void addNonBasicLands() {
final Iterable<PaperCard> lands = Iterables.filter(aiPlayables,
Predicates.compose(CardRulesPredicates.Presets.IS_NONBASIC_LAND, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_NONBASIC_LAND, PaperCard::getRules));
List<PaperCard> landsToAdd = new ArrayList<>();
for (final PaperCard card : lands) {
if (landsNeeded > 0) {
@@ -483,7 +483,7 @@ public class LimitedDeckBuilder extends DeckGeneratorBase {
private void addThirdColorCards(int num) {
if (num > 0) {
final Iterable<PaperCard> others = Iterables.filter(aiPlayables,
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard::getRules));
// We haven't yet ranked the off-color cards.
// Compare them to the cards already in the deckList.
List<PaperCard> rankedOthers = CardRanker.rankCardsInPack(others, deckList, colors, true);
@@ -500,7 +500,7 @@ public class LimitedDeckBuilder extends DeckGeneratorBase {
hasColor = Predicates.or(new DeckGeneratorBase.MatchColorIdentity(colors),
DeckGeneratorBase.COLORLESS_CARDS);
final Iterable<PaperCard> threeColorList = Iterables.filter(rankedOthers,
Predicates.compose(hasColor, PaperCard.FN_GET_RULES));
Predicates.compose(hasColor, PaperCard::getRules));
for (final PaperCard card : threeColorList) {
if (num > 0) {
toAdd.add(card);
@@ -527,7 +527,7 @@ public class LimitedDeckBuilder extends DeckGeneratorBase {
*/
private void addRandomCards(int num) {
final Iterable<PaperCard> others = Iterables.filter(aiPlayables,
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard.FN_GET_RULES));
Predicates.compose(CardRulesPredicates.Presets.IS_NON_LAND, PaperCard::getRules));
List <PaperCard> toAdd = new ArrayList<>();
for (final PaperCard card : others) {
if (num > 0) {
@@ -671,7 +671,7 @@ public class LimitedDeckBuilder extends DeckGeneratorBase {
creatureCosts.put(i, 0);
}
final Predicate<PaperCard> filter = Predicates.compose(CardRulesPredicates.Presets.IS_CREATURE,
PaperCard.FN_GET_RULES);
PaperCard::getRules);
for (final IPaperCard creature : Iterables.filter(deckList, filter)) {
int cmc = creature.getRules().getManaCost().getCMC();
if (cmc < 1) {

View File

@@ -265,7 +265,7 @@ public class LimitedPlayerAI extends LimitedPlayer {
DeckGeneratorBase.MatchColorIdentity hasColor = new DeckGeneratorBase.MatchColorIdentity(colors);
Iterable<PaperCard> colorList = Iterables.filter(deckCards,
Predicates.not(Predicates.compose(hasColor, PaperCard.FN_GET_RULES)));
Predicates.not(Predicates.compose(hasColor, PaperCard::getRules)));
PaperCard exchangeCard = null;

View File

@@ -39,30 +39,27 @@ public abstract class LimitedWinLoseController {
view.getBtnRestart().setText(localizer.getMessage("btnRestartRound"));
showOutcome(new Runnable() {
@Override
public void run() {
if (!lastGame.isMatchOver()) {
showTournamentInfo(localizer.getMessage("btnTournamentInfo"));
return;
}
showOutcome(() -> {
if (!lastGame.isMatchOver()) {
showTournamentInfo(localizer.getMessage("btnTournamentInfo"));
return;
}
if (wonMatch) {
if (gauntlet.getCurrentRound() < gauntlet.getRounds()) {
view.getBtnContinue().setText(localizer.getMessage("btnNextRound") + " (" + (gauntlet.getCurrentRound() + 1)
+ "/" + gauntlet.getRounds() + ")");
nextRound = true;
view.getBtnContinue().setEnabled(true);
showTournamentInfo(localizer.getMessage("btnWonRound") + gauntlet.getCurrentRound() + "/"
+ gauntlet.getRounds());
} else {
showTournamentInfo(localizer.getMessage("btnWonTournament"));
}
} else {
view.getBtnContinue().setVisible(false);
showTournamentInfo(localizer.getMessage("btnLoseRound") + gauntlet.getCurrentRound() + "/"
if (wonMatch) {
if (gauntlet.getCurrentRound() < gauntlet.getRounds()) {
view.getBtnContinue().setText(localizer.getMessage("btnNextRound") + " (" + (gauntlet.getCurrentRound() + 1)
+ "/" + gauntlet.getRounds() + ")");
nextRound = true;
view.getBtnContinue().setEnabled(true);
showTournamentInfo(localizer.getMessage("btnWonRound") + gauntlet.getCurrentRound() + "/"
+ gauntlet.getRounds());
} else {
showTournamentInfo(localizer.getMessage("btnWonTournament"));
}
} else {
view.getBtnContinue().setVisible(false);
showTournamentInfo(localizer.getMessage("btnLoseRound") + gauntlet.getCurrentRound() + "/"
+ gauntlet.getRounds());
}
});
}

View File

@@ -42,7 +42,7 @@ public class SealedDeckBuilder extends LimitedDeckBuilder {
colorChooserList.add(cp);
}
Iterable<CardRules> rules = Iterables.transform(colorChooserList, PaperCard.FN_GET_RULES);
Iterable<CardRules> rules = Iterables.transform(colorChooserList, PaperCard::getRules);
int white = Iterables.size(Iterables.filter(rules, CardRulesPredicates.Presets.IS_WHITE));
int blue = Iterables.size(Iterables.filter(rules, CardRulesPredicates.Presets.IS_BLUE));

View File

@@ -4,7 +4,6 @@ import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import forge.card.CardEdition;
@@ -100,36 +99,28 @@ public class ThemedChaosDraft implements Comparable<ThemedChaosDraft> {
default:
format = formats.getStandard();
}
return new Predicate<CardEdition>() {
@Override
public boolean apply(final CardEdition cardEdition){
return DEFAULT_FILTER.apply(cardEdition) && format.isSetLegal(cardEdition.getCode());
}
};
return cardEdition -> DEFAULT_FILTER.apply(cardEdition) && format.isSetLegal(cardEdition.getCode());
}
/**
* Default filter that only allows actual sets that were printed as 15-card boosters
*/
private static final Predicate<CardEdition> DEFAULT_FILTER = new Predicate<CardEdition>() {
@Override
public boolean apply(final CardEdition cardEdition) {
boolean isExpansion = cardEdition.getType().equals(CardEdition.Type.EXPANSION);
boolean isCoreSet = cardEdition.getType().equals(CardEdition.Type.CORE);
boolean isReprintSet = cardEdition.getType().equals(CardEdition.Type.REPRINT);
if (isExpansion || isCoreSet || isReprintSet) {
// Only allow sets with 15 cards in booster packs
if (cardEdition.hasBoosterTemplate()) {
final List<Pair<String, Integer>> slots = cardEdition.getBoosterTemplate().getSlots();
int boosterSize = 0;
for (Pair<String, Integer> slot : slots) {
boosterSize += slot.getRight();
}
return boosterSize == 15;
private static final Predicate<CardEdition> DEFAULT_FILTER = cardEdition -> {
boolean isExpansion = cardEdition.getType().equals(CardEdition.Type.EXPANSION);
boolean isCoreSet = cardEdition.getType().equals(CardEdition.Type.CORE);
boolean isReprintSet = cardEdition.getType().equals(CardEdition.Type.REPRINT);
if (isExpansion || isCoreSet || isReprintSet) {
// Only allow sets with 15 cards in booster packs
if (cardEdition.hasBoosterTemplate()) {
final List<Pair<String, Integer>> slots = cardEdition.getBoosterTemplate().getSlots();
int boosterSize = 0;
for (Pair<String, Integer> slot : slots) {
boosterSize += slot.getRight();
}
return boosterSize == 15;
}
return false;
}
return false;
};
/*
@@ -195,16 +186,9 @@ public class ThemedChaosDraft implements Comparable<ThemedChaosDraft> {
return true;
}
public static final Function<ThemedChaosDraft, String> FN_GET_TAG = new Function<ThemedChaosDraft, String>() {
@Override
public String apply(ThemedChaosDraft themedChaosBooster) {
return themedChaosBooster.getTag();
}
};
public static class Reader extends StorageReaderFile<ThemedChaosDraft> {
public Reader(String pathname) {
super(pathname, ThemedChaosDraft.FN_GET_TAG);
super(pathname, ThemedChaosDraft::getTag);
}
@Override

View File

@@ -534,23 +534,20 @@ public abstract class GameLobby implements IHasGameType {
}
//if above checks succeed, return runnable that can be used to finish starting game
return new Runnable() {
@Override
public void run() {
hostedMatch = GuiBase.getInterface().hostMatch();
hostedMatch.startMatch(GameType.Constructed, variantTypes, players, guis);
return () -> {
hostedMatch = GuiBase.getInterface().hostMatch();
hostedMatch.startMatch(GameType.Constructed, variantTypes, players, guis);
for (final Player p : hostedMatch.getGame().getPlayers()) {
final LobbySlot slot = playerToSlot.get(p.getRegisteredPlayer());
if (p.getController() instanceof IGameController) {
gameControllers.put(slot, (IGameController) p.getController());
}
for (final Player p : hostedMatch.getGame().getPlayers()) {
final LobbySlot slot = playerToSlot.get(p.getRegisteredPlayer());
if (p.getController() instanceof IGameController) {
gameControllers.put(slot, (IGameController) p.getController());
}
hostedMatch.gameControllers = gameControllers;
onGameStarted();
}
hostedMatch.gameControllers = gameControllers;
onGameStarted();
};
}

View File

@@ -2,7 +2,6 @@ package forge.gamemodes.match;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -135,13 +134,11 @@ public class HostedMatch {
}
final List<RegisteredPlayer> sortedPlayers = Lists.newArrayList(players);
Collections.sort(sortedPlayers, new Comparator<RegisteredPlayer>() {
@Override public final int compare(final RegisteredPlayer p1, final RegisteredPlayer p2) {
Collections.sort(sortedPlayers, (p1, p2) -> {
final int v1 = p1.getPlayer() instanceof LobbyPlayerHuman ? 0 : 1;
final int v2 = p2.getPlayer() instanceof LobbyPlayerHuman ? 0 : 1;
return Integer.compare(v1, v2);
}
final int v1 = p1.getPlayer() instanceof LobbyPlayerHuman ? 0 : 1;
final int v2 = p2.getPlayer() instanceof LobbyPlayerHuman ? 0 : 1;
return Integer.compare(v1, v2);
});
if (sortedPlayers.size() == 2) {
@@ -262,30 +259,28 @@ public class HostedMatch {
// It's important to run match in a different thread to allow GUI inputs to be invoked from inside game.
// Game is set on pause while gui player takes decisions
game.getAction().invoke(new Runnable() {
@Override public final void run() {
if (humanCount == 0) {
// Create FControlGamePlayback in game thread to allow pausing
playbackControl = new FControlGamePlayback(humanControllers.get(0));
playbackControl.setGame(game);
game.subscribeToEvents(playbackControl);
}
// Actually start the game!
match.startGame(game, startGameHook);
// this function waits?
if (endGameHook != null){
endGameHook.run();
}
game.getAction().invoke(() -> {
if (humanCount == 0) {
// Create FControlGamePlayback in game thread to allow pausing
playbackControl = new FControlGamePlayback(humanControllers.get(0));
playbackControl.setGame(game);
game.subscribeToEvents(playbackControl);
}
// Actually start the game!
match.startGame(game, startGameHook);
// this function waits?
if (endGameHook != null){
endGameHook.run();
}
// After game is over...
isMatchOver = match.isMatchOver();
if (humanCount == 0) {
// ... if no human players, let AI decide next game
if (isMatchOver) {
addNextGameDecision(null, NextGameDecision.QUIT);
} else {
addNextGameDecision(null, NextGameDecision.CONTINUE);
}
// After game is over...
isMatchOver = match.isMatchOver();
if (humanCount == 0) {
// ... if no human players, let AI decide next game
if (isMatchOver) {
addNextGameDecision(null, NextGameDecision.QUIT);
} else {
addNextGameDecision(null, NextGameDecision.CONTINUE);
}
}
});
@@ -397,23 +392,20 @@ public class HostedMatch {
final GameView gameView = event.subgame.getView();
Runnable switchGameView = new Runnable() {
@Override
public void run() {
for (final Player p : event.subgame.getPlayers()) {
if (p.getController() instanceof PlayerControllerHuman) {
final PlayerControllerHuman humanController = (PlayerControllerHuman) p.getController();
final IGuiGame gui = guis.get(p.getRegisteredPlayer());
humanController.setGui(gui);
gui.setGameView(null);
gui.setGameView(gameView);
gui.setOriginalGameController(p.getView(), humanController);
gui.openView(new TrackableCollection<>(p.getView()));
gui.setGameView(null);
gui.setGameView(gameView);
event.subgame.subscribeToEvents(new FControlGameEventHandler(humanController));
gui.message(event.message);
}
Runnable switchGameView = () -> {
for (final Player p : event.subgame.getPlayers()) {
if (p.getController() instanceof PlayerControllerHuman) {
final PlayerControllerHuman humanController = (PlayerControllerHuman) p.getController();
final IGuiGame gui = guis.get(p.getRegisteredPlayer());
humanController.setGui(gui);
gui.setGameView(null);
gui.setGameView(gameView);
gui.setOriginalGameController(p.getView(), humanController);
gui.openView(new TrackableCollection<>(p.getView()));
gui.setGameView(null);
gui.setGameView(gameView);
event.subgame.subscribeToEvents(new FControlGameEventHandler(humanController));
gui.message(event.message);
}
}
};
@@ -433,22 +425,19 @@ public class HostedMatch {
@Override
public Void visit(final GameEventSubgameEnd event) {
final GameView gameView = event.maingame.getView();
Runnable switchGameView = new Runnable() {
@Override
public void run() {
for (final Player p : event.maingame.getPlayers()) {
if (p.getController() instanceof PlayerControllerHuman) {
final PlayerControllerHuman humanController = (PlayerControllerHuman) p.getController();
final IGuiGame gui = guis.get(p.getRegisteredPlayer());
gui.setGameView(null);
gui.setGameView(gameView);
gui.setOriginalGameController(p.getView(), humanController);
gui.openView(new TrackableCollection<>(p.getView()));
gui.setGameView(null);
gui.setGameView(gameView);
gui.updatePhase(true);
gui.message(event.message);
}
Runnable switchGameView = () -> {
for (final Player p : event.maingame.getPlayers()) {
if (p.getController() instanceof PlayerControllerHuman) {
final PlayerControllerHuman humanController = (PlayerControllerHuman) p.getController();
final IGuiGame gui = guis.get(p.getRegisteredPlayer());
gui.setGameView(null);
gui.setGameView(gameView);
gui.setOriginalGameController(p.getView(), humanController);
gui.openView(new TrackableCollection<>(p.getView()));
gui.setGameView(null);
gui.setGameView(gameView);
gui.updatePhase(true);
gui.message(event.message);
}
}
};
@@ -483,11 +472,9 @@ public class HostedMatch {
private void addNextGameDecision(final PlayerControllerHuman controller, final NextGameDecision decision) {
if (decision == NextGameDecision.QUIT) {
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override public void run() {
endCurrentGame();
isMatchOver = true;
}
FThreads.invokeInEdtNowOrLater(() -> {
endCurrentGame();
isMatchOver = true;
});
return; // if any player chooses quit, quit the match
}
@@ -511,17 +498,9 @@ public class HostedMatch {
}
if (continueMatch >= newMatch) {
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override public void run() {
continueMatch();
}
});
FThreads.invokeInEdtNowOrLater(this::continueMatch);
} else {
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override public void run() {
restartMatch();
}
});
FThreads.invokeInEdtNowOrLater(this::restartMatch);
}
}

View File

@@ -60,12 +60,8 @@ public class InputBlock extends InputSyncronizedBase {
for (final Card attacker : combat.getAttackers()) {
for (final Card c : defender.getCreaturesInPlay()) {
if (CombatUtil.canBlock(attacker, c, combat)) {
FThreads.invokeInEdtNowOrLater(new Runnable() { //must set current attacker on EDT
@Override
public void run() {
setCurrentAttacker(attacker);
}
});
//must set current attacker on EDT
FThreads.invokeInEdtNowOrLater(() -> setCurrentAttacker(attacker));
return;
}
}
@@ -103,12 +99,7 @@ public class InputBlock extends InputSyncronizedBase {
stop();
} else {
//must run in game thread to prevent problems for mobile game
ThreadUtil.invokeInGameThread(new Runnable() {
@Override
public void run() {
getController().getGui().message(blockErrors);
}
});
ThreadUtil.invokeInGameThread(() -> getController().getGui().message(blockErrors));
}
}

View File

@@ -118,16 +118,14 @@ public class InputConfirmMulligan extends InputSyncronizedBase {
//pfps leave this as is for now - it is confirming during another confirm so it might need the popup
if (getController().getGui().confirm(cView, "Use " + cView + "'s ability?")) {
cardSelectLocked = true;
ThreadUtil.invokeInGameThread(new Runnable() {
@Override public void run() {
final CardCollectionView hand = c0.getController().getCardsIn(ZoneType.Hand);
final int handSize = hand.size();
for (final Card c : hand.threadSafeIterable()) {
player.getGame().getAction().exile(c, null, null);
}
c0.getController().drawCards(handSize);
cardSelectLocked = false;
ThreadUtil.invokeInGameThread(() -> {
final CardCollectionView hand = c0.getController().getCardsIn(ZoneType.Hand);
final int handSize = hand.size();
for (final Card c : hand.threadSafeIterable()) {
player.getGame().getAction().exile(c, null, null);
}
c0.getController().drawCards(handSize);
cardSelectLocked = false;
});
}
return true;

View File

@@ -72,12 +72,9 @@ public class InputPassPriority extends InputSyncronizedBase {
/** {@inheritDoc} */
@Override
protected final void onOk() {
passPriority(new Runnable() {
@Override
public void run() {
getController().macros().addRememberedAction(new PassPriorityAction());
stop();
}
passPriority(() -> {
getController().macros().addRememberedAction(new PassPriorityAction());
stop();
});
}
@@ -86,12 +83,9 @@ public class InputPassPriority extends InputSyncronizedBase {
protected final void onCancel() {
if (!getController().tryUndoLastAction()) { //undo if possible
//otherwise end turn
passPriority(new Runnable() {
@Override
public void run() {
getController().autoPassUntilEndOfTurn();
stop();
}
passPriority(() -> {
getController().autoPassUntilEndOfTurn();
stop();
});
}
}
@@ -108,17 +102,15 @@ public class InputPassPriority extends InputSyncronizedBase {
if (game.getStack().isEmpty()) { //phase can't end right now if stack isn't empty
Player player = game.getPhaseHandler().getPriorityPlayer();
if (player != null && player.getManaPool().willManaBeLostAtEndOfPhase() && player.getLobbyPlayer() == GamePlayerUtil.getGuiPlayer()) {
ThreadUtil.invokeInGameThread(new Runnable() { //must invoke in game thread so dialog can be shown on mobile game
@Override
public void run() {
Localizer localizer = Localizer.getInstance();
String message = localizer.getMessage("lblYouHaveManaFloatingInYourManaPoolCouldBeLostIfPassPriority");
if (player.getManaPool().hasBurn()) {
message += " " + localizer.getMessage("lblYouWillTakeManaBurnDamageEqualAmountFloatingManaLostThisWay");
}
if (getController().getGui().showConfirmDialog(message, localizer.getMessage("lblManaFloating"), localizer.getMessage("lblOK"), localizer.getMessage("lblCancel"))) {
runnable.run();
}
//must invoke in game thread so dialog can be shown on mobile game
ThreadUtil.invokeInGameThread(() -> {
Localizer localizer = Localizer.getInstance();
String message = localizer.getMessage("lblYouHaveManaFloatingInYourManaPoolCouldBeLostIfPassPriority");
if (player.getManaPool().hasBurn()) {
message += " " + localizer.getMessage("lblYouWillTakeManaBurnDamageEqualAmountFloatingManaLostThisWay");
}
if (getController().getGui().showConfirmDialog(message, localizer.getMessage("lblManaFloating"), localizer.getMessage("lblOK"), localizer.getMessage("lblCancel"))) {
runnable.run();
}
});
return;

View File

@@ -338,33 +338,30 @@ public abstract class InputPayMana extends InputSyncronizedBase {
// System.out.println("Chosen sa=" + chosen + " of " + chosen.getHostCard() + " to pay mana");
locked = true;
game.getAction().invoke(new Runnable() {
@Override
public void run() {
if (HumanPlay.playSpellAbility(getController(), chosen.getActivatingPlayer(), chosen)) {
final List<AbilityManaPart> manaAbilities = chosen.getAllManaParts();
boolean restrictionsMet = true;
game.getAction().invoke(() -> {
if (HumanPlay.playSpellAbility(getController(), chosen.getActivatingPlayer(), chosen)) {
final List<AbilityManaPart> manaAbilities = chosen.getAllManaParts();
boolean restrictionsMet = true;
for (AbilityManaPart sa : manaAbilities) {
if (!sa.meetsManaRestrictions(saPaidFor)) {
restrictionsMet = false;
break;
}
for (AbilityManaPart sa : manaAbilities) {
if (!sa.meetsManaRestrictions(saPaidFor)) {
restrictionsMet = false;
break;
}
if (restrictionsMet && !player.getController().isFullControl()) {
player.getManaPool().payManaFromAbility(saPaidFor, manaCost, chosen);
}
if (!restrictionsMet || chosen.getPayCosts().hasManaCost()) {
// force refresh in case too much mana got spent
updateButtons();
canPayManaCost = null;
}
onManaAbilityPaid();
}
// Need to call this to unlock
onStateChanged();
if (restrictionsMet && !player.getController().isFullControl()) {
player.getManaPool().payManaFromAbility(saPaidFor, manaCost, chosen);
}
if (!restrictionsMet || chosen.getPayCosts().hasManaCost()) {
// force refresh in case too much mana got spent
updateButtons();
canPayManaCost = null;
}
onManaAbilityPaid();
}
// Need to call this to unlock
onStateChanged();
});
return true;
@@ -390,19 +387,11 @@ public abstract class InputPayMana extends InputSyncronizedBase {
if (supportAutoPay() && !locked) { //prevent AI taking over from double-clicking Auto
locked = true;
//use AI utility to automatically pay mana cost if possible
final Runnable proc = new Runnable() {
@Override
public void run() {
ComputerUtilMana.payManaCost(manaCost, saPaidFor, player, effect);
}
};
final Runnable proc = () -> ComputerUtilMana.payManaCost(manaCost, saPaidFor, player, effect);
//must run in game thread as certain payment actions can only be automated there
game.getAction().invoke(new Runnable() {
@Override
public void run() {
runAsAi(proc);
onStateChanged();
}
game.getAction().invoke(() -> {
runAsAi(proc);
onStateChanged();
});
}
}
@@ -451,12 +440,7 @@ public abstract class InputPayMana extends InputSyncronizedBase {
done();
stop();
} else {
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override
public void run() {
updateMessage();
}
});
FThreads.invokeInEdtNowOrLater(this::updateMessage);
}
}

View File

@@ -64,14 +64,11 @@ public class InputProxy implements Observer {
if (!(nextInput instanceof InputLockUI)) {
controller.getGui().setCurrentPlayer(nextInput.getOwner());
}
final Runnable showMessage = new Runnable() {
@Override
public void run() {
Input current = getInput();
controller.getInputQueue().syncPoint();
//System.out.printf("\t%s > showMessage @ %s/%s during %s%n", FThreads.debugGetCurrThreadId(), nextInput.getClass().getSimpleName(), current.getClass().getSimpleName(), game.getPhaseHandler().debugPrintState());
current.showMessageInitial();
}
final Runnable showMessage = () -> {
Input current = getInput();
controller.getInputQueue().syncPoint();
//System.out.printf("\t%s > showMessage @ %s/%s during %s%n", FThreads.debugGetCurrThreadId(), nextInput.getClass().getSimpleName(), current.getClass().getSimpleName(), game.getPhaseHandler().debugPrintState());
current.showMessageInitial();
};
FThreads.invokeInEdtLater(showMessage);
}

View File

@@ -110,7 +110,7 @@ public final class InputSelectCardsForConvokeOrImprovise extends InputSelectMany
}
@Override
protected final void onPlayerSelected(final Player player, final ITriggerEvent triggerEvent) {
protected void onPlayerSelected(final Player player, final ITriggerEvent triggerEvent) {
}
public Map<Card, ManaCostShard> getConvokeMap() {

View File

@@ -60,12 +60,9 @@ public class InputSelectEntitiesFromList<T extends GameEntity> extends InputSele
zonesToUpdate.add(new PlayerZoneUpdate(cz.getPlayer().getView(), cz.getZoneType()));
}
}
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override
public void run() {
getController().getGui().updateZones(zonesToUpdate);
zonesShown = getController().getGui().tempShowZones(controller.getPlayer().getView(), zonesToUpdate);
}
FThreads.invokeInEdtNowOrLater(() -> {
getController().getGui().updateZones(zonesToUpdate);
zonesShown = getController().getGui().tempShowZones(controller.getPlayer().getView(), zonesToUpdate);
});
}

View File

@@ -17,7 +17,6 @@ import forge.game.GameEntity;
import forge.game.GameObject;
import forge.game.ability.ApiType;
import forge.game.card.Card;
import forge.game.card.CardPredicates;
import forge.game.card.CardView;
import forge.game.player.Player;
import forge.game.player.PlayerView;
@@ -48,8 +47,8 @@ public final class InputSelectTargets extends InputSyncronizedBase {
private boolean mustTargetFiltered;
private static final long serialVersionUID = -1091595663541356356L;
public final boolean hasCancelled() { return bCancel; }
public final boolean hasPressedOk() { return bOk; }
public boolean hasCancelled() { return bCancel; }
public boolean hasPressedOk() { return bOk; }
public InputSelectTargets(final PlayerControllerHuman controller, final List<Card> choices, final SpellAbility sa, final boolean mandatory, Integer numTargets, Collection<Integer> divisionValues, Predicate<GameObject> filter, boolean mustTargetFiltered) {
super(controller);
@@ -72,16 +71,13 @@ public final class InputSelectTargets extends InputSyncronizedBase {
for (final Card c : choices) {
zonesToUpdate.add(new PlayerZoneUpdate(c.getZone().getPlayer().getView(), c.getZone().getZoneType()));
}
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override
public void run() {
for (final GameEntity c : targets) {
if (c instanceof Card) {
controller.getGui().setUsedToPay(CardView.get((Card) c), true);
}
FThreads.invokeInEdtNowOrLater(() -> {
for (final GameEntity c : targets) {
if (c instanceof Card) {
controller.getGui().setUsedToPay(CardView.get((Card) c), true);
}
controller.getGui().updateZones(zonesToUpdate);
}
controller.getGui().updateZones(zonesToUpdate);
});
}
@@ -152,19 +148,19 @@ public final class InputSelectTargets extends InputSyncronizedBase {
}
@Override
protected final void onCancel() {
protected void onCancel() {
bCancel = true;
this.done();
}
@Override
protected final void onOk() {
protected void onOk() {
bOk = true;
this.done();
}
@Override
protected final boolean onCardSelected(final Card card, final List<Card> otherCardsToSelect, final ITriggerEvent triggerEvent) {
protected boolean onCardSelected(final Card card, final List<Card> otherCardsToSelect, final ITriggerEvent triggerEvent) {
if (targets.contains(card)) {
removeTarget(card);
return false;
@@ -204,7 +200,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
if (sa.hasParam("MaxTotalTargetCMC")) {
int maxTotalCMC = tgt.getMaxTotalCMC(sa.getHostCard(), sa);
if (maxTotalCMC > 0) {
int soFar = Aggregates.sum(sa.getTargets().getTargetCards(), CardPredicates.Accessors.fnGetCmc);
int soFar = Aggregates.sum(sa.getTargets().getTargetCards(), Card::getCMC);
if (!sa.isTargeting(card)) {
soFar += card.getCMC();
}
@@ -218,7 +214,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
if (sa.hasParam("MaxTotalTargetPower")) {
int maxTotalPower = tgt.getMaxTotalPower(sa.getHostCard(), sa);
if (maxTotalPower > 0) {
int soFar = Aggregates.sum(sa.getTargets().getTargetCards(), CardPredicates.Accessors.fnGetNetPower);
int soFar = Aggregates.sum(sa.getTargets().getTargetCards(), Card::getNetPower);
if (!sa.isTargeting(card)) {
soFar += card.getNetPower();
}
@@ -317,7 +313,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
}
@Override
protected final void onPlayerSelected(final Player player, final ITriggerEvent triggerEvent) {
protected void onPlayerSelected(final Player player, final ITriggerEvent triggerEvent) {
if (targets.contains(player)) {
removeTarget(player);
return;

View File

@@ -40,12 +40,7 @@ public abstract class InputSyncronizedBase extends InputBase implements InputSyn
onStop();
// ensure input won't accept any user actions.
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override
public void run() {
setFinished();
}
});
FThreads.invokeInEdtNowOrLater(this::setFinished);
// thread irrelevant
if (getController().getInputQueue().getInput() != null) {

View File

@@ -53,38 +53,36 @@ public abstract class GameProtocolHandler<T> extends ChannelInboundHandlerAdapte
beforeCall(protocolMethod, args);
final Class<?> returnType = protocolMethod.getReturnType();
final Runnable toRun = new Runnable() {
@Override public final void run() {
if (returnType.equals(Void.TYPE)) {
try {
method.invoke(toInvoke, args);
} catch (final IllegalAccessException | IllegalArgumentException e) {
System.err.println(String.format("Unknown protocol method %s with %d args", methodName, args == null ? 0 : args.length));
} catch (final InvocationTargetException e) {
//throw new RuntimeException(e.getTargetException());
catchedError[0] += (String.format("RuntimeException: %s (GameProtocolHandler.java Line 65)\n", e.getTargetException().toString()));
System.err.println(e.getTargetException().toString());
}
} else {
Serializable reply = null;
try {
final Object theReply = method.invoke(toInvoke, args);
if (theReply instanceof Serializable) {
protocolMethod.checkReturnValue(theReply);
reply = (Serializable) theReply;
} else if (theReply != null) {
System.err.println(String.format("Non-serializable return type %s for method %s, returning null", returnType.getName(), methodName));
}
} catch (final IllegalAccessException | IllegalArgumentException e) {
System.err.println(String.format("Unknown protocol method %s with %d args, replying with null", methodName, args == null ? 0 : args.length));
} catch (final NullPointerException | InvocationTargetException e) {
//throw new RuntimeException(e.getTargetException());
catchedError[0] += e.toString();
SOptionPane.showMessageDialog(catchedError[0], "Error", FSkinProp.ICO_WARNING);
System.err.println(e.toString());
}
getRemote(ctx).send(new ReplyEvent(event.getId(), reply));
final Runnable toRun = () -> {
if (returnType.equals(Void.TYPE)) {
try {
method.invoke(toInvoke, args);
} catch (final IllegalAccessException | IllegalArgumentException e) {
System.err.println(String.format("Unknown protocol method %s with %d args", methodName, args == null ? 0 : args.length));
} catch (final InvocationTargetException e) {
//throw new RuntimeException(e.getTargetException());
catchedError[0] += (String.format("RuntimeException: %s (GameProtocolHandler.java Line 65)\n", e.getTargetException().toString()));
System.err.println(e.getTargetException().toString());
}
} else {
Serializable reply = null;
try {
final Object theReply = method.invoke(toInvoke, args);
if (theReply instanceof Serializable) {
protocolMethod.checkReturnValue(theReply);
reply = (Serializable) theReply;
} else if (theReply != null) {
System.err.println(String.format("Non-serializable return type %s for method %s, returning null", returnType.getName(), methodName));
}
} catch (final IllegalAccessException | IllegalArgumentException e) {
System.err.println(String.format("Unknown protocol method %s with %d args, replying with null", methodName, args == null ? 0 : args.length));
} catch (final NullPointerException | InvocationTargetException e) {
//throw new RuntimeException(e.getTargetException());
catchedError[0] += e.toString();
SOptionPane.showMessageDialog(catchedError[0], "Error", FSkinProp.ICO_WARNING);
System.err.println(e.toString());
}
getRemote(ctx).send(new ReplyEvent(event.getId(), reply));
}
};

View File

@@ -9,7 +9,6 @@ import forge.gamemodes.net.client.FGameClient;
import forge.gamemodes.net.event.IdentifiableNetEvent;
import forge.gamemodes.net.event.MessageEvent;
import forge.gamemodes.net.event.NetEvent;
import forge.gamemodes.net.event.UpdateLobbyPlayerEvent;
import forge.gamemodes.net.server.FServerManager;
import forge.gamemodes.net.server.ServerGameLobby;
import forge.gui.GuiBase;
@@ -17,7 +16,6 @@ import forge.gui.interfaces.IGuiGame;
import forge.gui.interfaces.ILobbyView;
import forge.gui.util.SOptionPane;
import forge.interfaces.ILobbyListener;
import forge.interfaces.IPlayerChangeListener;
import forge.interfaces.IUpdateable;
import forge.localinstance.properties.ForgeConstants;
import forge.localinstance.properties.ForgePreferences.FPref;
@@ -51,32 +49,29 @@ public class NetConnectUtil {
lobby.setListener(new IUpdateable() {
@Override
public final void update(final boolean fullUpdate) {
public void update(final boolean fullUpdate) {
view.update(fullUpdate);
server.updateLobbyState();
}
@Override
public final void update(final int slot, final LobbySlotType type) {return;}
public void update(final int slot, final LobbySlotType type) {return;}
});
view.setPlayerChangeListener(new IPlayerChangeListener() {
@Override
public final void update(final int index, final UpdateLobbyPlayerEvent event) {
server.updateSlot(index, event);
server.updateLobbyState();
}
view.setPlayerChangeListener((index, event) -> {
server.updateSlot(index, event);
server.updateLobbyState();
});
server.setLobbyListener(new ILobbyListener() {
@Override
public final void update(final GameLobbyData state, final int slot) {
public void update(final GameLobbyData state, final int slot) {
// NO-OP, lobby connected directly
}
@Override
public final void message(final String source, final String message) {
public void message(final String source, final String message) {
chatInterface.addMessage(new ChatMessage(source, message));
}
@Override
public final void close() {
public void close() {
// NO-OP, server can't receive close message
}
@Override
@@ -86,7 +81,7 @@ public class NetConnectUtil {
});
chatInterface.setGameClient(new IRemote() {
@Override
public final void send(final NetEvent event) {
public void send(final NetEvent event) {
if (event instanceof MessageEvent) {
final MessageEvent message = (MessageEvent) event;
chatInterface.addMessage(new ChatMessage(message.getSource(), message.getMessage()));
@@ -94,7 +89,7 @@ public class NetConnectUtil {
}
}
@Override
public final Object sendAndWait(final IdentifiableNetEvent event) {
public Object sendAndWait(final IdentifiableNetEvent event) {
send(event);
return null;
}
@@ -136,16 +131,16 @@ public class NetConnectUtil {
lobby.setListener(view);
client.addLobbyListener(new ILobbyListener() {
@Override
public final void message(final String source, final String message) {
public void message(final String source, final String message) {
chatInterface.addMessage(new ChatMessage(source, message));
}
@Override
public final void update(final GameLobbyData state, final int slot) {
public void update(final GameLobbyData state, final int slot) {
lobby.setLocalPlayer(slot);
lobby.setData(state);
}
@Override
public final void close() {
public void close() {
GuiBase.setInterrupted(true);
onlineLobby.closeConn(Localizer.getInstance().getMessage("lblYourConnectionToHostWasInterrupted", url));
}
@@ -154,12 +149,7 @@ public class NetConnectUtil {
return lobby;
}
});
view.setPlayerChangeListener(new IPlayerChangeListener() {
@Override
public final void update(final int index, final UpdateLobbyPlayerEvent event) {
client.send(event);
}
});
view.setPlayerChangeListener((index, event) -> client.send(event));
String hostname = url;
int port = ForgeProfileProperties.getServerPort();

View File

@@ -1,7 +1,6 @@
package forge.gamemodes.net;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
@@ -42,11 +41,7 @@ public class ReplyPool {
private static final class CompletableFuture extends FutureTask<Object> {
public CompletableFuture() {
super(new Callable<Object>() {
@Override public Object call() throws Exception {
return null;
}
});
super(() -> null);
}
@Override

View File

@@ -68,15 +68,13 @@ public class FGameClient implements IToServer {
// Start the connection attempt.
channel = b.connect(host, port).sync().channel();
final ChannelFuture ch = channel.closeFuture();
new Thread(new Runnable() {
@Override public void run() {
try {
ch.sync();
} catch (final InterruptedException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
new Thread(() -> {
try {
ch.sync();
} catch (final InterruptedException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}).start();
} catch (final InterruptedException e) {

View File

@@ -1,7 +1,6 @@
package forge.gamemodes.net.client;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.List;
@@ -216,13 +215,10 @@ final class GameClientHandler extends GameProtocolHandler<IGuiGame> {
}
final List<RegisteredPlayer> sortedPlayers = Lists.newArrayList(players);
Collections.sort(sortedPlayers, new Comparator<RegisteredPlayer>() {
@Override
public final int compare(final RegisteredPlayer p1, final RegisteredPlayer p2) {
final int v1 = p1.getPlayer() instanceof LobbyPlayerHuman ? 0 : 1;
final int v2 = p2.getPlayer() instanceof LobbyPlayerHuman ? 0 : 1;
return Integer.compare(v1, v2);
}
Collections.sort(sortedPlayers, (p1, p2) -> {
final int v1 = p1.getPlayer() instanceof LobbyPlayerHuman ? 0 : 1;
final int v2 = p2.getPlayer() instanceof LobbyPlayerHuman ? 0 : 1;
return Integer.compare(v1, v2);
});
return sortedPlayers;

View File

@@ -65,11 +65,9 @@ public final class FServerManager {
private final Map<Channel, RemoteClient> clients = Maps.newTreeMap();
private ServerGameLobby localLobby;
private ILobbyListener lobbyListener;
private final Thread shutdownHook = new Thread(new Runnable() {
@Override public final void run() {
if (isHosting()) {
stopServer(false);
}
private final Thread shutdownHook = new Thread(() -> {
if (isHosting()) {
stopServer(false);
}
});
@@ -103,7 +101,7 @@ public final class FServerManager {
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public final void initChannel(final SocketChannel ch) throws Exception {
public void initChannel(final SocketChannel ch) throws Exception {
final ChannelPipeline p = ch.pipeline();
p.addLast(
new CompatibleObjectEncoder(),
@@ -118,15 +116,13 @@ public final class FServerManager {
// Bind and start to accept incoming connections.
final ChannelFuture ch = b.bind(port).sync().channel().closeFuture();
new Thread(new Runnable() {
@Override public void run() {
try {
ch.sync();
} catch (final InterruptedException e) {
e.printStackTrace();
} finally {
stopServer();
}
new Thread(() -> {
try {
ch.sync();
} catch (final InterruptedException e) {
e.printStackTrace();
} finally {
stopServer();
}
}).start();
mapNatPort(port);

View File

@@ -1,7 +1,5 @@
package forge.gamemodes.planarconquest;
import com.google.common.base.Predicate;
import forge.card.CardRules;
import forge.deck.Deck;
import forge.deck.DeckSection;
@@ -25,12 +23,9 @@ public class ConquestCommander implements InventoryItem, IXmlWritable {
this(card0, null, null);
}
public ConquestCommander(PaperCard card0, ConquestPlane startingPlane) {
this(card0, ConquestUtil.generateDeck(card0, new DeckGenPool(startingPlane.getCardPool().getAllCards(new Predicate<PaperCard>() {
@Override
public boolean apply(PaperCard pc) {
CardRules rules = pc.getRules();
return !rules.canBeCommander() && !rules.getType().isPlaneswalker(); //prevent including additional commanders or planeswalkers in starting deck
}
this(card0, ConquestUtil.generateDeck(card0, new DeckGenPool(startingPlane.getCardPool().getAllCards(pc -> {
CardRules rules = pc.getRules();
return !rules.canBeCommander() && !rules.getType().isPlaneswalker(); //prevent including additional commanders or planeswalkers in starting deck
})), false), null);
}
private ConquestCommander(PaperCard card0, Deck deck0, ConquestRecord record0) {

View File

@@ -139,12 +139,7 @@ public class ConquestController {
rules.setGamesPerMatch(battle.gamesPerMatch());
rules.setManaBurn(FModel.getPreferences().getPrefBoolean(FPref.UI_MANABURN));
final HostedMatch hostedMatch = GuiBase.getInterface().hostMatch();
FThreads.invokeInEdtNowOrLater(new Runnable(){
@Override
public void run() {
hostedMatch.startMatch(rules, variants, starter, humanStart, gui);
}
});
FThreads.invokeInEdtNowOrLater(() -> hostedMatch.startMatch(rules, variants, starter, humanStart, gui));
activeBattle = battle;
}

View File

@@ -531,19 +531,9 @@ public final class ConquestData {
}
private static final Function<Entry<InventoryItem, Integer>, Comparable<?>> fnNewCompare =
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return FModel.getConquest().getModel().newCards.contains(from.getKey()) ? Integer.valueOf(1) : Integer.valueOf(0);
}
};
from -> FModel.getConquest().getModel().newCards.contains(from.getKey()) ? Integer.valueOf(1) : Integer.valueOf(0);
private static final Function<Entry<? extends InventoryItem, Integer>, Object> fnNewGet =
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return FModel.getConquest().getModel().newCards.contains(from.getKey()) ? "NEW" : "";
}
};
from -> FModel.getConquest().getModel().newCards.contains(from.getKey()) ? "NEW" : "";
public static Map<ColumnDef, ItemColumn> getColOverrides(ItemManagerConfig config) {
Map<ColumnDef, ItemColumn> colOverrides = new HashMap<>();

View File

@@ -23,8 +23,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.common.base.Function;
import forge.card.CardDb;
import forge.card.CardEdition;
import forge.card.CardEdition.CardInSet;
@@ -225,13 +223,6 @@ public class ConquestPlane {
return name;
}
public static final Function<ConquestPlane, String> FN_GET_NAME = new Function<ConquestPlane, String>() {
@Override
public String apply(ConquestPlane plane) {
return plane.getName();
}
};
public ConquestAwardPool getAwardPool() {
if (awardPool == null) { //delay initializing until needed
awardPool = new ConquestAwardPool(cardPool.getAllCards());
@@ -241,7 +232,7 @@ public class ConquestPlane {
public static class Reader extends StorageReaderFile<ConquestPlane> {
public Reader(String file0) {
super(file0, ConquestPlane.FN_GET_NAME);
super(file0, ConquestPlane::getName);
}
@Override

View File

@@ -131,23 +131,20 @@ public class ConquestRegion {
break;
case "colors":
colorSet = ColorSet.fromNames(value.toCharArray());
pred = Predicates.compose(CardRulesPredicates.hasColorIdentity(colorSet.getColor()), PaperCard.FN_GET_RULES);
pred = Predicates.compose(CardRulesPredicates.hasColorIdentity(colorSet.getColor()), PaperCard::getRules);
break;
case "sets":
final String[] sets = value.split(",");
for (int i = 0; i < sets.length; i++) {
sets[i] = sets[i].trim();
}
pred = new Predicate<PaperCard>() {
@Override
public boolean apply(PaperCard pc) {
for (String set : sets) {
if (pc.getEdition().equals(set)) {
return true;
}
pred = pc -> {
for (String set : sets) {
if (pc.getEdition().equals(set)) {
return true;
}
return false;
}
return false;
};
break;
default:

View File

@@ -186,24 +186,21 @@ public class ConquestUtil {
public static Iterable<PaperCard> getStartingPlaneswalkerOptions(final PaperCard startingCommander) {
final byte colorIdentity = startingCommander.getRules().getColorIdentity().getColor();
final List<String> selected = Lists.newArrayList();
return Iterables.filter(FModel.getMagicDb().getCommonCards().getAllNonPromosNonReprintsNoAlt(), new Predicate<PaperCard>() {
@Override
public boolean apply(PaperCard card) {
if (selected.contains(card.getName())) {
return false;
}
CardRules rules = card.getRules();
boolean allowed = rules.getType().isPlaneswalker() &&
!card.getName().equals(startingCommander.getName()) && //don't allow picking a commander as a starting planeswalker
rules.getColorIdentity().hasNoColorsExcept(colorIdentity);
if (allowed) {
selected.add(card.getName());
return true;
}
return Iterables.filter(FModel.getMagicDb().getCommonCards().getAllNonPromosNonReprintsNoAlt(), card -> {
if (selected.contains(card.getName())) {
return false;
}
CardRules rules = card.getRules();
boolean allowed = rules.getType().isPlaneswalker() &&
!card.getName().equals(startingCommander.getName()) && //don't allow picking a commander as a starting planeswalker
rules.getColorIdentity().hasNoColorsExcept(colorIdentity);
if (allowed) {
selected.add(card.getName());
return true;
}
return false;
});
}

View File

@@ -209,7 +209,7 @@ public final class BoosterUtils {
for (int i = 0; i < quantity; i++) {
CardEdition edition = Aggregates.random(possibleEditions);
BoosterPack pack = BoosterPack.FN_FROM_SET.apply(edition);
BoosterPack pack = BoosterPack.fromSet(edition);
if (pack != null) {
output.add(pack);
@@ -315,7 +315,7 @@ public final class BoosterUtils {
if (preferredColors.contains(MagicColor.COLORLESS) && preferredColors.size() == 1) {
Predicate<CardRules> predicateRules = CardRulesPredicates.cost(StringOp.CONTAINS_IC, "p/");
Predicate<PaperCard> predicateCard = Predicates.compose(predicateRules, PaperCard.FN_GET_RULES);
Predicate<PaperCard> predicateCard = Predicates.compose(predicateRules, PaperCard::getRules);
int size = Iterables.size(Iterables.filter(cardPool, predicateCard));
int totalSize = cardPool.size();
@@ -336,7 +336,7 @@ public final class BoosterUtils {
CardRulesPredicates.isColor(preferredColors.get(index)),
CardRulesPredicates.Presets.IS_MULTICOLOR
);
Predicate<PaperCard> predicateCard = Predicates.compose(predicateRules, PaperCard.FN_GET_RULES);
Predicate<PaperCard> predicateCard = Predicates.compose(predicateRules, PaperCard::getRules);
//Adjust for the number of multicolored possibilities. This prevents flooding of non-selected
//colors if multicolored cards aren't in the selected sets. The more multi-colored cards in the
@@ -413,7 +413,7 @@ public final class BoosterUtils {
//handful of multi-colored cards.
do {
if (color2 != null) {
Predicate<PaperCard> color2c = Predicates.compose(color2, PaperCard.FN_GET_RULES);
Predicate<PaperCard> color2c = Predicates.compose(color2, PaperCard::getRules);
card = Aggregates.random(Iterables.filter(source, Predicates.and(filter, color2c)));
}
} while (card == null && colorMisses++ < 10);
@@ -496,7 +496,7 @@ public final class BoosterUtils {
Predicate<CardRules> cr = parseRulesLimitation(temp[1]);
//noinspection RedundantCast
if (Predicates.alwaysTrue() != (Object) cr) { // guava has a single instance for always-const predicates
preds.add(Predicates.compose(cr, PaperCard.FN_GET_RULES));
preds.add(Predicates.compose(cr, PaperCard::getRules));
}
}
@@ -516,10 +516,12 @@ public final class BoosterUtils {
rewards.add(new QuestRewardCardFiltered(temp));
} else if (temp.length >= 3 && temp[0].equalsIgnoreCase("booster") && temp[1].equalsIgnoreCase("pack")) {
// Type 4: a predetermined extra booster pack
rewards.add(BoosterPack.FN_FROM_SET.apply(FModel.getMagicDb().getEditions().get(temp[2])));
CardEdition edition = FModel.getMagicDb().getEditions().get(temp[2]);
rewards.add(BoosterPack.fromSet(edition));
} else if (temp.length >= 3 && temp[0].equalsIgnoreCase("tournament") && temp[1].equalsIgnoreCase("pack")) {
// Type 5: a predetermined extra tournament ("starter") pack
rewards.add(TournamentPack.FN_FROM_SET.apply(FModel.getMagicDb().getEditions().get(temp[2])));
CardEdition edition = FModel.getMagicDb().getEditions().get(temp[2]);
rewards.add(TournamentPack.fromSet(edition));
}
else if (temp.length > 0) {
// default: assume we are asking for a single copy of a specific card
@@ -578,23 +580,8 @@ public final class BoosterUtils {
public static void sort(List<PaperCard> cards) {
//sort cards alphabetically so colors appear together and rares appear on top
Collections.sort(cards, new Comparator<PaperCard>() {
@Override
public int compare(PaperCard c1, PaperCard c2) {
return c1.getName().compareTo(c2.getName());
}
});
Collections.sort(cards, new Comparator<PaperCard>() {
@Override
public int compare(PaperCard c1, PaperCard c2) {
return c1.getRules().getColor().compareTo(c2.getRules().getColor());
}
});
Collections.sort(cards, new Comparator<PaperCard>() {
@Override
public int compare(PaperCard c1, PaperCard c2) {
return c2.getRarity().compareTo(c1.getRarity());
}
});
Collections.sort(cards, Comparator.comparing(PaperCard::getName));
Collections.sort(cards, Comparator.comparing(c -> c.getRules().getColor()));
Collections.sort(cards, Comparator.comparing(PaperCard::getRarity).reversed());
}
}

View File

@@ -21,8 +21,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.common.base.Function;
import forge.deck.Deck;
import forge.item.InventoryItem;
@@ -51,10 +49,6 @@ public abstract class QuestEvent implements IQuestEvent {
private boolean isRandomMatch = false;
public static final Function<QuestEvent, String> FN_GET_NAME = new Function<QuestEvent, String>() {
@Override public final String apply(QuestEvent qe) { return qe.name; }
};
public final String getTitle() {
return title;
}

View File

@@ -20,8 +20,6 @@ package forge.gamemodes.quest;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Function;
import forge.deck.Deck;
/**
@@ -34,9 +32,6 @@ import forge.deck.Deck;
*
*/
public class QuestEventChallenge extends QuestEvent {
public static final Function<QuestEventChallenge, String> FN_GET_ID = new Function<QuestEventChallenge, String>() {
@Override public final String apply(QuestEventChallenge qe) { return qe.id; }
};
// ID (default -1, should be explicitly set at later time.)
/** The id. */

View File

@@ -20,7 +20,6 @@ package forge.gamemodes.quest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
@@ -465,7 +464,8 @@ public class QuestEventDraft implements IQuestEvent {
}
private BoosterPack getBoosterPack() {
return BoosterPack.FN_FROM_SET.apply(getRandomEdition());
CardEdition edition = getRandomEdition();
return BoosterPack.fromSet(edition);
}
private PaperCard getPromoCard() {
@@ -1001,16 +1001,13 @@ public class QuestEventDraft implements IQuestEvent {
}
final boolean oldSetsFirst = sets.get(0).getDate().before(FModel.getMagicDb().getEditions().get("SOM").getDate());
Collections.sort(allowedSets, new Comparator<CardEdition>() {
@Override
public int compare(final CardEdition edition1, final CardEdition edition2) {
if (edition1.getDate().before(edition2.getDate())) {
return oldSetsFirst ? -1 : 1;
} else if (edition1.getDate().after(edition2.getDate())) {
return oldSetsFirst ? 1 : -1;
}
return 0;
Collections.sort(allowedSets, (edition1, edition2) -> {
if (edition1.getDate().before(edition2.getDate())) {
return oldSetsFirst ? -1 : 1;
} else if (edition1.getDate().after(edition2.getDate())) {
return oldSetsFirst ? 1 : -1;
}
return 0;
});
boolean largeSetFound = false;

View File

@@ -107,7 +107,7 @@ public abstract class QuestRewardCard implements IQuestRewardCard {
}
if (filterRules != null) {
final Predicate<PaperCard> rulesPrinted = Predicates.compose(filterRules, PaperCard.FN_GET_RULES);
final Predicate<PaperCard> rulesPrinted = Predicates.compose(filterRules, PaperCard::getRules);
filters = Predicates.and(filters, rulesPrinted);
}
if (filterRarity != null) {

View File

@@ -134,36 +134,11 @@ public class QuestSpellShop {
return value;
}
public static final Function<Entry<InventoryItem, Integer>, Comparable<?>> fnPriceCompare = new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return getCardValue(from.getKey());
}
};
public static final Function<Entry<? extends InventoryItem, Integer>, Object> fnPriceGet = new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return getCardValue(from.getKey());
}
};
public static final Function<Entry<? extends InventoryItem, Integer>, Object> fnPriceSellGet = new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return Math.max((int) (multiplier * getCardValue(from.getKey())), 1);
}
};
public static final Function<Entry<InventoryItem, Integer>, Comparable<?>> fnDeckCompare = new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return decksUsingMyCards.count(from.getKey());
}
};
public static final Function<Entry<? extends InventoryItem, Integer>, Object> fnDeckGet = new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return Integer.toString(decksUsingMyCards.count(from.getKey()));
}
};
public static final Function<Entry<InventoryItem, Integer>, Comparable<?>> fnPriceCompare = from -> getCardValue(from.getKey());
public static final Function<Entry<? extends InventoryItem, Integer>, Object> fnPriceGet = from -> getCardValue(from.getKey());
public static final Function<Entry<? extends InventoryItem, Integer>, Object> fnPriceSellGet = from -> Math.max((int) (multiplier * getCardValue(from.getKey())), 1);
public static final Function<Entry<InventoryItem, Integer>, Comparable<?>> fnDeckCompare = from -> decksUsingMyCards.count(from.getKey());
public static final Function<Entry<? extends InventoryItem, Integer>, Object> fnDeckGet = from -> Integer.toString(decksUsingMyCards.count(from.getKey()));
public static long getTotalBuyCost(Iterable<Entry<InventoryItem, Integer>> items) {
long totalCost = 0;

View File

@@ -382,38 +382,30 @@ public class QuestTournamentController {
}
public void startDraft() {
ThreadUtil.invokeInGameThread(new Runnable() {
@Override
public void run() {
if (drafting) {
SOptionPane.showErrorDialog(localizer.getMessage("lblCurrentlyInDraft"));
return;
}
final QuestEventDraft draftEvent = QuestUtil.getDraftEvent();
final long creditsAvailable = FModel.getQuest().getAssets().getCredits();
if (draftEvent.canEnter()) {
SOptionPane.showMessageDialog(localizer.getMessage("lblYouNeed") + QuestUtil.formatCredits(draftEvent.getEntryFee() - creditsAvailable) + " " + localizer.getMessage("lblMoreCredits"), localizer.getMessage("lblNotEnoughCredits"), SOptionPane.WARNING_ICON);
return;
}
final boolean okayToEnter = SOptionPane.showOptionDialog(localizer.getMessage("lblTournamentCosts") + QuestUtil.formatCredits(draftEvent.getEntryFee()) + localizer.getMessage("lblSureEnterTournament"), localizer.getMessage("lblEnterDraftTournament"), FSkinProp.ICO_QUEST_GOLD, ImmutableList.of(localizer.getMessage("lblYes"), localizer.getMessage("lblNo")), 1) == 0;
if (!okayToEnter) {
return;
}
drafting = true;
final BoosterDraft draft = draftEvent.enter();
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
view.startDraft(draft);
}
});
ThreadUtil.invokeInGameThread(() -> {
if (drafting) {
SOptionPane.showErrorDialog(localizer.getMessage("lblCurrentlyInDraft"));
return;
}
final QuestEventDraft draftEvent = QuestUtil.getDraftEvent();
final long creditsAvailable = FModel.getQuest().getAssets().getCredits();
if (draftEvent.canEnter()) {
SOptionPane.showMessageDialog(localizer.getMessage("lblYouNeed") + QuestUtil.formatCredits(draftEvent.getEntryFee() - creditsAvailable) + " " + localizer.getMessage("lblMoreCredits"), localizer.getMessage("lblNotEnoughCredits"), SOptionPane.WARNING_ICON);
return;
}
final boolean okayToEnter = SOptionPane.showOptionDialog(localizer.getMessage("lblTournamentCosts") + QuestUtil.formatCredits(draftEvent.getEntryFee()) + localizer.getMessage("lblSureEnterTournament"), localizer.getMessage("lblEnterDraftTournament"), FSkinProp.ICO_QUEST_GOLD, ImmutableList.of(localizer.getMessage("lblYes"), localizer.getMessage("lblNo")), 1) == 0;
if (!okayToEnter) {
return;
}
drafting = true;
final BoosterDraft draft = draftEvent.enter();
FThreads.invokeInEdtLater(() -> view.startDraft(draft));
});
}

View File

@@ -525,13 +525,10 @@ public class QuestUtil {
public static void finishStartingGame() {
final QuestController qData = FModel.getQuest();
FThreads.invokeInBackgroundThread(new Runnable() {
@Override
public void run() {
qData.getDuelsManager().randomizeOpponents();
qData.setCurrentEvent(event);
qData.save();
}
FThreads.invokeInBackgroundThread(() -> {
qData.getDuelsManager().randomizeOpponents();
qData.setCurrentEvent(event);
qData.save();
});
int extraLifeHuman = 0;
@@ -608,12 +605,7 @@ public class QuestUtil {
final HostedMatch hostedMatch = GuiBase.getInterface().hostMatch();
final IGuiGame gui = GuiBase.getInterface().getNewGuiGame();
gui.setPlayerAvatar(aiPlayer, event);
FThreads.invokeInEdtNowOrLater(new Runnable(){
@Override
public void run() {
hostedMatch.startMatch(rules, variant, starter, ImmutableMap.of(humanStart, gui), null);
}
});
FThreads.invokeInEdtNowOrLater(() -> hostedMatch.startMatch(rules, variant, starter, ImmutableMap.of(humanStart, gui), null));
}
/**

View File

@@ -654,7 +654,7 @@ public final class QuestUtilCards {
formatFilter = Predicates.and(formatFilter, isLegalInQuestFormat(questController.getFormat()));
}
Iterable<CardEdition> rightEditions = Iterables.filter(FModel.getMagicDb().getEditions(), formatFilter);
questAssets.getShopList().addAllOfTypeFlat(Aggregates.random(Iterables.transform(rightEditions, TournamentPack.FN_FROM_SET), count));
questAssets.getShopList().addAllOfTypeFlat(Aggregates.random(Iterables.transform(rightEditions, TournamentPack::fromSet), count));
}
/**
@@ -669,7 +669,7 @@ public final class QuestUtilCards {
formatFilter = Predicates.and(formatFilter, isLegalInQuestFormat(questController.getFormat()));
}
Iterable<CardEdition> rightEditions = Iterables.filter(FModel.getMagicDb().getEditions(), formatFilter);
questAssets.getShopList().addAllOfTypeFlat(Aggregates.random(Iterables.transform(rightEditions, FatPack.FN_FROM_SET), count));
questAssets.getShopList().addAllOfTypeFlat(Aggregates.random(Iterables.transform(rightEditions, FatPack::fromSet), count));
}
private void generateBoosterBoxesInShop(final int count) {
@@ -701,7 +701,7 @@ public final class QuestUtilCards {
List<BoosterBox> output = new ArrayList<>();
for (CardEdition e : editions) {
output.add(BoosterBox.FN_FROM_SET.apply(e));
output.add(BoosterBox.fromSet(e));
}
questAssets.getShopList().addAllOfTypeFlat(output);
@@ -859,20 +859,10 @@ public final class QuestUtilCards {
// deck editors
// Maybe we should consider doing so later
/** The fn new compare. */
private final Function<Entry<InventoryItem, Integer>, Comparable<?>> fnNewCompare = new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return isNew(from.getKey()) ? Integer.valueOf(1) : Integer.valueOf(0);
}
};
private final Function<Entry<InventoryItem, Integer>, Comparable<?>> fnNewCompare = from -> isNew(from.getKey()) ? Integer.valueOf(1) : Integer.valueOf(0);
/** The fn new get. */
private final Function<Entry<? extends InventoryItem, Integer>, Object> fnNewGet = new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return isNew(from.getKey()) ? "NEW" : "";
}
};
private final Function<Entry<? extends InventoryItem, Integer>, Object> fnNewGet = from -> isNew(from.getKey()) ? "NEW" : "";
public Function<Entry<InventoryItem, Integer>, Comparable<?>> getFnOwnedCompare() {
return fnOwnedCompare;

View File

@@ -19,7 +19,6 @@ package forge.gamemodes.quest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
@@ -145,11 +144,11 @@ public class QuestUtilUnlockSets {
List<CardEdition> options = new ArrayList<>();
// Sort current sets by date
List<CardEdition> allowedSets = Lists.newArrayList(Iterables.transform(qData.getFormat().getAllowedSetCodes(), FModel.getMagicDb().getEditions().FN_EDITION_BY_CODE));
List<CardEdition> allowedSets = Lists.newArrayList(Iterables.transform(qData.getFormat().getAllowedSetCodes(), FModel.getMagicDb().getEditions()::get));
Collections.sort(allowedSets);
// Sort unlockable sets by date
List<CardEdition> excludedSets = Lists.newArrayList(Iterables.transform(qData.getFormat().getLockedSets(), FModel.getMagicDb().getEditions().FN_EDITION_BY_CODE));
List<CardEdition> excludedSets = Lists.newArrayList(Iterables.transform(qData.getFormat().getLockedSets(), FModel.getMagicDb().getEditions()::get));
Collections.sort(excludedSets);
// get a number of sets between an excluded and any included set
@@ -168,12 +167,9 @@ public class QuestUtilUnlockSets {
}
// sort by distance, then by code desc
Collections.sort(excludedWithDistances, new Comparator<ImmutablePair<CardEdition, Long>>() {
@Override
public int compare(ImmutablePair<CardEdition, Long> o1, ImmutablePair<CardEdition, Long> o2) {
long delta = o2.right - o1.right;
return delta < 0 ? -1 : delta == 0 ? 0 : 1;
}
Collections.sort(excludedWithDistances, (o1, o2) -> {
long delta = o2.right - o1.right;
return delta < 0 ? -1 : delta == 0 ? 0 : 1;
});
for (ImmutablePair<CardEdition, Long> set : excludedWithDistances) {

View File

@@ -103,73 +103,70 @@ public class QuestWinLoseController {
}
//give controller a chance to run remaining logic on a separate thread
view.showRewards(new Runnable() {
@Override
public void run() {
if (isAnte) {
// Won/lost cards should already be calculated (even in a draw)
final GameOutcome.AnteResult anteResult = lastGame.getAnteResult(questPlayer);
if (anteResult != null) {
if (anteResult.wonCards != null) {
qc.getCards().addAllCards(anteResult.wonCards);
}
if (anteResult.lostCards != null) {
qc.getCards().loseCards(anteResult.lostCards);
}
anteReport(anteResult.wonCards, anteResult.lostCards);
view.showRewards(() -> {
if (isAnte) {
// Won/lost cards should already be calculated (even in a draw)
final GameOutcome.AnteResult anteResult = lastGame.getAnteResult(questPlayer);
if (anteResult != null) {
if (anteResult.wonCards != null) {
qc.getCards().addAllCards(anteResult.wonCards);
}
if (anteResult.lostCards != null) {
qc.getCards().loseCards(anteResult.lostCards);
}
anteReport(anteResult.wonCards, anteResult.lostCards);
}
}
if (matchIsNotOver) { return; } //skip remaining logic if match isn't over yet
// TODO: We don't have a enum for difficulty?
final int difficulty = qData.getAchievements().getDifficulty();
final int wins = qData.getAchievements().getWin();
// Win case
if (wonMatch) {
// Standard event reward credits
awardEventCredits();
// Challenge reward credits
if (qEvent instanceof QuestEventChallenge) {
awardChallengeWin();
}
if (matchIsNotOver) { return; } //skip remaining logic if match isn't over yet
// TODO: We don't have a enum for difficulty?
final int difficulty = qData.getAchievements().getDifficulty();
final int wins = qData.getAchievements().getWin();
// Win case
if (wonMatch) {
// Standard event reward credits
awardEventCredits();
// Challenge reward credits
if (qEvent instanceof QuestEventChallenge) {
awardChallengeWin();
}
else {
awardSpecialReward("Special bonus reward"); // If any
// Random rare for winning against a very hard deck
if (qEvent.getDifficulty() == QuestEventDifficulty.EXPERT) {
awardRandomRare("You've won a random rare for winning against a very hard deck.");
}
}
awardWinStreakBonus();
// Random rare given at 50% chance (65% with luck upgrade)
if (getLuckyCoinResult()) {
awardRandomRare("You've won a random rare.");
}
// Award jackpot every 80 games won (currently 10 rares)
if ((wins > 0) && (((wins + 1) % 80) == 0)) {
awardJackpot();
}
}
// Lose case
else {
penalizeLoss();
awardSpecialReward("Special bonus reward"); // If any
// Random rare for winning against a very hard deck
if (qEvent.getDifficulty() == QuestEventDifficulty.EXPERT) {
awardRandomRare("You've won a random rare for winning against a very hard deck.");
}
}
// Grant booster on a win, or on a loss in easy mode
if (wonMatch || difficulty == 0) {
final int outcome = wonMatch ? wins : qData.getAchievements().getLost();
final int winsPerBooster = FModel.getQuestPreferences().getPrefInt(DifficultyPrefs.WINS_BOOSTER, qData.getAchievements().getDifficulty());
if (winsPerBooster > 0 && (outcome + 1) % winsPerBooster == 0) {
awardBooster();
}
awardWinStreakBonus();
// Random rare given at 50% chance (65% with luck upgrade)
if (getLuckyCoinResult()) {
awardRandomRare("You've won a random rare.");
}
// Award jackpot every 80 games won (currently 10 rares)
if ((wins > 0) && (((wins + 1) % 80) == 0)) {
awardJackpot();
}
}
// Lose case
else {
penalizeLoss();
}
// Grant booster on a win, or on a loss in easy mode
if (wonMatch || difficulty == 0) {
final int outcome = wonMatch ? wins : qData.getAchievements().getLost();
final int winsPerBooster = FModel.getQuestPreferences().getPrefInt(DifficultyPrefs.WINS_BOOSTER, qData.getAchievements().getDifficulty());
if (winsPerBooster > 0 && (outcome + 1) % winsPerBooster == 0) {
awardBooster();
}
}
});

View File

@@ -24,8 +24,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.common.base.Function;
import forge.card.CardEdition;
import forge.deck.Deck;
import forge.game.GameFormat;
@@ -124,13 +122,6 @@ public class QuestWorld implements Comparable<QuestWorld>{
return this.getName();
}
public static final Function<QuestWorld, String> FN_GET_NAME = new Function<QuestWorld, String>() {
@Override
public String apply(QuestWorld arg1) {
return arg1.getName();
}
};
/**
* Class for reading world definitions.
*/
@@ -141,7 +132,7 @@ public class QuestWorld implements Comparable<QuestWorld>{
* @param file0
*/
public Reader(String file0) {
super(file0, QuestWorld.FN_GET_NAME);
super(file0, QuestWorld::getName);
}
/* (non-Javadoc)

View File

@@ -34,7 +34,7 @@ public class MainWorldDuelReader extends StorageReaderFolder<QuestEventDuel> {
private static final String WILD_DIR_NAME = "wild";
public MainWorldDuelReader(File deckDir0) {
super(deckDir0, QuestEvent.FN_GET_NAME);
super(deckDir0, QuestEvent::getName);
}
@Override

View File

@@ -18,7 +18,7 @@ import forge.util.storage.StorageReaderFolder;
public class QuestChallengeReader extends StorageReaderFolder<QuestEventChallenge> {
public QuestChallengeReader(File deckDir0) {
super(deckDir0, QuestEventChallenge.FN_GET_ID);
super(deckDir0, QuestEventChallenge::getId);
// TODO Auto-generated constructor stub
}

View File

@@ -907,26 +907,26 @@ public class QuestDataIO {
protected BoosterPack readBooster(final HierarchicalStreamReader reader) {
String s = reader.getAttribute("s");
if (SealedProduct.specialSets.contains(s) || s.equals("?")) {
return BoosterPack.FN_FROM_COLOR.apply(s);
return BoosterPack.fromColor(s);
} else {
final CardEdition ed = FModel.getMagicDb().getEditions().get(s);
return BoosterPack.FN_FROM_SET.apply(ed);
return BoosterPack.fromSet(ed);
}
}
protected TournamentPack readTournamentPack(final HierarchicalStreamReader reader) {
final CardEdition ed = FModel.getMagicDb().getEditions().get(reader.getAttribute("s"));
return TournamentPack.FN_FROM_SET.apply(ed);
return TournamentPack.fromSet(ed);
}
protected FatPack readFatPack(final HierarchicalStreamReader reader) {
final CardEdition ed = FModel.getMagicDb().getEditions().get(reader.getAttribute("s"));
return FatPack.FN_FROM_SET.apply(ed);
return FatPack.fromSet(ed);
}
protected BoosterBox readBoosterBox(final HierarchicalStreamReader reader) {
final CardEdition ed = FModel.getMagicDb().getEditions().get(reader.getAttribute("s"));
return BoosterBox.FN_FROM_SET.apply(ed);
return BoosterBox.fromSet(ed);
}
protected PaperCard readCardPrinted(final HierarchicalStreamReader reader) {

View File

@@ -17,7 +17,7 @@ import forge.util.storage.StorageReaderFolder;
public class QuestDuelReader extends StorageReaderFolder<QuestEventDuel> {
public QuestDuelReader(File deckDir0) {
super(deckDir0, QuestEvent.FN_GET_NAME);
super(deckDir0, QuestEvent::getName);
// TODO Auto-generated constructor stub
}

View File

@@ -64,24 +64,14 @@ public class TournamentIO {
}
public static File[] getTournamentFilesUnlocked(final String prefix) {
final FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return ((prefix == null || name.startsWith(prefix)) && name.endsWith(SUFFIX_DATA));
}
};
final FilenameFilter filter = (dir, name) -> ((prefix == null || name.startsWith(prefix)) && name.endsWith(SUFFIX_DATA));
final File folder = new File(ForgeConstants.TOURNAMENT_DIR.userPrefLoc);
return folder.listFiles(filter);
}
public static File[] getTournamentFilesLocked() {
final FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return (name.startsWith(PREFIX_LOCKED) && name.endsWith(SUFFIX_DATA));
}
};
final FilenameFilter filter = (dir, name) -> (name.startsWith(PREFIX_LOCKED) && name.endsWith(SUFFIX_DATA));
final File folder = new File(ForgeConstants.TOURNAMENT_DIR.defaultLoc);
return folder.listFiles(filter);

View File

@@ -3,7 +3,6 @@ package forge.gamemodes.tournament.system;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.google.common.collect.Lists;
@@ -108,26 +107,11 @@ public abstract class AbstractTournament implements Serializable {
public void sortAllPlayers(String sortType) {
if (sortType.equals("score")) {
Collections.sort(allPlayers, new Comparator<TournamentPlayer>() {
@Override
public int compare(TournamentPlayer o1, TournamentPlayer o2) {
return o2.getScore() - o1.getScore();
}
});
Collections.sort(allPlayers, (o1, o2) -> o2.getScore() - o1.getScore());
} else if (sortType.equals("index")) {
Collections.sort(allPlayers, new Comparator<TournamentPlayer>() {
@Override
public int compare(TournamentPlayer o1, TournamentPlayer o2) {
return o2.getIndex() - o1.getIndex();
}
});
Collections.sort(allPlayers, (o1, o2) -> o2.getIndex() - o1.getIndex());
} else if (sortType.equals("swiss")) {
Collections.sort(allPlayers, new Comparator<TournamentPlayer>() {
@Override
public int compare(TournamentPlayer o1, TournamentPlayer o2) {
return o2.getSwissScore() - o1.getSwissScore();
}
});
Collections.sort(allPlayers, (o1, o2) -> o2.getSwissScore() - o1.getSwissScore());
}
}

View File

@@ -134,12 +134,7 @@ public class TournamentSwiss extends AbstractTournament {
return pairSwissGroup(players);
}
Collections.sort(players, new Comparator<TournamentPlayer>() {
@Override
public int compare(TournamentPlayer o1, TournamentPlayer o2) {
return availableOpponents.get(o1).size() - availableOpponents.get(o2).size();
}
});
Collections.sort(players, Comparator.comparingInt(o -> availableOpponents.get(o).size()));
while (players.size() > 1) {
TournamentPlayer initialPlayer = players.get(0);

View File

@@ -63,12 +63,7 @@ public class FThreads {
}
public static void delayInEDT(final int milliseconds, final Runnable inputUpdater) {
final Runnable runInEdt = new Runnable() {
@Override
public void run() {
FThreads.invokeInEdtNowOrLater(inputUpdater);
}
};
final Runnable runInEdt = () -> FThreads.invokeInEdtNowOrLater(inputUpdater);
ThreadUtil.delay(milliseconds, runInEdt);
}

View File

@@ -345,11 +345,8 @@ public final class CardScriptParser {
}
}
private static final Predicate<String> startsWith(final String s) {
return new Predicate<String>() {
@Override public boolean apply(final String input) {
return s.startsWith(input);
}};
private static Predicate<String> startsWith(final String s) {
return s::startsWith;
}
/**

View File

@@ -131,12 +131,7 @@ public class FControlGamePlayback extends IGameEventVisitor.Base<Void> {
@Override
public Void visit(final GameEventSpellResolved event) {
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override
public void run() {
humanController.getGui().setCard(CardView.get(event.spell.getHostCard()));
}
});
FThreads.invokeInEdtNowOrLater(() -> humanController.getGui().setCard(CardView.get(event.spell.getHostCard())));
pauseForEvent(resolveDelay);
return null;
}
@@ -146,12 +141,7 @@ public class FControlGamePlayback extends IGameEventVisitor.Base<Void> {
*/
@Override
public Void visit(final GameEventSpellAbilityCast event) {
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override
public void run() {
humanController.getGui().setCard(CardView.get(event.sa.getHostCard()));
}
});
FThreads.invokeInEdtNowOrLater(() -> humanController.getGui().setCard(CardView.get(event.sa.getHostCard())));
pauseForEvent(castDelay);
return null;
}
@@ -183,15 +173,12 @@ public class FControlGamePlayback extends IGameEventVisitor.Base<Void> {
private void releaseGameThread() {
// just need to run another thread through the barrier... not edt preferrably :)
getGame().getAction().invoke(new Runnable() {
@Override
public void run() {
try {
gameThreadPauser.await();
} catch (final InterruptedException | BrokenBarrierException e) {
// Auto-generated catch block ignores the exception, but sends it to System.err and probably forge.log.
e.printStackTrace();
}
getGame().getAction().invoke(() -> {
try {
gameThreadPauser.await();
} catch (final InterruptedException | BrokenBarrierException e) {
// Auto-generated catch block ignores the exception, but sends it to System.err and probably forge.log.
e.printStackTrace();
}
});
}

View File

@@ -102,25 +102,19 @@ public abstract class GuiDownloadService implements Runnable {
String startOverrideDesc = getStartOverrideDesc();
if (startOverrideDesc == null) {
// Free up the EDT by assembling card list on a background thread
FThreads.invokeInBackgroundThread(new Runnable() {
@Override
public void run() {
try {
files = getNeededFiles();
}
catch (Exception e) {
e.printStackTrace();
}
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
if (onReadyToStart != null) {
onReadyToStart.run();
}
readyToStart();
}
});
FThreads.invokeInBackgroundThread(() -> {
try {
files = getNeededFiles();
}
catch (Exception e) {
e.printStackTrace();
}
FThreads.invokeInEdtLater(() -> {
if (onReadyToStart != null) {
onReadyToStart.run();
}
readyToStart();
});
});
} else {
//handle special case of zip service
@@ -131,12 +125,7 @@ public abstract class GuiDownloadService implements Runnable {
btnStart.setCommand(cmdStartDownload);
btnStart.setEnabled(true);
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
btnStart.requestFocusInWindow();
}
});
FThreads.invokeInEdtLater(() -> btnStart.requestFocusInWindow());
}
}
@@ -161,12 +150,7 @@ public abstract class GuiDownloadService implements Runnable {
}
btnStart.setEnabled(true);
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
btnStart.requestFocusInWindow();
}
});
FThreads.invokeInEdtLater(() -> btnStart.requestFocusInWindow());
}
public void setType(int type0) {
@@ -200,43 +184,40 @@ public abstract class GuiDownloadService implements Runnable {
}
private void update(final int count) {
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
if (onUpdate != null) {
onUpdate.run();
}
final StringBuilder sb = new StringBuilder();
final int a = getAverageTimePerObject();
if (count != files.size()) {
sb.append(count).append("/").append(files.size()).append(" - ");
long t2Go = (files.size() - count) * a;
if (t2Go > 3600000) {
sb.append(String.format("%02d:", t2Go / 3600000));
t2Go = t2Go % 3600000;
}
if (t2Go > 60000) {
sb.append(String.format("%02d:", t2Go / 60000));
t2Go = t2Go % 60000;
} else {
sb.append("00:");
}
sb.append(String.format("%02d remaining.", t2Go / 1000));
} else {
sb.append(String.format("%d of %d items finished! Skipped " + skipped + " items. Please close!",
count, files.size()));
finish();
}
progressBar.setValue(count);
progressBar.setDescription(sb.toString());
FThreads.invokeInEdtLater(() -> {
if (onUpdate != null) {
onUpdate.run();
}
final StringBuilder sb = new StringBuilder();
final int a = getAverageTimePerObject();
if (count != files.size()) {
sb.append(count).append("/").append(files.size()).append(" - ");
long t2Go = (files.size() - count) * a;
if (t2Go > 3600000) {
sb.append(String.format("%02d:", t2Go / 3600000));
t2Go = t2Go % 3600000;
}
if (t2Go > 60000) {
sb.append(String.format("%02d:", t2Go / 60000));
t2Go = t2Go % 60000;
} else {
sb.append("00:");
}
sb.append(String.format("%02d remaining.", t2Go / 1000));
} else {
sb.append(String.format("%d of %d items finished! Skipped " + skipped + " items. Please close!",
count, files.size()));
finish();
}
progressBar.setValue(count);
progressBar.setDescription(sb.toString());
});
}

View File

@@ -57,13 +57,10 @@ public class GuiDownloadZipService extends GuiDownloadService {
public final void run() {
downloadAndUnzip();
if (!cancel) {
FThreads.invokeInEdtNowOrLater(new Runnable() {
@Override
public void run() {
if (progressBar != null)
progressBar.setDescription(filesExtracted + " " + desc + " extracted");
finish();
}
FThreads.invokeInEdtNowOrLater(() -> {
if (progressBar != null)
progressBar.setDescription(filesExtracted + " " + desc + " extracted");
finish();
});
}
}

View File

@@ -116,7 +116,7 @@ public class AdvancedSearch {
return Keyword.getKeywordSet(input);
}
}),
CARD_SET("lblSet", PaperCard.class, FilterOperator.SINGLE_LIST_OPS, new CustomListEvaluator<PaperCard, CardEdition>(FModel.getMagicDb().getSortedEditions(), CardEdition.FN_GET_CODE) {
CARD_SET("lblSet", PaperCard.class, FilterOperator.SINGLE_LIST_OPS, new CustomListEvaluator<PaperCard, CardEdition>(FModel.getMagicDb().getSortedEditions(), CardEdition::getCode) {
@Override
protected CardEdition getItemValue(PaperCard input) {
return FModel.getMagicDb().getCardEdition(input.getEdition());
@@ -285,7 +285,7 @@ public class AdvancedSearch {
return input.getRules().getManaCost().toString();
}
}),
CARD_RARITY("lblRarity", PaperCard.class, FilterOperator.SINGLE_LIST_OPS, new CustomListEvaluator<PaperCard, CardRarity>(Arrays.asList(CardRarity.FILTER_OPTIONS), CardRarity.FN_GET_LONG_NAME, CardRarity.FN_GET_LONG_NAME) {
CARD_RARITY("lblRarity", PaperCard.class, FilterOperator.SINGLE_LIST_OPS, new CustomListEvaluator<PaperCard, CardRarity>(Arrays.asList(CardRarity.FILTER_OPTIONS), CardRarity::getLongName, CardRarity::getLongName) {
@Override
protected CardRarity getItemValue(PaperCard input) {
return input.getRarity();
@@ -335,7 +335,7 @@ public class AdvancedSearch {
return Keyword.getKeywordSet((PaperCard)input);
}
}),
INVITEM_SET("lblSet", InventoryItem.class, FilterOperator.SINGLE_LIST_OPS, new CustomListEvaluator<InventoryItem, CardEdition>(FModel.getMagicDb().getSortedEditions(), CardEdition.FN_GET_CODE) {
INVITEM_SET("lblSet", InventoryItem.class, FilterOperator.SINGLE_LIST_OPS, new CustomListEvaluator<InventoryItem, CardEdition>(FModel.getMagicDb().getSortedEditions(), CardEdition::getCode) {
@Override
protected CardEdition getItemValue(InventoryItem input) {
if (input instanceof PaperCard) {
@@ -532,7 +532,7 @@ public class AdvancedSearch {
return cards.get(0) == input;
}
}),
INVITEM_RARITY("lblRarity", InventoryItem.class, FilterOperator.SINGLE_LIST_OPS, new CustomListEvaluator<InventoryItem, CardRarity>(Arrays.asList(CardRarity.FILTER_OPTIONS), CardRarity.FN_GET_LONG_NAME, CardRarity.FN_GET_LONG_NAME) {
INVITEM_RARITY("lblRarity", InventoryItem.class, FilterOperator.SINGLE_LIST_OPS, new CustomListEvaluator<InventoryItem, CardRarity>(Arrays.asList(CardRarity.FILTER_OPTIONS), CardRarity::getLongName, CardRarity::getLongName) {
@Override
protected CardRarity getItemValue(InventoryItem input) {
if (!(input instanceof PaperCard)) {
@@ -1103,23 +1103,13 @@ public class AdvancedSearch {
String caption = getCaption(values, option, operator);
final OperatorEvaluator<V> evaluator = (OperatorEvaluator<V>) operator.evaluator;
Predicate<T> predicate = new Predicate<T>() {
@Override
public boolean apply(T input) {
return evaluator.apply(getItemValue(input), values);
}
};
Predicate<T> predicate = input -> evaluator.apply(getItemValue(input), values);
final FilterOperator[][] manyValueOperators = { FilterOperator.MULTI_LIST_OPS,
FilterOperator.COMBINATION_OPS, FilterOperator.COLLECTION_OPS, FilterOperator.STRINGS_OPS };
for (FilterOperator[] oper : manyValueOperators) {
if (option.operatorOptions == oper) {
predicate = new Predicate<T>() {
@Override
public boolean apply(T input) {
return evaluator.apply(getItemValues(input), values);
}
};
predicate = input -> evaluator.apply(getItemValues(input), values);
break;
}
}
@@ -1340,7 +1330,7 @@ public class AdvancedSearch {
private static abstract class ColorEvaluator<T extends InventoryItem> extends CustomListEvaluator<T, MagicColor.Color> {
public ColorEvaluator() {
super(Arrays.asList(MagicColor.Color.values()), MagicColor.FN_GET_SYMBOL);
super(Arrays.asList(MagicColor.Color.values()), MagicColor.Color::getSymbol);
}
@Override
@@ -1615,12 +1605,7 @@ public class AdvancedSearch {
@SuppressWarnings("serial")
public void addFilterControl(final IFilterControl<T> control) {
control.getBtnFilter().setText(EMPTY_FILTER_TEXT);
control.getBtnFilter().setCommand(new UiCommand() {
@Override
public void run() {
editFilterControl(control, null);
}
});
control.getBtnFilter().setCommand((UiCommand) () -> editFilterControl(control, null));
controls.add(control);
}
@@ -1635,35 +1620,29 @@ public class AdvancedSearch {
}
public void editFilterControl(final IFilterControl<T> control, final Runnable onChange) {
FThreads.invokeInBackgroundThread(new Runnable() {
@Override
public void run() {
final Filter<T> filter = getFilter(control.getGenericType(), control.getFilter(), onChange == null); //reselect option if no change handler passed
if (control.getFilter() != filter) {
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
control.setFilter(filter);
if (filter != null) {
control.getBtnFilter().setText(GuiBase.getInterface().encodeSymbols(filter.toString(), false));
FThreads.invokeInBackgroundThread(() -> {
final Filter<T> filter = getFilter(control.getGenericType(), control.getFilter(), onChange == null); //reselect option if no change handler passed
if (control.getFilter() != filter) {
FThreads.invokeInEdtLater(() -> {
control.setFilter(filter);
if (filter != null) {
control.getBtnFilter().setText(GuiBase.getInterface().encodeSymbols(filter.toString(), false));
if (filter.getOption() == FilterOption.CARD_KEYWORDS) {
//the first time the user selects keywords, preload keywords for all cards
Runnable preloadTask = Keyword.getPreloadTask();
if (preloadTask != null) {
GuiBase.getInterface().runBackgroundTask(Localizer.getInstance().getMessage("lblLoadingKeywords"), preloadTask);
}
}
}
else {
control.getBtnFilter().setText(EMPTY_FILTER_TEXT);
}
if (onChange != null) {
onChange.run();
if (filter.getOption() == FilterOption.CARD_KEYWORDS) {
//the first time the user selects keywords, preload keywords for all cards
Runnable preloadTask = Keyword.getPreloadTask();
if (preloadTask != null) {
GuiBase.getInterface().runBackgroundTask(Localizer.getInstance().getMessage("lblLoadingKeywords"), preloadTask);
}
}
});
}
}
else {
control.getBtnFilter().setText(EMPTY_FILTER_TEXT);
}
if (onChange != null) {
onChange.run();
}
});
}
});
}

View File

@@ -49,155 +49,70 @@ public enum ColumnDef {
* The column containing the inventory item name.
*/
STRING("", "", 0, false, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return from.getKey() instanceof Comparable<?> ? (Comparable<?>) from.getKey() : from.getKey().getName();
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return from.getKey().toString();
}
}),
from -> from.getKey() instanceof Comparable<?> ? (Comparable<?>) from.getKey() : from.getKey().getName(),
from -> from.getKey().toString()),
/**
* The name column.
*/
NAME("lblName", "lblName", 180, false, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
if (from.getKey() instanceof PaperCard) {
String sortableName = ((PaperCard)from.getKey()).getSortableName();
return sortableName == null ? TextUtil.toSortableName(from.getKey().getName()) : sortableName;
}
return TextUtil.toSortableName(from.getKey().getName());
from -> {
if (from.getKey() instanceof PaperCard) {
String sortableName = ((PaperCard)from.getKey()).getSortableName();
return sortableName == null ? TextUtil.toSortableName(from.getKey().getName()) : sortableName;
}
return TextUtil.toSortableName(from.getKey().getName());
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
if (from.getKey() instanceof PaperCard)
return from.getKey().toString();
return from.getKey().getName();
}
from -> {
if (from.getKey() instanceof PaperCard)
return from.getKey().toString();
return from.getKey().getName();
}),
/**
* The column for sorting cards in collector order.
*/
COLLECTOR_ORDER("lblCN", "ttCN", 20, false, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toCollectorPrefix(from.getKey());
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
InventoryItem item = from.getKey();
return item instanceof PaperCard ?
((PaperCard) item).getCollectorNumber() : IPaperCard.NO_COLLECTOR_NUMBER;
}
from -> toCollectorPrefix(from.getKey()),
from -> {
InventoryItem item = from.getKey();
return item instanceof PaperCard ? ((PaperCard) item).getCollectorNumber() : IPaperCard.NO_COLLECTOR_NUMBER;
}),
/**
* The type column.
*/
TYPE("lblType", "ttType", 100, false, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return CardTranslation.getTranslatedType(from.getKey().getName(), toType(from.getKey()));
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return CardTranslation.getTranslatedType(from.getKey().getName(), toType(from.getKey()));
}
}),
from -> CardTranslation.getTranslatedType(from.getKey().getName(), toType(from.getKey())),
from -> CardTranslation.getTranslatedType(from.getKey().getName(), toType(from.getKey()))),
/**
* The mana cost column.
*/
COST("lblCost", "ttCost", 70, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toManaCost(from.getKey());
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toCardRules(from.getKey());
}
}),
from -> toManaCost(from.getKey()),
from -> toCardRules(from.getKey())),
/**
* The color column.
*/
COLOR("lblColor", "ttColor", 46, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toColor(from.getKey());
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toColor(from.getKey());
}
}),
from -> toColor(from.getKey()),
from -> toColor(from.getKey())),
/**
* The power column.
*/
POWER("lblPower", "ttPower", 20, true, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toPower(from.getKey());
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toPower(from.getKey());
}
}),
from -> toPower(from.getKey()),
from -> toPower(from.getKey())),
/**
* The toughness column.
*/
TOUGHNESS("lblToughness", "ttToughness", 20, true, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toToughness(from.getKey());
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toToughness(from.getKey());
}
}),
from -> toToughness(from.getKey()),
from -> toToughness(from.getKey())),
/**
* The converted mana cost column.
*/
CMC("lblCMC", "ttCMC", 20, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toCMC(from.getKey());
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toCMC(from.getKey());
}
}),
from -> toCMC(from.getKey()),
from -> toCMC(from.getKey())),
ATTRACTION_LIGHTS("lblLights", "lblLights", 94, true, SortState.NONE,
from -> toAttractionLightSort(from.getKey()),
from -> toAttractionLights(from.getKey())
@@ -206,153 +121,93 @@ public enum ColumnDef {
* The rarity column.
*/
RARITY("lblRarity", "lblRarity", 20, true, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toRarity(from.getKey());
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toRarity(from.getKey());
}
}),
from -> toRarity(from.getKey()),
from -> toRarity(from.getKey())),
/**
* The set code column.
*/
SET("lblSet", "lblSet", 38, true, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
InventoryItem i = from.getKey();
if (!(i instanceof InventoryItemFromSet))
return CardEdition.UNKNOWN;
String editionCode = ((InventoryItemFromSet) i).getEdition();
return FModel.getMagicDb().getCardEdition(editionCode);
}
from -> {
InventoryItem i = from.getKey();
if (!(i instanceof InventoryItemFromSet))
return CardEdition.UNKNOWN;
String editionCode = ((InventoryItemFromSet) i).getEdition();
return FModel.getMagicDb().getCardEdition(editionCode);
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
InventoryItem i = from.getKey();
return i instanceof InventoryItemFromSet ? ((InventoryItemFromSet) i).getEdition() : "n/a";
}
from -> {
InventoryItem i = from.getKey();
return i instanceof InventoryItemFromSet ? ((InventoryItemFromSet) i).getEdition() : "n/a";
}),
/**
* The AI compatibility flag column
*/
AI("lblAI", "lblAIStatus", 30, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
InventoryItem i = from.getKey();
return i instanceof PaperCard ? ((IPaperCard) i).getRules().getAiHints().getAiStatusComparable() : Integer.valueOf(-1);
}
from -> {
InventoryItem i = from.getKey();
return i instanceof PaperCard ? ((IPaperCard) i).getRules().getAiHints().getAiStatusComparable() : Integer.valueOf(-1);
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
InventoryItem i = from.getKey();
if (!(i instanceof PaperCard)) {
return "n/a";
}
IPaperCard cp = (IPaperCard) i;
CardAiHints ai = cp.getRules().getAiHints();
return ai.getRemAIDecks() ? (ai.getRemRandomDecks() ? "X?" : "X")
: (ai.getRemRandomDecks() ? "?" : "");
from -> {
InventoryItem i = from.getKey();
if (!(i instanceof PaperCard)) {
return "n/a";
}
IPaperCard cp = (IPaperCard) i;
CardAiHints ai = cp.getRules().getAiHints();
return ai.getRemAIDecks() ? (ai.getRemRandomDecks() ? "X?" : "X")
: (ai.getRemRandomDecks() ? "?" : "");
}),
/**
* The card format column.
*/
FORMAT("lblFormat", "ttFormats", 60, false, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
PaperCard card = toPaperCard(from.getKey());
if (card == null) {
return -1;
}
Iterable<GameFormat> formats = FModel.getFormats().getAllFormatsOfCard(card);
int acc = 0;
for (GameFormat gf : formats) {
if (!gf.getFormatType().equals(GameFormat.FormatType.SANCTIONED)) {
continue;
}
int ix = gf.getIndex();
if (ix < 30 && ix > 0)
acc |= 0x40000000 >> (ix - 1);
}
return acc;
from -> {
PaperCard card = toPaperCard(from.getKey());
if (card == null) {
return -1;
}
Iterable<GameFormat> formats = FModel.getFormats().getAllFormatsOfCard(card);
int acc = 0;
for (GameFormat gf : formats) {
if (!gf.getFormatType().equals(GameFormat.FormatType.SANCTIONED)) {
continue;
}
int ix = gf.getIndex();
if (ix < 30 && ix > 0)
acc |= 0x40000000 >> (ix - 1);
}
return acc;
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
PaperCard card = toPaperCard(from.getKey());
if (card == null) {
return -1;
}
Iterable<GameFormat> formats = FModel.getFormats().getAllFormatsOfCard(card);
Set<GameFormat> sanctioned = new HashSet<>();
for (GameFormat gf : formats) {
if (gf.getFormatType().equals(GameFormat.FormatType.SANCTIONED)) {
sanctioned.add(gf);
}
}
return StringUtils.join(Iterables.transform(sanctioned, GameFormat.FN_GET_NAME), ", ");
from -> {
PaperCard card = toPaperCard(from.getKey());
if (card == null) {
return -1;
}
Iterable<GameFormat> formats = FModel.getFormats().getAllFormatsOfCard(card);
Set<GameFormat> sanctioned = new HashSet<>();
for (GameFormat gf : formats) {
if (gf.getFormatType().equals(GameFormat.FormatType.SANCTIONED)) {
sanctioned.add(gf);
}
}
return StringUtils.join(Iterables.transform(sanctioned, GameFormat::getName), ", ");
}),
/**
* The Draft ranking column.
*/
RANKING("lblRanking", "lblDraftRanking", 50, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toRanking(from.getKey(), false);
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toRanking(from.getKey(), true);
}
}),
from -> toRanking(from.getKey(), false),
from -> toRanking(from.getKey(), true)),
/**
* The quantity column.
*/
QUANTITY("lblQty", "lblQuantity", 25, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return from.getValue();
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return from.getValue();
}
}),
Entry::getValue, Entry::getValue),
/**
* The quantity in deck column.
*/
DECK_QUANTITY("lblQuantity", "lblQuantity", 50, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return from.getValue();
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return from.getValue();
}
}),
Entry::getValue, Entry::getValue),
/**
* The new inventory flag column.
*/
@@ -377,185 +232,95 @@ public enum ColumnDef {
* The favorite flag column.
*/
FAVORITE("", "ttFavorite", 18, true, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
IPaperCard card = toCard(from.getKey());
if (card == null) {
return -1;
}
return CardPreferences.getPrefs(card).getStarCount();
from -> {
IPaperCard card = toCard(from.getKey());
if (card == null) {
return -1;
}
return CardPreferences.getPrefs(card).getStarCount();
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toCard(from.getKey());
}
}),
from -> toCard(from.getKey())),
/**
* The favorite deck flag column.
*/
DECK_FAVORITE("", "ttFavorite", 18, true, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
DeckProxy deck = toDeck(from.getKey());
if (deck == null) {
return -1;
}
return DeckPreferences.getPrefs(deck).getStarCount();
from -> {
DeckProxy deck = toDeck(from.getKey());
if (deck == null) {
return -1;
}
return DeckPreferences.getPrefs(deck).getStarCount();
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toDeck(from.getKey());
}
}),
from -> toDeck(from.getKey())),
/**
* The edit/delete deck column.
*/
DECK_ACTIONS("", "lblDeleteEdit", 40, true, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return 0;
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toDeck(from.getKey());
}
}),
from -> 0,
from -> toDeck(from.getKey())),
/**
* The deck folder column.
*/
DECK_FOLDER("lblFolder", "lblFolder", 80, false, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toDeckFolder(from.getKey());
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toDeckFolder(from.getKey());
}
}),
from -> toDeckFolder(from.getKey()),
from -> toDeckFolder(from.getKey())),
/**
* The deck color column.
*/
DECK_COLOR("lblColor", "ttColor", 70, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toDeckColor(from.getKey());
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toDeckColor(from.getKey());
}
}),
from -> toDeckColor(from.getKey()),
from -> toDeckColor(from.getKey())),
/**
* The deck format column.
*/
DECK_FORMAT("lblFormat", "ttFormats", 60, false, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
DeckProxy deck = toDeck(from.getKey());
if (deck == null) {
return -1;
}
Iterable<GameFormat> all = deck.getExhaustiveFormats();
int acc = 0;
for (GameFormat gf : all) {
int ix = gf.getIndex();
if (ix < 30 && ix > 0)
acc |= 0x40000000 >> (ix - 1);
}
return acc;
from -> {
DeckProxy deck = toDeck(from.getKey());
if (deck == null) {
return -1;
}
Iterable<GameFormat> all = deck.getExhaustiveFormats();
int acc = 0;
for (GameFormat gf : all) {
int ix = gf.getIndex();
if (ix < 30 && ix > 0)
acc |= 0x40000000 >> (ix - 1);
}
return acc;
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
DeckProxy deck = toDeck(from.getKey());
if (deck == null) {
return null;
}
return deck.getFormatsString();
from -> {
DeckProxy deck = toDeck(from.getKey());
if (deck == null) {
return null;
}
return deck.getFormatsString();
}),
/**
* The deck edition column, a mystery to us all.
*/
DECK_EDITION("lblSet", "lblSet", 38, true, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toDeck(from.getKey()).getEdition();
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
CardEdition deckEdition = toDeck(from.getKey()).getEdition();
if (deckEdition != null)
return deckEdition.getCode();
return null;
}
from -> toDeck(from.getKey()).getEdition(),
from -> {
CardEdition deckEdition = toDeck(from.getKey()).getEdition();
if (deckEdition != null)
return deckEdition.getCode();
return null;
}),
DECK_AI("lblAI", "lblAIStatus", 38, true, SortState.DESC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toDeck(from.getKey()).getAI().inMainDeck;
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toDeck(from.getKey()).getAI();
}
}),
from -> toDeck(from.getKey()).getAI().inMainDeck,
from -> toDeck(from.getKey()).getAI()),
/**
* The main library size column.
*/
DECK_MAIN("lblMain", "ttMain", 30, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toDeck(from.getKey()).getMainSize();
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toDeck(from.getKey()).getMainSize();
}
}),
from -> toDeck(from.getKey()).getMainSize(),
from -> toDeck(from.getKey()).getMainSize()),
/**
* The sideboard size column.
*/
DECK_SIDE("lblSide", "lblSideboard", 30, true, SortState.ASC,
new Function<Entry<InventoryItem, Integer>, Comparable<?>>() {
@Override
public Comparable<?> apply(final Entry<InventoryItem, Integer> from) {
return toDeck(from.getKey()).getSideSize();
}
},
new Function<Entry<? extends InventoryItem, Integer>, Object>() {
@Override
public Object apply(final Entry<? extends InventoryItem, Integer> from) {
return toDeck(from.getKey()).getSideSize();
}
});
from -> toDeck(from.getKey()).getSideSize(),
from -> toDeck(from.getKey()).getSideSize());
ColumnDef(String shortName0, String longName0, int preferredWidth0, boolean isWidthFixed0, SortState sortState0,
Function<Entry<InventoryItem, Integer>, Comparable<?>> fnSort0,

View File

@@ -19,195 +19,143 @@ import forge.util.Localizer;
public enum GroupDef {
COLOR("lblColor", getColorGroups(),
new Function<Integer, ColumnDef>() {
@Override
public ColumnDef apply(final Integer groupIndex) {
return null;
groupIndex -> null,
item -> {
if (item instanceof PaperCard) {
return getColorGroup(((PaperCard) item).getRules().getColor());
}
},
new Function<InventoryItem, Integer>() {
@Override
public Integer apply(final InventoryItem item) {
if (item instanceof PaperCard) {
return getColorGroup(((PaperCard) item).getRules().getColor());
}
else if (item instanceof DeckProxy) {
return getColorGroup(((DeckProxy) item).getColor());
}
return -1;
else if (item instanceof DeckProxy) {
return getColorGroup(((DeckProxy) item).getColor());
}
return -1;
}),
COLOR_IDENTITY("lblColorIdentity", getColorGroups(),
new Function<Integer, ColumnDef>() {
@Override
public ColumnDef apply(final Integer groupIndex) {
return null;
groupIndex -> null,
item -> {
if (item instanceof PaperCard) {
return getColorGroup(((PaperCard) item).getRules().getColorIdentity());
}
},
new Function<InventoryItem, Integer>() {
@Override
public Integer apply(final InventoryItem item) {
if (item instanceof PaperCard) {
return getColorGroup(((PaperCard) item).getRules().getColorIdentity());
}
else if (item instanceof DeckProxy) {
return getColorGroup(((DeckProxy) item).getColorIdentity());
}
return -1;
else if (item instanceof DeckProxy) {
return getColorGroup(((DeckProxy) item).getColorIdentity());
}
return -1;
}),
SET("lblSet", getSetGroups(),
new Function<Integer, ColumnDef>() {
@Override
public ColumnDef apply(final Integer groupIndex) {
return null;
groupIndex -> null,
item -> {
if (item instanceof PaperCard) {
return getSetGroup(((PaperCard) item).getEdition());
}
},
new Function<InventoryItem, Integer>() {
@Override
public Integer apply(final InventoryItem item) {
if (item instanceof PaperCard) {
return getSetGroup(((PaperCard) item).getEdition());
}
else if (item instanceof DeckProxy) {
return getSetGroup(((DeckProxy) item).getEdition().getCode());
}
return -1;
else if (item instanceof DeckProxy) {
return getSetGroup(((DeckProxy) item).getEdition().getCode());
}
return -1;
}),
DEFAULT("lblDefault",
new String[] { "Creatures", "Spells", "Lands" },
new Function<Integer, ColumnDef>() {
@Override
public ColumnDef apply(final Integer groupIndex) {
if (groupIndex == 2) {
return ColumnDef.NAME; //pile lands by name regardless
}
return null;
groupIndex -> {
if (groupIndex == 2) {
return ColumnDef.NAME; //pile lands by name regardless
}
return null;
},
new Function<InventoryItem, Integer>() {
@Override
public Integer apply(final InventoryItem item) {
if (item instanceof PaperCard) {
CardType type = ((PaperCard) item).getRules().getType();
if (type.isCreature()) {
return 0;
}
if (type.isLand()) { //make Artifact Lands appear in Lands group
return 2;
}
if (type.isArtifact() || type.isEnchantment() || type.isPlaneswalker() || type.isInstant() || type.isSorcery() || type.isBattle()) {
return 1;
}
item -> {
if (item instanceof PaperCard) {
CardType type = ((PaperCard) item).getRules().getType();
if (type.isCreature()) {
return 0;
}
if (type.isLand()) { //make Artifact Lands appear in Lands group
return 2;
}
if (type.isArtifact() || type.isEnchantment() || type.isPlaneswalker() || type.isInstant() || type.isSorcery() || type.isBattle()) {
return 1;
}
return -1;
}
return -1;
}),
CARD_TYPE("lblType",
new String[] { "Planeswalker", "Creature", "Sorcery", "Instant", "Artifact", "Enchantment", "Land", "Battle" },
new Function<Integer, ColumnDef>() {
@Override
public ColumnDef apply(final Integer groupIndex) {
if (groupIndex == 6) {
return ColumnDef.NAME; //pile lands by name regardless
}
return null;
groupIndex -> {
if (groupIndex == 6) {
return ColumnDef.NAME; //pile lands by name regardless
}
return null;
},
new Function<InventoryItem, Integer>() {
@Override
public Integer apply(final InventoryItem item) {
if (item instanceof PaperCard) {
CardType type = ((PaperCard) item).getRules().getType();
if (type.isPlaneswalker()) {
return 0;
}
if (type.isCreature()) {
return 1;
}
if (type.isInstant()) {
return 3;
}
if (type.isSorcery()) {
return 2;
}
if (type.isArtifact()) {
return 4;
}
if (type.isEnchantment()) {
return 5;
}
if (type.isBattle()) {
return 7;
}
if (type.isLand()) {
return 6;
}
item -> {
if (item instanceof PaperCard) {
CardType type = ((PaperCard) item).getRules().getType();
if (type.isPlaneswalker()) {
return 0;
}
if (type.isCreature()) {
return 1;
}
if (type.isInstant()) {
return 3;
}
if (type.isSorcery()) {
return 2;
}
if (type.isArtifact()) {
return 4;
}
if (type.isEnchantment()) {
return 5;
}
if (type.isBattle()) {
return 7;
}
if (type.isLand()) {
return 6;
}
return -1;
}
return -1;
}),
PW_DECK_SORT("lblPlaneswalkerDeckSort",
new String[] { "Planeswalker", "Rares", "Creature", "Land", "Other Spells" },
new Function<Integer, ColumnDef>() {
@Override
public ColumnDef apply(final Integer groupIndex) {
return null;
}
},
new Function<InventoryItem, Integer>() {
@Override
public Integer apply(final InventoryItem item) {
if (item instanceof PaperCard) {
CardType type = ((PaperCard) item).getRules().getType();
if (type.isPlaneswalker()){
return 0;
}
if (((PaperCard) item).getRarity().toString() == "R"){
return 1;
}
if (type.isCreature()){
return 2;
}
if (type.isLand()){
return 3;
}
return 4;
groupIndex -> null,
item -> {
if (item instanceof PaperCard) {
CardType type = ((PaperCard) item).getRules().getType();
if (type.isPlaneswalker()){
return 0;
}
return -1;
if (((PaperCard) item).getRarity().toString() == "R"){
return 1;
}
if (type.isCreature()){
return 2;
}
if (type.isLand()){
return 3;
}
return 4;
}
return -1;
}),
CARD_RARITY("lblRarity",
new String[] { "Mythic Rares", "Rares", "Uncommons", "Commons", "Basic Lands" },
new Function<Integer, ColumnDef>() {
@Override
public ColumnDef apply(final Integer groupIndex) {
return null;
}
},
new Function<InventoryItem, Integer>() {
@Override
public Integer apply(final InventoryItem item) {
if (item instanceof PaperCard) {
switch (((PaperCard) item).getRarity()) {
case MythicRare:
return 0;
case Rare:
return 1;
case Uncommon:
return 2;
case Common:
return 3;
case BasicLand:
return 4;
default:
return -1; //show Special and Unknown in "Other" group
}
groupIndex -> null,
item -> {
if (item instanceof PaperCard) {
switch (((PaperCard) item).getRarity()) {
case MythicRare:
return 0;
case Rare:
return 1;
case Uncommon:
return 2;
case Common:
return 3;
case BasicLand:
return 4;
default:
return -1; //show Special and Unknown in "Other" group
}
return -1;
}
return -1;
});
GroupDef(String name0, String[] groups0, Function<Integer, ColumnDef> fnGetPileByOverride0, Function<InventoryItem, Integer> fnGroupItem0) {

View File

@@ -51,7 +51,7 @@ public class SFilterUtil {
try {
Predicate<CardRules> filter = expression.evaluate();
if (filter != null) {
return Predicates.compose(invert ? Predicates.not(filter) : filter, PaperCard.FN_GET_RULES);
return Predicates.compose(invert ? Predicates.not(filter) : filter, PaperCard::getRules);
}
}
catch (Exception ignored) {
@@ -74,7 +74,7 @@ public class SFilterUtil {
}
Predicate<CardRules> textFilter = invert ? Predicates.not(Predicates.or(terms)) : Predicates.and(terms);
return Predicates.compose(textFilter, PaperCard.FN_GET_RULES);
return Predicates.compose(textFilter, PaperCard::getRules);
}
private static List<String> getSplitText(String text) {
@@ -145,50 +145,47 @@ public class SFilterUtil {
public static Predicate<PaperCard> buildStarRatingFilter(Map<SItemManagerUtil.StatTypes, ? extends IButton> buttonMap, final HashSet<StarRating> QuestRatings) {
final Map<SItemManagerUtil.StatTypes, ? extends IButton> buttonMap2 = buttonMap;
return new Predicate<PaperCard>() {
@Override
public boolean apply(PaperCard card) {
return card -> {
StarRating r = new StarRating();
r.Name = card.getName();
r.Edition = card.getEdition();
int j = 0;
for (int i = 1; i < 6; i++) {
r.rating = i;
if (QuestRatings.contains(r)) {
j = i;
}
StarRating r = new StarRating();
r.Name = card.getName();
r.Edition = card.getEdition();
int j = 0;
for (int i = 1; i < 6; i++) {
r.rating = i;
if (QuestRatings.contains(r)) {
j = i;
}
boolean result = true;
if (j == 0) {
if (!buttonMap2.get(StatTypes.RATE_NONE).isSelected()) {
result = false;
}
} else if (j == 1) {
if (!buttonMap2.get(StatTypes.RATE_1).isSelected()) {
result = false;
}
} else if (j == 2) {
if (!buttonMap2.get(StatTypes.RATE_2).isSelected()) {
result = false;
}
} else if (j == 3) {
if (!buttonMap2.get(StatTypes.RATE_3).isSelected()) {
result = false;
}
} else if (j == 4) {
if (!buttonMap2.get(StatTypes.RATE_4).isSelected()) {
result = false;
}
} else if (j == 5) {
if (!buttonMap2.get(StatTypes.RATE_5).isSelected()) {
result = false;
}
}
return result;
}
boolean result = true;
if (j == 0) {
if (!buttonMap2.get(StatTypes.RATE_NONE).isSelected()) {
result = false;
}
} else if (j == 1) {
if (!buttonMap2.get(StatTypes.RATE_1).isSelected()) {
result = false;
}
} else if (j == 2) {
if (!buttonMap2.get(StatTypes.RATE_2).isSelected()) {
result = false;
}
} else if (j == 3) {
if (!buttonMap2.get(StatTypes.RATE_3).isSelected()) {
result = false;
}
} else if (j == 4) {
if (!buttonMap2.get(StatTypes.RATE_4).isSelected()) {
result = false;
}
} else if (j == 5) {
if (!buttonMap2.get(StatTypes.RATE_5).isSelected()) {
result = false;
}
}
return result;
};
}
@@ -197,31 +194,27 @@ public class SFilterUtil {
+ ((buttonMap.get(StatTypes.FOIL_NEW).isSelected()) ? 2 : 0)
+ ((buttonMap.get(StatTypes.FOIL_NONE).isSelected()) ? 4 : 0));
return new Predicate<PaperCard>() {
@Override
public boolean apply(PaperCard card) {
return card -> {
boolean result = false;
boolean result = false;
CardEdition edition = StaticData.instance().getEditions().get(card.getEdition());
if ((Foil & 1) == 1) {
// Old Style Foil
if (edition.getFoilType() == CardEdition.FoilType.OLD_STYLE) {
result = result || card.isFoil();
}
CardEdition edition = StaticData.instance().getEditions().get(card.getEdition());
if ((Foil & 1) == 1) {
// Old Style Foil
if (edition.getFoilType() == CardEdition.FoilType.OLD_STYLE) {
result = result || card.isFoil();
}
if ((Foil & 2) == 2) {
// New Style Foil
if (edition.getFoilType() == CardEdition.FoilType.MODERN) {
result = result || card.isFoil();
}
}
if ((Foil & 4) == 4) {
result = result || !card.isFoil();
}
return result;
}
if ((Foil & 2) == 2) {
// New Style Foil
if (edition.getFoilType() == CardEdition.FoilType.MODERN) {
result = result || card.isFoil();
}
}
if ((Foil & 4) == 4) {
result = result || !card.isFoil();
}
return result;
};
}
@@ -248,86 +241,80 @@ public class SFilterUtil {
final boolean wantColorless = buttonMap.get(StatTypes.COLORLESS).isSelected();
final boolean wantMulticolor = buttonMap.get(StatTypes.MULTICOLOR).isSelected();
return new Predicate<PaperCard>() {
@Override
public boolean apply(PaperCard card) {
CardRules rules = card.getRules();
ColorSet color = rules.getColor();
boolean allColorsFilteredOut = colors == 0;
return card -> {
CardRules rules = card.getRules();
ColorSet color = rules.getColor();
boolean allColorsFilteredOut = colors == 0;
//use color identity for lands, which allows filtering to just lands that can be played in your deck
boolean useColorIdentity = rules.getType().isLand() && !allColorsFilteredOut && FModel.getPreferences().getPrefBoolean(ForgePreferences.FPref.UI_FILTER_LANDS_BY_COLOR_IDENTITY);
if (useColorIdentity) {
color = rules.getColorIdentity();
}
boolean result = true;
if (wantMulticolor) {
if (colors == 0) { //handle showing all multi-color cards if all 5 colors are filtered
result = color.isMulticolor() || (wantColorless && color.isColorless());
} else if (colors != ColorSet.ALL_COLORS.getColor()) {
if (useColorIdentity && !allColorsFilteredOut) {
result = color.hasAnyColor(colors) || (wantColorless && color.isColorless());
} else {
result = (wantColorless && color.isColorless()) || rules.canCastWithAvailable(colors);
}
}
} else {
result = !color.isMulticolor();
if (colors != ColorSet.ALL_COLORS.getColor()) {
if (useColorIdentity && !allColorsFilteredOut) {
result = result && (color.hasAnyColor(colors) || (wantColorless && color.isColorless()));
} else {
result = result && (color.isColorless() || rules.canCastWithAvailable(colors));
}
}
}
if (!wantColorless) {
if (colors != 0 && colors != ColorSet.ALL_COLORS.getColor()) {
//if colorless filtered out ensure phyrexian cards don't appear
//unless at least one of their colors is selected
result = result && color.hasAnyColor(colors);
}
result = result && !color.isColorless();
}
return result;
//use color identity for lands, which allows filtering to just lands that can be played in your deck
boolean useColorIdentity = rules.getType().isLand() && !allColorsFilteredOut && FModel.getPreferences().getPrefBoolean(ForgePreferences.FPref.UI_FILTER_LANDS_BY_COLOR_IDENTITY);
if (useColorIdentity) {
color = rules.getColorIdentity();
}
boolean result = true;
if (wantMulticolor) {
if (colors == 0) { //handle showing all multi-color cards if all 5 colors are filtered
result = color.isMulticolor() || (wantColorless && color.isColorless());
} else if (colors != ColorSet.ALL_COLORS.getColor()) {
if (useColorIdentity && !allColorsFilteredOut) {
result = color.hasAnyColor(colors) || (wantColorless && color.isColorless());
} else {
result = (wantColorless && color.isColorless()) || rules.canCastWithAvailable(colors);
}
}
} else {
result = !color.isMulticolor();
if (colors != ColorSet.ALL_COLORS.getColor()) {
if (useColorIdentity && !allColorsFilteredOut) {
result = result && (color.hasAnyColor(colors) || (wantColorless && color.isColorless()));
} else {
result = result && (color.isColorless() || rules.canCastWithAvailable(colors));
}
}
}
if (!wantColorless) {
if (colors != 0 && colors != ColorSet.ALL_COLORS.getColor()) {
//if colorless filtered out ensure phyrexian cards don't appear
//unless at least one of their colors is selected
result = result && color.hasAnyColor(colors);
}
result = result && !color.isColorless();
}
return result;
};
}
public static Predicate<DeckProxy> buildDeckColorFilter(final Map<StatTypes, ? extends IButton> buttonMap) {
return new Predicate<DeckProxy>() {
@Override
public boolean apply(DeckProxy input) {
byte colorProfile = input.getColor().getColor();
if (colorProfile == 0) {
return buttonMap.get(StatTypes.DECK_COLORLESS).isSelected();
}
boolean wantMulticolor = buttonMap.get(StatTypes.DECK_MULTICOLOR).isSelected();
if (!wantMulticolor && BinaryUtil.bitCount(colorProfile) > 1) {
return false;
}
byte colors = 0;
if (buttonMap.get(StatTypes.DECK_WHITE).isSelected()) {
colors |= MagicColor.WHITE;
}
if (buttonMap.get(StatTypes.DECK_BLUE).isSelected()) {
colors |= MagicColor.BLUE;
}
if (buttonMap.get(StatTypes.DECK_BLACK).isSelected()) {
colors |= MagicColor.BLACK;
}
if (buttonMap.get(StatTypes.DECK_RED).isSelected()) {
colors |= MagicColor.RED;
}
if (buttonMap.get(StatTypes.DECK_GREEN).isSelected()) {
colors |= MagicColor.GREEN;
}
return colors == 0 && wantMulticolor && BinaryUtil.bitCount(colorProfile) > 1 || (colorProfile & colors) == colorProfile;
return input -> {
byte colorProfile = input.getColor().getColor();
if (colorProfile == 0) {
return buttonMap.get(StatTypes.DECK_COLORLESS).isSelected();
}
boolean wantMulticolor = buttonMap.get(StatTypes.DECK_MULTICOLOR).isSelected();
if (!wantMulticolor && BinaryUtil.bitCount(colorProfile) > 1) {
return false;
}
byte colors = 0;
if (buttonMap.get(StatTypes.DECK_WHITE).isSelected()) {
colors |= MagicColor.WHITE;
}
if (buttonMap.get(StatTypes.DECK_BLUE).isSelected()) {
colors |= MagicColor.BLUE;
}
if (buttonMap.get(StatTypes.DECK_BLACK).isSelected()) {
colors |= MagicColor.BLACK;
}
if (buttonMap.get(StatTypes.DECK_RED).isSelected()) {
colors |= MagicColor.RED;
}
if (buttonMap.get(StatTypes.DECK_GREEN).isSelected()) {
colors |= MagicColor.GREEN;
}
return colors == 0 && wantMulticolor && BinaryUtil.bitCount(colorProfile) > 1 || (colorProfile & colors) == colorProfile;
};
}

View File

@@ -151,12 +151,7 @@ public final class SItemManagerUtil {
for (final Entry<InventoryItem, Integer> itemEntry : items) {
sorted.add(itemEntry);
}
sorted.sort(new Comparator<Entry<InventoryItem, Integer>>() {
@Override
public int compare(final Entry<InventoryItem, Integer> x, final Entry<InventoryItem, Integer> y) {
return x.getKey().toString().compareTo(y.getKey().toString());
}
});
sorted.sort(Comparator.comparing(x -> x.getKey().toString()));
final StringBuilder builder = new StringBuilder();
for (final Entry<InventoryItem, Integer> itemEntry : sorted) {
builder.append("\n").append(itemEntry.getValue()).append(" * ").append(itemEntry.getKey().toString());

View File

@@ -51,12 +51,7 @@ public abstract class AchievementCollection implements Iterable<Achievement> {
//update all achievements for GUI player after game finished
//(we are doing it in different threads in different game ports to prevent freezing when processing multiple achievements)
if (GuiBase.getInterface().isLibgdxPort()) {
ThreadUtil.invokeInGameThread(new Runnable() {
@Override
public void run() {
doUpdateAllAchievements(match, player);
}
});
ThreadUtil.invokeInGameThread(() -> doUpdateAllAchievements(match, player));
} else {
doUpdateAllAchievements(match, player);
}

View File

@@ -24,7 +24,6 @@ import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import forge.card.CardEdition;
@@ -212,14 +211,6 @@ public final class CardBlock implements Comparable<CardBlock> {
return this.name + " (block)";
}
public static final Function<CardBlock, String> FN_GET_NAME = new Function<CardBlock, String>() {
@Override
public String apply(CardBlock arg1) {
return arg1.getName();
}
};
public static class Reader extends StorageReaderFile<CardBlock> {
private final CardEdition.Collection editions;
@@ -229,7 +220,7 @@ public final class CardBlock implements Comparable<CardBlock> {
* @param editions0
*/
public Reader(String pathname, CardEdition.Collection editions0) {
super(pathname, CardBlock.FN_GET_NAME);
super(pathname, CardBlock::getName);
editions = editions0;
}

View File

@@ -140,23 +140,17 @@ public final class FModel {
ProgressObserver.emptyObserver : new ProgressObserver() {
@Override
public void setOperationName(final String name, final boolean usePercents) {
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
progressBar.setDescription(name);
progressBar.setPercentMode(usePercents);
}
FThreads.invokeInEdtLater(() -> {
progressBar.setDescription(name);
progressBar.setPercentMode(usePercents);
});
}
@Override
public void report(final int current, final int total) {
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
progressBar.setMaximum(total);
progressBar.setValue(current);
}
FThreads.invokeInEdtLater(() -> {
progressBar.setMaximum(total);
progressBar.setValue(current);
});
}
};
@@ -249,12 +243,7 @@ public final class FModel {
Spell.setPerformanceMode(preferences.getPrefBoolean(FPref.PERFORMANCE_MODE));
if (progressBar != null) {
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
progressBar.setDescription(Localizer.getInstance().getMessage("splash.loading.decks"));
}
});
FThreads.invokeInEdtLater(() -> progressBar.setDescription(Localizer.getInstance().getMessage("splash.loading.decks")));
}
decks = new CardCollections();
@@ -337,63 +326,63 @@ public final class FModel {
public static ItemPool<PaperCard> getArchenemyCards() {
if (archenemyCards == null)
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_SCHEME, PaperCard.FN_GET_RULES)), PaperCard.class);
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_SCHEME, PaperCard::getRules)), PaperCard.class);
return archenemyCards;
}
public static ItemPool<PaperCard> getPlanechaseCards() {
if (planechaseCards == null)
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_PLANE_OR_PHENOMENON, PaperCard.FN_GET_RULES)), PaperCard.class);
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_PLANE_OR_PHENOMENON, PaperCard::getRules)), PaperCard.class);
return planechaseCards;
}
public static ItemPool<PaperCard> getBrawlCommander() {
if (brawlCommander == null)
return ItemPool.createFrom(getMagicDb().getCommonCards().getAllCardsNoAlt(Predicates.and(
FModel.getFormats().get("Brawl").getFilterPrinted(), Predicates.compose(CardRulesPredicates.Presets.CAN_BE_BRAWL_COMMANDER, PaperCard.FN_GET_RULES))), PaperCard.class);
FModel.getFormats().get("Brawl").getFilterPrinted(), Predicates.compose(CardRulesPredicates.Presets.CAN_BE_BRAWL_COMMANDER, PaperCard::getRules))), PaperCard.class);
return brawlCommander;
}
public static ItemPool<PaperCard> getOathbreakerCommander() {
if (oathbreakerCommander == null)
return ItemPool.createFrom(getMagicDb().getCommonCards().getAllCardsNoAlt(Predicates.compose(Predicates.or(
CardRulesPredicates.Presets.CAN_BE_OATHBREAKER, CardRulesPredicates.Presets.CAN_BE_SIGNATURE_SPELL), PaperCard.FN_GET_RULES)), PaperCard.class);
CardRulesPredicates.Presets.CAN_BE_OATHBREAKER, CardRulesPredicates.Presets.CAN_BE_SIGNATURE_SPELL), PaperCard::getRules)), PaperCard.class);
return oathbreakerCommander;
}
public static ItemPool<PaperCard> getTinyLeadersCommander() {
if (tinyLeadersCommander == null)
return ItemPool.createFrom(getMagicDb().getCommonCards().getAllCardsNoAlt(Predicates.compose(CardRulesPredicates.Presets.CAN_BE_TINY_LEADERS_COMMANDER, PaperCard.FN_GET_RULES)), PaperCard.class);
return ItemPool.createFrom(getMagicDb().getCommonCards().getAllCardsNoAlt(Predicates.compose(CardRulesPredicates.Presets.CAN_BE_TINY_LEADERS_COMMANDER, PaperCard::getRules)), PaperCard.class);
return tinyLeadersCommander;
}
public static ItemPool<PaperCard> getCommanderPool() {
if (commanderPool == null)
return ItemPool.createFrom(getMagicDb().getCommonCards().getAllCardsNoAlt(Predicates.compose(CardRulesPredicates.Presets.CAN_BE_COMMANDER, PaperCard.FN_GET_RULES)), PaperCard.class);
return ItemPool.createFrom(getMagicDb().getCommonCards().getAllCardsNoAlt(Predicates.compose(CardRulesPredicates.Presets.CAN_BE_COMMANDER, PaperCard::getRules)), PaperCard.class);
return commanderPool;
}
public static ItemPool<PaperCard> getAvatarPool() {
if (avatarPool == null)
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_VANGUARD, PaperCard.FN_GET_RULES)), PaperCard.class);
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_VANGUARD, PaperCard::getRules)), PaperCard.class);
return avatarPool;
}
public static ItemPool<PaperCard> getConspiracyPool() {
if (conspiracyPool == null)
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_CONSPIRACY, PaperCard.FN_GET_RULES)), PaperCard.class);
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_CONSPIRACY, PaperCard::getRules)), PaperCard.class);
return conspiracyPool;
}
public static ItemPool<PaperCard> getDungeonPool() {
if (dungeonPool == null)
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_DUNGEON, PaperCard.FN_GET_RULES)), PaperCard.class);
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_DUNGEON, PaperCard::getRules)), PaperCard.class);
return dungeonPool;
}
public static ItemPool<PaperCard> getAttractionPool() {
if (attractionPool == null)
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_ATTRACTION, PaperCard.FN_GET_RULES)), PaperCard.class);
return ItemPool.createFrom(getMagicDb().getVariantCards().getAllCards(Predicates.compose(CardRulesPredicates.Presets.IS_ATTRACTION, PaperCard::getRules)), PaperCard.class);
return attractionPool;
}
private static boolean keywordsLoaded = false;

View File

@@ -19,10 +19,10 @@ public final class GamePlayerUtil {
private GamePlayerUtil() { }
private static final LobbyPlayer guiPlayer = new LobbyPlayerHuman("Human");
public static final LobbyPlayer getGuiPlayer() {
public static LobbyPlayer getGuiPlayer() {
return guiPlayer;
}
public static final LobbyPlayer getGuiPlayer(final String name, final int avatarIndex, final int sleeveIndex, final boolean writePref) {
public static LobbyPlayer getGuiPlayer(final String name, final int avatarIndex, final int sleeveIndex, final boolean writePref) {
if (writePref) {
if (!name.equals(guiPlayer.getName())) {
guiPlayer.setName(name);
@@ -38,34 +38,34 @@ public final class GamePlayerUtil {
return new LobbyPlayerHuman(name, avatarIndex, sleeveIndex);
}
public static final LobbyPlayer getQuestPlayer() {
public static LobbyPlayer getQuestPlayer() {
return guiPlayer; //TODO: Make this a separate player
}
public final static LobbyPlayer createAiPlayer() {
public static LobbyPlayer createAiPlayer() {
return createAiPlayer(GuiDisplayUtil.getRandomAiName());
}
public final static LobbyPlayer createAiPlayer(final String name) {
public static LobbyPlayer createAiPlayer(final String name) {
final int avatarCount = GuiBase.getInterface().getAvatarCount();
final int sleeveCount = GuiBase.getInterface().getSleevesCount();
return createAiPlayer(name, avatarCount == 0 ? 0 : MyRandom.getRandom().nextInt(avatarCount), sleeveCount == 0 ? 0 : MyRandom.getRandom().nextInt(sleeveCount));
}
public final static LobbyPlayer createAiPlayer(final String name, final String profileOverride) {
public static LobbyPlayer createAiPlayer(final String name, final String profileOverride) {
final int avatarCount = GuiBase.getInterface().getAvatarCount();
final int sleeveCount = GuiBase.getInterface().getSleevesCount();
return createAiPlayer(name, avatarCount == 0 ? 0 : MyRandom.getRandom().nextInt(avatarCount), sleeveCount == 0 ? 0 : MyRandom.getRandom().nextInt(sleeveCount), null, profileOverride);
}
public final static LobbyPlayer createAiPlayer(final String name, final int avatarIndex) {
public static LobbyPlayer createAiPlayer(final String name, final int avatarIndex) {
final int sleeveCount = GuiBase.getInterface().getSleevesCount();
return createAiPlayer(name, avatarIndex, sleeveCount == 0 ? 0 : MyRandom.getRandom().nextInt(sleeveCount), null, "");
}
public final static LobbyPlayer createAiPlayer(final String name, final int avatarIndex, final int sleeveIndex) {
public static LobbyPlayer createAiPlayer(final String name, final int avatarIndex, final int sleeveIndex) {
return createAiPlayer(name, avatarIndex, sleeveIndex, null, "");
}
public final static LobbyPlayer createAiPlayer(final String name, final int avatarIndex, final int sleeveIndex, final Set<AIOption> options) {
public static LobbyPlayer createAiPlayer(final String name, final int avatarIndex, final int sleeveIndex, final Set<AIOption> options) {
return createAiPlayer(name, avatarIndex, sleeveIndex, options, "");
}
public final static LobbyPlayer createAiPlayer(final String name, final int avatarIndex, final int sleeveIndex, final Set<AIOption> options, final String profileOverride) {
public static LobbyPlayer createAiPlayer(final String name, final int avatarIndex, final int sleeveIndex, final Set<AIOption> options, final String profileOverride) {
final LobbyPlayerAi player = new LobbyPlayerAi(name, options);
// TODO: implement specific AI profiles for quest mode.

View File

@@ -1053,7 +1053,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
return counterTable.totalValues();
}
protected final boolean isValidChoice(final GameEntity choice) {
protected boolean isValidChoice(final GameEntity choice) {
return validChoices.contains(choice);
}
@@ -1119,7 +1119,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
}
final InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, 1, 1, validCards, ability);
inp.setMessage(Localizer.getInstance().getMessage("lblRemoveCountersFromAInZoneCard", Lang.joinHomogenous(cost.zone, ZoneType.Accessors.GET_TRANSLATED_NAME)));
inp.setMessage(Localizer.getInstance().getMessage("lblRemoveCountersFromAInZoneCard", Lang.joinHomogenous(cost.zone, ZoneType::getTranslatedName)));
inp.setCancelAllowed(true);
inp.showAndWait();

View File

@@ -1343,7 +1343,7 @@ public class PlayerControllerHuman extends PlayerController implements IGameCont
// create sorted list from map from least to most frequent
List<Entry<String, Integer>> sortedList = Lists.newArrayList(typesInDeck.entrySet());
Collections.sort(sortedList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
Collections.sort(sortedList, Entry.comparingByValue());
// loop through sorted list and move each type to the front of the
// validTypes collection
@@ -1527,7 +1527,7 @@ public class PlayerControllerHuman extends PlayerController implements IGameCont
@SuppressWarnings("serial") final InputSelectCardsFromList inp = new InputSelectCardsFromList(this, nDiscard, nDiscard,
player.getZone(ZoneType.Hand).getCards()) {
@Override
protected final boolean allowAwaitNextInput() {
protected boolean allowAwaitNextInput() {
return true; // prevent Cleanup message getting stuck during
// opponent's next turn
}

View File

@@ -67,7 +67,7 @@ public class TargetSelection {
this.ability = currentAbility;
}
private final TargetRestrictions getTgt() {
private TargetRestrictions getTgt() {
return this.ability.getTargetRestrictions();
}
@@ -218,7 +218,7 @@ public class TargetSelection {
return choiceResult && chooseTargets(numTargets, divisionValues, filter, optional, canFilterMustTarget);
}
private final boolean chooseCardFromList(final List<Card> choices, final boolean targeted, final boolean mandatory) {
private boolean chooseCardFromList(final List<Card> choices, final boolean targeted, final boolean mandatory) {
// Send in a list of valid cards, and popup a choice box to target
final Game game = ability.getActivatingPlayer().getGame();
@@ -318,7 +318,7 @@ public class TargetSelection {
return true;
}
private final boolean chooseCardFromStack(final boolean mandatory, final Integer numTargets) {
private boolean chooseCardFromStack(final boolean mandatory, final Integer numTargets) {
final TargetRestrictions tgt = this.getTgt();
final String message = TextUtil.fastReplace(tgt.getVTSelection(),
"CARDNAME", ability.getHostCard().toString());

View File

@@ -214,15 +214,13 @@ public class SoundSystem {
try {
currentTrack = GuiBase.getInterface().createAudioMusic(filename);
currentTrack.play(new Runnable() {
@Override public void run() {
try {
Thread.sleep(SoundSystem.DELAY);
} catch (final InterruptedException ex) {
ex.printStackTrace();
}
changeBackgroundTrack(); //change track when music completes on its own
currentTrack.play(() -> {
try {
Thread.sleep(SoundSystem.DELAY);
} catch (final InterruptedException ex) {
ex.printStackTrace();
}
changeBackgroundTrack(); //change track when music completes on its own
});
refreshVolume();
} catch (final Exception ex) {

View File

@@ -10,13 +10,10 @@ public abstract class WaitRunnable implements Runnable {
public final void invokeAndWait() {
FThreads.assertExecutedByEdt(false); //not supported if on UI thread
FThreads.invokeInEdtLater(new Runnable() {
@Override
public void run() {
WaitRunnable.this.run();
synchronized(lock) {
lock.notify();
}
FThreads.invokeInEdtLater(() -> {
WaitRunnable.this.run();
synchronized(lock) {
lock.notify();
}
});
try {