Whitespace cleanup

This commit is contained in:
drdev
2013-11-22 02:23:53 +00:00
parent f934764290
commit 72d0cfdbbc
5 changed files with 175 additions and 205 deletions

View File

@@ -21,90 +21,83 @@ import forge.util.storage.StorageBase;
* @author Max * @author Max
*/ */
public class StaticData { public class StaticData {
private final CardDb commonCards;
private final CardDb variantCards;
private final CardEdition.Collection editions;
private final IStorage<SealedProduct.Template> boosters;
private final IStorage<SealedProduct.Template> specialBoosters;
private final IStorage<SealedProduct.Template> tournaments;
private final IStorage<FatPack.Template> fatPacks;
private final IStorage<PrintSheet> printSheets;
private final CardDb commonCards; private static StaticData lastInstance = null;
private final CardDb variantCards;
private final CardEdition.Collection editions;
private final IStorage<SealedProduct.Template> boosters;
private final IStorage<SealedProduct.Template> specialBoosters;
private final IStorage<SealedProduct.Template> tournaments;
private final IStorage<FatPack.Template> fatPacks;
private final IStorage<PrintSheet> printSheets;
private static StaticData lastInstance = null; public StaticData(ICardStorageReader reader, String editionFolder, String blockDataFolder) {
this.editions = new CardEdition.Collection(new CardEdition.Reader(new File(editionFolder)));
lastInstance = this;
final Map<String, CardRules> regularCards = new TreeMap<String, CardRules>(String.CASE_INSENSITIVE_ORDER);
final Map<String, CardRules> variantsCards = new TreeMap<String, CardRules>(String.CASE_INSENSITIVE_ORDER);
List<CardRules> rules = reader.loadCards();
public StaticData(ICardStorageReader reader, String editionFolder, String blockDataFolder) { for (CardRules card : rules) {
this.editions = new CardEdition.Collection(new CardEdition.Reader(new File(editionFolder))); if (null == card) continue;
lastInstance = this;
final Map<String, CardRules> regularCards = new TreeMap<String, CardRules>(String.CASE_INSENSITIVE_ORDER); final String cardName = card.getName();
final Map<String, CardRules> variantsCards = new TreeMap<String, CardRules>(String.CASE_INSENSITIVE_ORDER); if ( card.isVariant() ) {
variantsCards.put(cardName, card);
}
else {
regularCards.put(cardName, card);
}
}
commonCards = new CardDb(regularCards, editions, false);
variantCards = new CardDb(variantsCards, editions, false);
List<CardRules> rules = reader.loadCards(); this.boosters = new StorageBase<SealedProduct.Template>("Boosters", editions.getBoosterGenerator());
for (CardRules card : rules) { this.specialBoosters = new StorageBase<SealedProduct.Template>("Special boosters", new SealedProduct.Template.Reader(new File(blockDataFolder, "boosters-special.txt")));
if (null == card) continue; this.tournaments = new StorageBase<SealedProduct.Template>("Starter sets", new SealedProduct.Template.Reader(new File(blockDataFolder, "starters.txt")));
this.fatPacks = new StorageBase<FatPack.Template>("Fat packs", new FatPack.Template.Reader("res/blockdata/fatpacks.txt"));
final String cardName = card.getName(); this.printSheets = new StorageBase<PrintSheet>("Special print runs", new PrintSheet.Reader(new File(blockDataFolder, "printsheets.txt")));
if ( card.isVariant() ) }
variantsCards.put(cardName, card);
else
regularCards.put(cardName, card);
}
commonCards = new CardDb(regularCards, editions, false);
variantCards = new CardDb(variantsCards, editions, false);
public final static StaticData instance() {
return lastInstance;
}
this.boosters = new StorageBase<SealedProduct.Template>("Boosters", editions.getBoosterGenerator()); public final CardEdition.Collection getEditions() {
this.specialBoosters = new StorageBase<SealedProduct.Template>("Special boosters", new SealedProduct.Template.Reader(new File(blockDataFolder, "boosters-special.txt"))); return this.editions;
this.tournaments = new StorageBase<SealedProduct.Template>("Starter sets", new SealedProduct.Template.Reader(new File(blockDataFolder, "starters.txt"))); }
this.fatPacks = new StorageBase<FatPack.Template>("Fat packs", new FatPack.Template.Reader("res/blockdata/fatpacks.txt"));
this.printSheets = new StorageBase<PrintSheet>("Special print runs", new PrintSheet.Reader(new File(blockDataFolder, "printsheets.txt")));
}
public final static StaticData instance() {
return lastInstance;
}
public final CardEdition.Collection getEditions() {
return this.editions;
}
/** @return {@link forge.util.storage.IStorageView}<{@link forge.item.FatPackTemplate}> */ /** @return {@link forge.util.storage.IStorageView}<{@link forge.item.FatPackTemplate}> */
public IStorage<FatPack.Template> getFatPacks() { public IStorage<FatPack.Template> getFatPacks() {
return fatPacks; return fatPacks;
} }
/** @return {@link forge.util.storage.IStorageView}<{@link forge.card.BoosterTemplate}> */ /** @return {@link forge.util.storage.IStorageView}<{@link forge.card.BoosterTemplate}> */
public final IStorage<SealedProduct.Template> getTournamentPacks() { public final IStorage<SealedProduct.Template> getTournamentPacks() {
return tournaments; return tournaments;
} }
/** @return {@link forge.util.storage.IStorageView}<{@link forge.card.BoosterTemplate}> */ /** @return {@link forge.util.storage.IStorageView}<{@link forge.card.BoosterTemplate}> */
public final IStorage<SealedProduct.Template> getBoosters() { public final IStorage<SealedProduct.Template> getBoosters() {
return boosters; return boosters;
} }
public final IStorage<SealedProduct.Template> getSpecialBoosters() { public final IStorage<SealedProduct.Template> getSpecialBoosters() {
return specialBoosters; return specialBoosters;
} }
public IStorage<PrintSheet> getPrintSheets() { public IStorage<PrintSheet> getPrintSheets() {
return printSheets; return printSheets;
} }
public CardDb getCommonCards() {
return commonCards;
}
public CardDb getCommonCards() { public CardDb getVariantCards() {
return commonCards; return variantCards;
} }
public CardDb getVariantCards() {
return variantCards;
}
} }

View File

@@ -39,7 +39,6 @@ import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps; import com.google.common.collect.Multimaps;
import forge.card.CardEdition.CardInSet; import forge.card.CardEdition.CardInSet;
import forge.deck.CardPool;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.util.Aggregates; import forge.util.Aggregates;
import forge.util.CollectionSuppliers; import forge.util.CollectionSuppliers;
@@ -54,12 +53,11 @@ public final class CardDb implements ICardDatabase {
private final Multimap<String, PaperCard> allCardsByName = Multimaps.newListMultimap(new TreeMap<String,Collection<PaperCard>>(String.CASE_INSENSITIVE_ORDER), CollectionSuppliers.<PaperCard>arrayLists()); private final Multimap<String, PaperCard> allCardsByName = Multimaps.newListMultimap(new TreeMap<String,Collection<PaperCard>>(String.CASE_INSENSITIVE_ORDER), CollectionSuppliers.<PaperCard>arrayLists());
private final Map<String, PaperCard> uniqueCardsByName = new TreeMap<String, PaperCard>(String.CASE_INSENSITIVE_ORDER); private final Map<String, PaperCard> uniqueCardsByName = new TreeMap<String, PaperCard>(String.CASE_INSENSITIVE_ORDER);
private final Map<String, CardRules> rulesByName; private final Map<String, CardRules> rulesByName;
private final List<PaperCard> allCards = new ArrayList<PaperCard>(); private final List<PaperCard> allCards = new ArrayList<PaperCard>();
private final List<PaperCard> roAllCards = Collections.unmodifiableList(allCards); private final List<PaperCard> roAllCards = Collections.unmodifiableList(allCards);
private final Collection<PaperCard> roUniqueCards = Collections.unmodifiableCollection(uniqueCardsByName.values()); private final Collection<PaperCard> roUniqueCards = Collections.unmodifiableCollection(uniqueCardsByName.values());
private final CardEdition.Collection editions; private final CardEdition.Collection editions;
public CardDb(Map<String, CardRules> rules, CardEdition.Collection editions0, boolean logMissingCards) { public CardDb(Map<String, CardRules> rules, CardEdition.Collection editions0, boolean logMissingCards) {
this.rulesByName = rules; this.rulesByName = rules;
@@ -72,14 +70,14 @@ public final class CardDb implements ICardDatabase {
String lastCardName = null; String lastCardName = null;
int artIdx = 0; int artIdx = 0;
for(CardEdition.CardInSet cis : e.getCards()) { for(CardEdition.CardInSet cis : e.getCards()) {
if ( cis.name.equals(lastCardName) ) if ( cis.name.equals(lastCardName) )
artIdx++; artIdx++;
else { else {
artIdx = 0; artIdx = 0;
lastCardName = cis.name; lastCardName = cis.name;
} }
CardRules cr = rulesByName.get(lastCardName); CardRules cr = rulesByName.get(lastCardName);
if( cr != null ) if( cr != null )
addCard(new PaperCard(cr, e.getCode(), cis.rarity, artIdx)); addCard(new PaperCard(cr, e.getCode(), cis.rarity, artIdx));
else if (worthLogging) else if (worthLogging)
missingCards.add(cis.name); missingCards.add(cis.name);
@@ -94,7 +92,7 @@ public final class CardDb implements ICardDatabase {
missingCards.clear(); missingCards.clear();
} }
} }
for(CardRules cr : rulesByName.values()) { for(CardRules cr : rulesByName.values()) {
if( !allCardsByName.containsKey(cr.getName()) ) if( !allCardsByName.containsKey(cr.getName()) )
{ {
@@ -102,7 +100,7 @@ public final class CardDb implements ICardDatabase {
addCard(new PaperCard(cr, CardEdition.UNKNOWN.getCode(), CardRarity.Special, 0)); addCard(new PaperCard(cr, CardEdition.UNKNOWN.getCode(), CardRarity.Special, 0));
} }
} }
reIndex(); reIndex();
} }
@@ -155,7 +153,7 @@ public final class CardDb implements ICardDatabase {
public PaperCard tryGetCard(final String cardName0) { public PaperCard tryGetCard(final String cardName0) {
return tryGetCard(cardName0, true); return tryGetCard(cardName0, true);
} }
@Override @Override
public PaperCard tryGetCard(final String cardName0, boolean fromLastSet) { public PaperCard tryGetCard(final String cardName0, boolean fromLastSet) {
if (null == cardName0) { if (null == cardName0) {
@@ -164,23 +162,23 @@ public final class CardDb implements ICardDatabase {
final boolean isFoil = this.isFoil(cardName0); final boolean isFoil = this.isFoil(cardName0);
final String cardName = isFoil ? this.removeFoilSuffix(cardName0) : cardName0; final String cardName = isFoil ? this.removeFoilSuffix(cardName0) : cardName0;
final ImmutablePair<String, String> nameWithSet = CardDb.splitCardName(cardName); final ImmutablePair<String, String> nameWithSet = CardDb.splitCardName(cardName);
final PaperCard res = nameWithSet.right == null final PaperCard res = nameWithSet.right == null
? ( fromLastSet ? this.uniqueCardsByName.get(nameWithSet.left) : Aggregates.random(this.allCardsByName.get(nameWithSet.left)) ) ? ( fromLastSet ? this.uniqueCardsByName.get(nameWithSet.left) : Aggregates.random(this.allCardsByName.get(nameWithSet.left)) )
: tryGetCard(nameWithSet.left, nameWithSet.right); : tryGetCard(nameWithSet.left, nameWithSet.right);
return null != res && isFoil ? getFoiled(res) : res; return null != res && isFoil ? getFoiled(res) : res;
} }
@Override @Override
public PaperCard tryGetCardPrintedByDate(final String name0, final boolean fromLatestSet, final Date printedBefore) { public PaperCard tryGetCardPrintedByDate(final String name0, final boolean fromLatestSet, final Date printedBefore) {
final boolean isFoil = this.isFoil(name0); final boolean isFoil = this.isFoil(name0);
final String cardName = isFoil ? this.removeFoilSuffix(name0) : name0; final String cardName = isFoil ? this.removeFoilSuffix(name0) : name0;
final ImmutablePair<String, String> nameWithSet = CardDb.splitCardName(cardName); final ImmutablePair<String, String> nameWithSet = CardDb.splitCardName(cardName);
PaperCard res = null; PaperCard res = null;
if (null != nameWithSet.right) // set explicitly requested, should return card from it and disregard the date if (null != nameWithSet.right) // set explicitly requested, should return card from it and disregard the date
res = tryGetCard(nameWithSet.left, nameWithSet.right); res = tryGetCard(nameWithSet.left, nameWithSet.right);
else { else {
Collection<PaperCard> cards = this.allCardsByName.get(nameWithSet.left); // cards are sorted by datetime desc Collection<PaperCard> cards = this.allCardsByName.get(nameWithSet.left); // cards are sorted by datetime desc
@@ -196,13 +194,12 @@ public final class CardDb implements ICardDatabase {
return null != res && isFoil ? getFoiled(res) : res; return null != res && isFoil ? getFoiled(res) : res;
} }
@Override @Override
public PaperCard tryGetCard(final String cardName, String setName) { public PaperCard tryGetCard(final String cardName, String setName) {
return tryGetCard(cardName, setName, -1); return tryGetCard(cardName, setName, -1);
} }
@Override @Override
public PaperCard tryGetCard(final String cardName0, String setName, int index) { public PaperCard tryGetCard(final String cardName0, String setName, int index) {
final boolean isFoil = this.isFoil(cardName0); final boolean isFoil = this.isFoil(cardName0);
@@ -212,7 +209,7 @@ public final class CardDb implements ICardDatabase {
if ( null == cards ) return null; if ( null == cards ) return null;
CardEdition edition = editions.get(setName); CardEdition edition = editions.get(setName);
if ( null == edition ) if ( null == edition )
return tryGetCard(cardName, true); // set not found, try to get the same card from just any set. return tryGetCard(cardName, true); // set not found, try to get the same card from just any set.
String effectiveSet = edition.getCode(); String effectiveSet = edition.getCode();
@@ -227,7 +224,7 @@ public final class CardDb implements ICardDatabase {
if (cnt == 0 ) return null; if (cnt == 0 ) return null;
result = cnt == 1 ? candidates[0] : candidates[MyRandom.getRandom().nextInt(cnt)]; result = cnt == 1 ? candidates[0] : candidates[MyRandom.getRandom().nextInt(cnt)];
} else } else
for( PaperCard pc : cards ) { for( PaperCard pc : cards ) {
if( pc.getEdition().equalsIgnoreCase(effectiveSet) && index == pc.getArtIndex() ) { if( pc.getEdition().equalsIgnoreCase(effectiveSet) && index == pc.getArtIndex() ) {
result = pc; result = pc;
@@ -237,7 +234,7 @@ public final class CardDb implements ICardDatabase {
if ( result == null ) return null; if ( result == null ) return null;
return isFoil ? getFoiled(result) : result; return isFoil ? getFoiled(result) : result;
} }
public PaperCard getFoiled(PaperCard card0) { public PaperCard getFoiled(PaperCard card0) {
// Here - I am still unsure if there should be a cache Card->Card from unfoiled to foiled, to avoid creation of N instances of single plains // Here - I am still unsure if there should be a cache Card->Card from unfoiled to foiled, to avoid creation of N instances of single plains
return new PaperCard(card0.getRules(), card0.getEdition(), card0.getRarity(), card0.getArtIndex(), true); return new PaperCard(card0.getRules(), card0.getEdition(), card0.getRarity(), card0.getArtIndex(), true);
@@ -252,17 +249,17 @@ public final class CardDb implements ICardDatabase {
} }
return cnt; return cnt;
} }
@Override @Override
public int getMaxPrintCount(String cardName) { public int getMaxPrintCount(String cardName) {
int max = -1; int max = -1;
for( PaperCard pc : allCardsByName.get(cardName) ) { for( PaperCard pc : allCardsByName.get(cardName) ) {
if ( max < pc.getArtIndex() ) if ( max < pc.getArtIndex() )
max = pc.getArtIndex(); max = pc.getArtIndex();
} }
return max + 1; return max + 1;
} }
// Single fetch // Single fetch
@Override @Override
public PaperCard getCard(final String name) { public PaperCard getCard(final String name) {
@@ -279,8 +276,7 @@ public final class CardDb implements ICardDatabase {
} }
return result; return result;
} }
@Override @Override
public PaperCard getCardPrintedByDate(final String name0, final boolean fromLatestSet, Date printedBefore ) { public PaperCard getCardPrintedByDate(final String name0, final boolean fromLatestSet, Date printedBefore ) {
// Sometimes they read from decks things like "CardName|Set" - but we // Sometimes they read from decks things like "CardName|Set" - but we
@@ -290,8 +286,8 @@ public final class CardDb implements ICardDatabase {
throw new NoSuchElementException(String.format("Card '%s' released before %s not found in our database.", name0, printedBefore.toString())); throw new NoSuchElementException(String.format("Card '%s' released before %s not found in our database.", name0, printedBefore.toString()));
} }
return result; return result;
} }
// Advanced fetch by name+set // Advanced fetch by name+set
@Override @Override
public PaperCard getCard(final String name, final String set) { public PaperCard getCard(final String name, final String set) {
@@ -300,7 +296,6 @@ public final class CardDb implements ICardDatabase {
@Override @Override
public PaperCard getCard(final String name, final String set, final int artIndex) { public PaperCard getCard(final String name, final String set, final int artIndex) {
final PaperCard result = tryGetCard(name, set, artIndex); final PaperCard result = tryGetCard(name, set, artIndex);
if (null == result) { if (null == result) {
final String message = String.format("Asked for '%s' from '%s' #%d: db didn't find that copy.", name, set, artIndex); final String message = String.format("Asked for '%s' from '%s' #%d: db didn't find that copy.", name, set, artIndex);
@@ -329,7 +324,7 @@ public final class CardDb implements ICardDatabase {
public Predicate<? super PaperCard> wasPrintedInSets(List<String> setCodes) { public Predicate<? super PaperCard> wasPrintedInSets(List<String> setCodes) {
return new PredicateExistsInSets(setCodes); return new PredicateExistsInSets(setCodes);
} }
private class PredicateExistsInSets implements Predicate<PaperCard> { private class PredicateExistsInSets implements Predicate<PaperCard> {
private final List<String> sets; private final List<String> sets;
@@ -340,20 +335,20 @@ public final class CardDb implements ICardDatabase {
@Override @Override
public boolean apply(final PaperCard subject) { public boolean apply(final PaperCard subject) {
Collection<PaperCard> cc = allCardsByName.get(subject.getName()); Collection<PaperCard> cc = allCardsByName.get(subject.getName());
for(PaperCard c : cc) for(PaperCard c : cc)
if (sets.contains(c.getEdition())) if (sets.contains(c.getEdition()))
return true; return true;
return false; return false;
} }
} }
private final Editor editor = new Editor(); private final Editor editor = new Editor();
public Editor getEditor() { return editor; } public Editor getEditor() { return editor; }
public class Editor { public class Editor {
private boolean immediateReindex = true; private boolean immediateReindex = true;
public CardRules putCard(CardRules rules) { return putCard(rules, null); /* will use data from editions folder */ } public CardRules putCard(CardRules rules) { return putCard(rules, null); /* will use data from editions folder */ }
public CardRules putCard(CardRules rules, List<Pair<String, CardRarity>> whenItWasPrinted){ // works similarly to Map<K,V>, returning prev. value public CardRules putCard(CardRules rules, List<Pair<String, CardRarity>> whenItWasPrinted){ // works similarly to Map<K,V>, returning prev. value
String cardName = rules.getName(); String cardName = rules.getName();
CardRules result = rulesByName.put(cardName, rules); CardRules result = rulesByName.put(cardName, rules);
// 1. generate all paper cards from edition data we have (either explicit, or found in res/editions, or add to unknown edition) // 1. generate all paper cards from edition data we have (either explicit, or found in res/editions, or add to unknown edition)
List<PaperCard> paperCards = new ArrayList<PaperCard>(); List<PaperCard> paperCards = new ArrayList<PaperCard>();
@@ -389,7 +384,7 @@ public final class CardDb implements ICardDatabase {
// 3. reindex can be temporary disabled and run after the whole batch of rules is added to db. // 3. reindex can be temporary disabled and run after the whole batch of rules is added to db.
if(immediateReindex) if(immediateReindex)
reIndex(); reIndex();
return result; return result;
} }
public void removeCard(String name) { public void removeCard(String name) {
@@ -404,7 +399,7 @@ public final class CardDb implements ICardDatabase {
} }
} }
public void rebuildIndex() { reIndex(); } public void rebuildIndex() { reIndex(); }
public boolean isImmediateReindex() { public boolean isImmediateReindex() {
return immediateReindex; return immediateReindex;
} }
@@ -412,5 +407,4 @@ public final class CardDb implements ICardDatabase {
this.immediateReindex = immediateReindex; this.immediateReindex = immediateReindex;
} }
} }
} }

View File

@@ -40,7 +40,7 @@ public final class CardRules implements ICardCharacteristics {
//private final Map<String, CardInSet> setsPrinted = new TreeMap<String, CardInSet>(String.CASE_INSENSITIVE_ORDER); //private final Map<String, CardInSet> setsPrinted = new TreeMap<String, CardInSet>(String.CASE_INSENSITIVE_ORDER);
private CardAiHints aiHints; private CardAiHints aiHints;
private ColorSet colorIdentity = null; private ColorSet colorIdentity = null;
private CardRules(ICardFace[] faces, CardSplitType altMode, CardAiHints cah) { private CardRules(ICardFace[] faces, CardSplitType altMode, CardAiHints cah) {
@@ -48,29 +48,29 @@ public final class CardRules implements ICardCharacteristics {
mainPart = faces[0]; mainPart = faces[0];
otherPart = faces[1]; otherPart = faces[1];
aiHints = cah; aiHints = cah;
//System.out.print(faces[0].getName()); //System.out.print(faces[0].getName());
// for (Entry<String, CardInSet> cs : sets.entrySet()) { // for (Entry<String, CardInSet> cs : sets.entrySet()) {
// if( CardRulesReader.editions.get(cs.getKey()) != null ) // if( CardRulesReader.editions.get(cs.getKey()) != null )
// setsPrinted.put(cs.getKey(), cs.getValue()); // setsPrinted.put(cs.getKey(), cs.getValue());
// } // }
// //
// if ( setsPrinted.isEmpty() ) { // if ( setsPrinted.isEmpty() ) {
// System.err.println(getName() + " was not assigned any set."); // System.err.println(getName() + " was not assigned any set.");
// setsPrinted.put(CardEdition.UNKNOWN.getCode(), new CardInSet(CardRarity.Common, 1) ); // setsPrinted.put(CardEdition.UNKNOWN.getCode(), new CardInSet(CardRarity.Common, 1) );
// } // }
// //
//Calculate Color Identity //Calculate Color Identity
byte colMask = calculateColorIdentity(mainPart); byte colMask = calculateColorIdentity(mainPart);
if(otherPart != null) if(otherPart != null)
{ {
colMask |= calculateColorIdentity(otherPart); colMask |= calculateColorIdentity(otherPart);
} }
colorIdentity = ColorSet.fromMask(colMask); colorIdentity = ColorSet.fromMask(colMask);
} }
private byte calculateColorIdentity(ICardFace face) private byte calculateColorIdentity(ICardFace face)
{ {
byte res = face.getColor().getColor(); byte res = face.getColor().getColor();
@@ -156,7 +156,7 @@ public final class CardRules implements ICardCharacteristics {
public ColorSet getColor() { public ColorSet getColor() {
switch(splitType.getAggregationMethod()) { switch(splitType.getAggregationMethod()) {
case COMBINE: case COMBINE:
return ColorSet.fromMask(mainPart.getColor().getColor() | otherPart.getColor().getColor()); return ColorSet.fromMask(mainPart.getColor().getColor() | otherPart.getColor().getColor());
default: default:
return mainPart.getColor(); return mainPart.getColor();
} }
@@ -172,7 +172,7 @@ public final class CardRules implements ICardCharacteristics {
public String getOracleText() { public String getOracleText() {
switch(splitType.getAggregationMethod()) { switch(splitType.getAggregationMethod()) {
case COMBINE: case COMBINE:
return mainPart.getOracleText() + "\r\n\r\n" + otherPart.getOracleText(); return mainPart.getOracleText() + "\r\n\r\n" + otherPart.getOracleText();
default: default:
return mainPart.getOracleText(); return mainPart.getOracleText();
} }
@@ -220,12 +220,11 @@ public final class CardRules implements ICardCharacteristics {
public final List<String> getAbilities() { public final List<String> getAbilities() {
return null; return null;
} }
public ColorSet getColorIdentity() { public ColorSet getColorIdentity() {
return colorIdentity; return colorIdentity;
} }
/** Instantiates class, reads a card. For batch operations better create you own reader instance. */ /** Instantiates class, reads a card. For batch operations better create you own reader instance. */
public static CardRules fromScript(Iterable<String> script) { public static CardRules fromScript(Iterable<String> script) {
Reader crr = new Reader(); Reader crr = new Reader();
@@ -233,24 +232,23 @@ public final class CardRules implements ICardCharacteristics {
crr.parseLine(line); crr.parseLine(line);
} }
return crr.getCard(); return crr.getCard();
} }
// Reads cardname.txt // Reads cardname.txt
public static class Reader { public static class Reader {
// fields to build // fields to build
private CardFace[] faces = new CardFace[] { null, null }; private CardFace[] faces = new CardFace[] { null, null };
private String[] pictureUrl = new String[] { null, null }; private String[] pictureUrl = new String[] { null, null };
private int curFace = 0; private int curFace = 0;
private CardSplitType altMode = CardSplitType.None; private CardSplitType altMode = CardSplitType.None;
private String handLife = null; private String handLife = null;
// fields to build CardAiHints // fields to build CardAiHints
private boolean removedFromAIDecks = false; private boolean removedFromAIDecks = false;
private boolean removedFromRandomDecks = false; private boolean removedFromRandomDecks = false;
private DeckHints hints = null; private DeckHints hints = null;
private DeckHints needs = null; private DeckHints needs = null;
/** /**
* Reset all fields to parse next card (to avoid allocating new CardRulesReader N times) * Reset all fields to parse next card (to avoid allocating new CardRulesReader N times)
*/ */
@@ -260,16 +258,16 @@ public final class CardRules implements ICardCharacteristics {
this.faces[1] = null; this.faces[1] = null;
this.pictureUrl[0] = null; this.pictureUrl[0] = null;
this.pictureUrl[1] = null; this.pictureUrl[1] = null;
this.handLife = null; this.handLife = null;
this.altMode = CardSplitType.None; this.altMode = CardSplitType.None;
this.removedFromAIDecks = false; this.removedFromAIDecks = false;
this.removedFromRandomDecks = false; this.removedFromRandomDecks = false;
this.needs = null; this.needs = null;
this.hints = null; this.hints = null;
} }
/** /**
* Gets the card. * Gets the card.
* *
@@ -285,7 +283,7 @@ public final class CardRules implements ICardCharacteristics {
result.setVanguardProperties(handLife); result.setVanguardProperties(handLife);
return result; return result;
} }
public final CardRules readCard(final Iterable<String> script) { public final CardRules readCard(final Iterable<String> script) {
this.reset(); this.reset();
for (String line : script) { for (String line : script) {
@@ -296,8 +294,7 @@ public final class CardRules implements ICardCharacteristics {
} }
return this.getCard(); return this.getCard();
} }
/** /**
* Parses the line. * Parses the line.
* *
@@ -308,7 +305,7 @@ public final class CardRules implements ICardCharacteristics {
int colonPos = line.indexOf(':'); int colonPos = line.indexOf(':');
String key = colonPos > 0 ? line.substring(0, colonPos) : line; String key = colonPos > 0 ? line.substring(0, colonPos) : line;
String value = colonPos > 0 ? line.substring(1+colonPos).trim() : null; String value = colonPos > 0 ? line.substring(1+colonPos).trim() : null;
switch(key.charAt(0)) { switch(key.charAt(0)) {
case 'A': case 'A':
if ("A".equals(key)) if ("A".equals(key))
@@ -320,7 +317,7 @@ public final class CardRules implements ICardCharacteristics {
this.curFace = 1; this.curFace = 1;
} }
break; break;
case 'C': case 'C':
if ("Colors".equals(key)) { if ("Colors".equals(key)) {
// This is forge.card.CardColor not forge.CardColor. // This is forge.card.CardColor not forge.CardColor.
@@ -329,7 +326,7 @@ public final class CardRules implements ICardCharacteristics {
this.faces[this.curFace].setColor(newCol); this.faces[this.curFace].setColor(newCol);
} }
break; break;
case 'D': case 'D':
if ("DeckHints".equals(key)) { if ("DeckHints".equals(key)) {
hints = new DeckHints(value); hints = new DeckHints(value);
@@ -337,67 +334,66 @@ public final class CardRules implements ICardCharacteristics {
needs = new DeckHints(value); needs = new DeckHints(value);
} }
break; break;
case 'H': case 'H':
if ("HandLifeModifier".equals(key)) { if ("HandLifeModifier".equals(key)) {
handLife = value; handLife = value;
} }
break; break;
case 'K': case 'K':
if ("K".equals(key)) { if ("K".equals(key)) {
this.faces[this.curFace].addKeyword(value); this.faces[this.curFace].addKeyword(value);
} }
break; break;
case 'L': case 'L':
if ("Loyalty".equals(key)) { if ("Loyalty".equals(key)) {
this.faces[this.curFace].setInitialLoyalty(Integer.valueOf(value)); this.faces[this.curFace].setInitialLoyalty(Integer.valueOf(value));
} }
break; break;
case 'M': case 'M':
if ("ManaCost".equals(key)) { if ("ManaCost".equals(key)) {
this.faces[this.curFace].setManaCost("no cost".equals(value) ? ManaCost.NO_COST this.faces[this.curFace].setManaCost("no cost".equals(value) ? ManaCost.NO_COST
: new ManaCost(new ManaCostParser(value))); : new ManaCost(new ManaCostParser(value)));
} }
break; break;
case 'N': case 'N':
if ("Name".equals(key)) { if ("Name".equals(key)) {
this.faces[this.curFace] = new CardFace(value); this.faces[this.curFace] = new CardFace(value);
} }
break; break;
case 'O': case 'O':
if ("Oracle".equals(key)) { if ("Oracle".equals(key)) {
this.faces[this.curFace].setOracleText(value); this.faces[this.curFace].setOracleText(value);
} }
break; break;
case 'P': case 'P':
if ("PT".equals(key)) { if ("PT".equals(key)) {
this.faces[this.curFace].setPtText(value); this.faces[this.curFace].setPtText(value);
} }
break; break;
case 'R': case 'R':
if ("R".equals(key)) { if ("R".equals(key)) {
this.faces[this.curFace].addReplacementEffect(value); this.faces[this.curFace].addReplacementEffect(value);
} }
break; break;
case 'S': case 'S':
if ("S".equals(key)) { if ("S".equals(key)) {
this.faces[this.curFace].addStaticAbility(value); this.faces[this.curFace].addStaticAbility(value);
} else if ( "SVar".equals(key) ) { } else if ( "SVar".equals(key) ) {
if ( null == value ) throw new IllegalArgumentException("SVar has no variable name"); if ( null == value ) throw new IllegalArgumentException("SVar has no variable name");
colonPos = value.indexOf(':'); colonPos = value.indexOf(':');
String variable = colonPos > 0 ? value.substring(0, colonPos) : value; String variable = colonPos > 0 ? value.substring(0, colonPos) : value;
value = colonPos > 0 ? value.substring(1+colonPos) : null; value = colonPos > 0 ? value.substring(1+colonPos) : null;
if ( "RemAIDeck".equals(variable) ) { if ( "RemAIDeck".equals(variable) ) {
this.removedFromAIDecks = "True".equalsIgnoreCase(value); this.removedFromAIDecks = "True".equalsIgnoreCase(value);
} else if ( "RemRandomDeck".equals(variable) ) { } else if ( "RemRandomDeck".equals(variable) ) {
@@ -412,7 +408,7 @@ public final class CardRules implements ICardCharacteristics {
// deprecated // deprecated
} }
break; break;
case 'T': case 'T':
if ("T".equals(key)) { if ("T".equals(key)) {
this.faces[this.curFace].addTrigger(value); this.faces[this.curFace].addTrigger(value);
@@ -423,21 +419,20 @@ public final class CardRules implements ICardCharacteristics {
} }
break; break;
} }
} }
/** /**
* The Class ParserCardnameTxtManaCost. * The Class ParserCardnameTxtManaCost.
*/ */
private static class ManaCostParser implements IParserManaCost { private static class ManaCostParser implements IParserManaCost {
private final StringTokenizer st; private final StringTokenizer st;
private int colorlessCost; private int colorlessCost;
public ManaCostParser(final String cost) { public ManaCostParser(final String cost) {
st = new StringTokenizer(cost, " "); st = new StringTokenizer(cost, " ");
this.colorlessCost = 0; this.colorlessCost = 0;
} }
@Override @Override
public final int getTotalColorlessCost() { public final int getTotalColorlessCost() {
if (this.hasNext()) { if (this.hasNext()) {
@@ -445,7 +440,7 @@ public final class CardRules implements ICardCharacteristics {
} }
return this.colorlessCost; return this.colorlessCost;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
@@ -455,7 +450,7 @@ public final class CardRules implements ICardCharacteristics {
public final boolean hasNext() { public final boolean hasNext() {
return st.hasMoreTokens(); return st.hasMoreTokens();
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
@@ -463,7 +458,6 @@ public final class CardRules implements ICardCharacteristics {
*/ */
@Override @Override
public final ManaCostShard next() { public final ManaCostShard next() {
final String unparsed = st.nextToken(); final String unparsed = st.nextToken();
// System.out.println(unparsed); // System.out.println(unparsed);
try { try {
@@ -472,10 +466,10 @@ public final class CardRules implements ICardCharacteristics {
return null; return null;
} }
catch (NumberFormatException nex) { } catch (NumberFormatException nex) { }
return ManaCostShard.parseNonGeneric(unparsed); return ManaCostShard.parseNonGeneric(unparsed);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *

View File

@@ -49,7 +49,7 @@ public final class PaperCard implements Comparable<IPaperCard>, InventoryItemFro
public String getName() { public String getName() {
return this.name; return this.name;
} }
@Override @Override
public String getEdition() { public String getEdition() {
return this.edition; return this.edition;
@@ -80,15 +80,11 @@ public final class PaperCard implements Comparable<IPaperCard>, InventoryItemFro
return this.rarity; return this.rarity;
} }
// @Override // @Override
// public String getImageKey() { // public String getImageKey() {
// return getImageLocator(getImageName(), getArtIndex(), true, false); // return getImageLocator(getImageName(), getArtIndex(), true, false);
// } // }
@Override @Override
public String getItemType() { public String getItemType() {
return "Card"; return "Card";
@@ -108,12 +104,12 @@ public final class PaperCard implements Comparable<IPaperCard>, InventoryItemFro
public String apply(final PaperCard from) { public String apply(final PaperCard from) {
return from.getName(); return from.getName();
} }
}; };
public PaperCard(final CardRules c, final String edition0, final CardRarity rare, final int index) { public PaperCard(final CardRules c, final String edition0, final CardRarity rare, final int index) {
this(c, edition0, rare, index, false); this(c, edition0, rare, index, false);
} }
public PaperCard(final CardRules c, final String edition0, final CardRarity rare, final int index, final boolean foil) { public PaperCard(final CardRules c, final String edition0, final CardRarity rare, final int index, final boolean foil) {
if ( edition0 == null || c == null || rare == null ) if ( edition0 == null || c == null || rare == null )
throw new IllegalArgumentException("Cannot create card without rules, edition or rarity"); throw new IllegalArgumentException("Cannot create card without rules, edition or rarity");
@@ -178,7 +174,6 @@ public final class PaperCard implements Comparable<IPaperCard>, InventoryItemFro
// return String.format("%s|%s", name, cardSet); // return String.format("%s|%s", name, cardSet);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *

View File

@@ -6,12 +6,12 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -47,7 +47,7 @@ import forge.util.FileUtil;
* <p> * <p>
* CardReader class. * CardReader class.
* </p> * </p>
* *
* @author Forge * @author Forge
* @version $Id$ * @version $Id$
*/ */
@@ -61,10 +61,10 @@ public class CardStorageReader implements ICardStorageReader {
private final boolean useThreadPool = FThreads.isMultiCoreSystem(); private final boolean useThreadPool = FThreads.isMultiCoreSystem();
public final static int NUMBER_OF_PARTS = 25; public final static int NUMBER_OF_PARTS = 25;
private final CountDownLatch cdl = new CountDownLatch(NUMBER_OF_PARTS); private final CountDownLatch cdl = new CountDownLatch(NUMBER_OF_PARTS);
private final IProgressObserver progressObserver; private final IProgressObserver progressObserver;
private transient File cardsfolder; private transient File cardsfolder;
private transient ZipFile zip; private transient ZipFile zip;
@@ -78,7 +78,7 @@ public class CardStorageReader implements ICardStorageReader {
* <p> * <p>
* Constructor for CardReader. * Constructor for CardReader.
* </p> * </p>
* *
* @param theCardsFolder * @param theCardsFolder
* indicates location of the cardsFolder * indicates location of the cardsFolder
* @param useZip * @param useZip
@@ -86,9 +86,9 @@ public class CardStorageReader implements ICardStorageReader {
* exists. * exists.
*/ */
public CardStorageReader(String cardDataDir, final boolean useZip, IProgressObserver progressObserver) { public CardStorageReader(String cardDataDir, final boolean useZip, IProgressObserver progressObserver) {
this.progressObserver = progressObserver != null ? progressObserver : IProgressObserver.emptyObserver; this.progressObserver = progressObserver != null ? progressObserver : IProgressObserver.emptyObserver;
this.cardsfolder = new File(cardDataDir); this.cardsfolder = new File(cardDataDir);
// These read data for lightweight classes. // These read data for lightweight classes.
if (!cardsfolder.exists()) { if (!cardsfolder.exists()) {
throw new RuntimeException("CardReader : constructor error -- " + cardsfolder.getAbsolutePath() + " file/folder not found."); throw new RuntimeException("CardReader : constructor error -- " + cardsfolder.getAbsolutePath() + " file/folder not found.");
@@ -98,8 +98,6 @@ public class CardStorageReader implements ICardStorageReader {
throw new RuntimeException("CardReader : constructor error -- not a directory -- " + cardsfolder.getAbsolutePath()); throw new RuntimeException("CardReader : constructor error -- not a directory -- " + cardsfolder.getAbsolutePath());
} }
final File zipFile = new File(cardsfolder, "cardsfolder.zip"); final File zipFile = new File(cardsfolder, "cardsfolder.zip");
if (useZip && zipFile.exists()) { if (useZip && zipFile.exists()) {
@@ -115,9 +113,8 @@ public class CardStorageReader implements ICardStorageReader {
} // CardReader() } // CardReader()
private final List<CardRules> loadCardsInRange(final List<File> files, int from, int to) { private final List<CardRules> loadCardsInRange(final List<File> files, int from, int to) {
CardRules.Reader rulesReader = new CardRules.Reader(); CardRules.Reader rulesReader = new CardRules.Reader();
List<CardRules> result = new ArrayList<CardRules>(); List<CardRules> result = new ArrayList<CardRules>();
for(int i = from; i < to; i++) { for(int i = from; i < to; i++) {
File cardTxtFile = files.get(i); File cardTxtFile = files.get(i);
@@ -125,11 +122,10 @@ public class CardStorageReader implements ICardStorageReader {
} }
return result; return result;
} }
private final List<CardRules> loadCardsInRangeFromZip(final List<ZipEntry> files, int from, int to) { private final List<CardRules> loadCardsInRangeFromZip(final List<ZipEntry> files, int from, int to) {
CardRules.Reader rulesReader = new CardRules.Reader(); CardRules.Reader rulesReader = new CardRules.Reader();
List<CardRules> result = new ArrayList<CardRules>(); List<CardRules> result = new ArrayList<CardRules>();
for(int i = from; i < to; i++) { for(int i = from; i < to; i++) {
ZipEntry ze = files.get(i); ZipEntry ze = files.get(i);
@@ -137,15 +133,14 @@ public class CardStorageReader implements ICardStorageReader {
result.add(this.loadCard(rulesReader, ze)); result.add(this.loadCard(rulesReader, ze));
} }
return result; return result;
} }
/** /**
* Starts reading cards into memory until the given card is found. * Starts reading cards into memory until the given card is found.
* *
* After that, we save our place in the list of cards (on disk) in case we * After that, we save our place in the list of cards (on disk) in case we
* need to load more. * need to load more.
* *
* @return the Card or null if it was not found. * @return the Card or null if it was not found.
*/ */
public final List<CardRules> loadCards() { public final List<CardRules> loadCards() {
@@ -154,7 +149,7 @@ public class CardStorageReader implements ICardStorageReader {
final List<Callable<List<CardRules>>> tasks; final List<Callable<List<CardRules>>> tasks;
long estimatedFilesRemaining; long estimatedFilesRemaining;
// Iterate through txt files or zip archive. // Iterate through txt files or zip archive.
// Report relevant numbers to progress monitor model. // Report relevant numbers to progress monitor model.
if (this.zip == null) { if (this.zip == null) {
@@ -162,7 +157,6 @@ public class CardStorageReader implements ICardStorageReader {
estimatedFilesRemaining = allFiles.size(); estimatedFilesRemaining = allFiles.size();
tasks = makeTaskListForFiles(allFiles); tasks = makeTaskListForFiles(allFiles);
} else { } else {
estimatedFilesRemaining = this.zip.size(); estimatedFilesRemaining = this.zip.size();
ZipEntry entry; ZipEntry entry;
List<ZipEntry> entries = new ArrayList<ZipEntry>(); List<ZipEntry> entries = new ArrayList<ZipEntry>();
@@ -180,9 +174,9 @@ public class CardStorageReader implements ICardStorageReader {
StopWatch sw = new StopWatch(); StopWatch sw = new StopWatch();
sw.start(); sw.start();
List<CardRules> res = executeLoadTask(tasks); List<CardRules> res = executeLoadTask(tasks);
sw.stop(); sw.stop();
final long timeOnParse = sw.getTime(); final long timeOnParse = sw.getTime();
System.out.printf("Read cards: %s %s in %d ms (%d parts) %s%n", estimatedFilesRemaining, zip == null? "files" : "archived files", timeOnParse, NUMBER_OF_PARTS, useThreadPool ? "using thread pool" : "in same thread"); System.out.printf("Read cards: %s %s in %d ms (%d parts) %s%n", estimatedFilesRemaining, zip == null? "files" : "archived files", timeOnParse, NUMBER_OF_PARTS, useThreadPool ? "using thread pool" : "in same thread");
@@ -215,13 +209,13 @@ public class CardStorageReader implements ICardStorageReader {
} catch (Exception e) { // this clause comes from non-threaded branch } catch (Exception e) { // this clause comes from non-threaded branch
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return result; return result;
} }
private List<Callable<List<CardRules>>> makeTaskListForZip(final List<ZipEntry> entries) { private List<Callable<List<CardRules>>> makeTaskListForZip(final List<ZipEntry> entries) {
int totalFiles = entries.size(); int totalFiles = entries.size();
int filesPerPart = totalFiles / NUMBER_OF_PARTS; int filesPerPart = totalFiles / NUMBER_OF_PARTS;
final List<Callable<List<CardRules>>> tasks = new ArrayList<Callable<List<CardRules>>>(); final List<Callable<List<CardRules>>> tasks = new ArrayList<Callable<List<CardRules>>>();
for (int iPart = 0; iPart < NUMBER_OF_PARTS; iPart++) { for (int iPart = 0; iPart < NUMBER_OF_PARTS; iPart++) {
final int from = iPart * filesPerPart; final int from = iPart * filesPerPart;
@@ -241,7 +235,7 @@ public class CardStorageReader implements ICardStorageReader {
private List<Callable<List<CardRules>>> makeTaskListForFiles(final List<File> allFiles) { private List<Callable<List<CardRules>>> makeTaskListForFiles(final List<File> allFiles) {
int totalFiles = allFiles.size(); int totalFiles = allFiles.size();
int filesPerPart = totalFiles / NUMBER_OF_PARTS; int filesPerPart = totalFiles / NUMBER_OF_PARTS;
final List<Callable<List<CardRules>>> tasks = new ArrayList<Callable<List<CardRules>>>(); final List<Callable<List<CardRules>>> tasks = new ArrayList<Callable<List<CardRules>>>();
for (int iPart = 0; iPart < NUMBER_OF_PARTS; iPart++) { for (int iPart = 0; iPart < NUMBER_OF_PARTS; iPart++) {
final int from = iPart * filesPerPart; final int from = iPart * filesPerPart;
@@ -257,8 +251,8 @@ public class CardStorageReader implements ICardStorageReader {
}); });
} }
return tasks; return tasks;
} }
public static List<File> collectCardFiles(List<File> accumulator, File startDir) { public static List<File> collectCardFiles(List<File> accumulator, File startDir) {
String[] list = startDir.list(); String[] list = startDir.list();
for (String filename : list) { for (String filename : list) {
@@ -282,10 +276,10 @@ public class CardStorageReader implements ICardStorageReader {
* <p> * <p>
* load a card. * load a card.
* </p> * </p>
* *
* @param inputStream * @param inputStream
* the stream from which to load the card's information * the stream from which to load the card's information
* *
* @return the card loaded from the stream * @return the card loaded from the stream
*/ */
protected final CardRules loadCard(CardRules.Reader reader, final InputStream inputStream) { protected final CardRules loadCard(CardRules.Reader reader, final InputStream inputStream) {
@@ -299,10 +293,10 @@ public class CardStorageReader implements ICardStorageReader {
/** /**
* Load a card from a txt file. * Load a card from a txt file.
* *
* @param pathToTxtFile * @param pathToTxtFile
* the full or relative path to the file to load * the full or relative path to the file to load
* *
* @return a new Card instance * @return a new Card instance
*/ */
protected final CardRules loadCard(final CardRules.Reader reader, final File file) { protected final CardRules loadCard(final CardRules.Reader reader, final File file) {
@@ -326,10 +320,10 @@ public class CardStorageReader implements ICardStorageReader {
/** /**
* Load a card from an entry in a zip file. * Load a card from an entry in a zip file.
* *
* @param entry * @param entry
* to load from * to load from
* *
* @return a new Card instance * @return a new Card instance
*/ */
protected final CardRules loadCard(final CardRules.Reader rulesReader, final ZipEntry entry) { protected final CardRules loadCard(final CardRules.Reader rulesReader, final ZipEntry entry) {