checkstyle

This commit is contained in:
jendave
2012-02-24 09:16:07 +00:00
parent fceab3b7ed
commit 4daa58c3c0
60 changed files with 2656 additions and 1502 deletions

View File

@@ -711,7 +711,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>11.0.1</version>
<version>11.0.2</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>

View File

@@ -62,7 +62,7 @@ public class CombatUtil {
return false;
}
for (final Card c : AllZoneUtil.getCardsIn(Constant.Zone.Battlefield)) {
for (String keyword : c.getKeyword()) {
for (final String keyword : c.getKeyword()) {
if (keyword.equals("No more than one creature can block each combat.")
&& (combat.getAllBlockers().size() > 0)) {
return false;
@@ -405,7 +405,8 @@ public class CombatUtil {
if (CombatUtil.canBlock(attacker, blocker, combat)) {
boolean must = true;
if (attacker.hasKeyword("CARDNAME can't be blocked except by two or more creatures.")) {
CardList possibleBlockers = combat.getDefendingPlayer().getCardsIn(Zone.Battlefield).getType("Creature");
final CardList possibleBlockers = combat.getDefendingPlayer().getCardsIn(Zone.Battlefield)
.getType("Creature");
possibleBlockers.remove(blocker);
if (!CombatUtil.canBeBlocked(attacker, possibleBlockers)) {
must = false;
@@ -422,7 +423,7 @@ public class CombatUtil {
for (final Card attacker : attackers) {
// don't accept one blocker for attackers with this keyword
if (attacker.hasKeyword("CARDNAME can't be blocked except by two or more creatures.")
&& combat.getBlockers(attacker).size() == 1) {
&& (combat.getBlockers(attacker).size() == 1)) {
return false;
}
}
@@ -452,12 +453,12 @@ public class CombatUtil {
return false;
}
CardList attackers = new CardList(combat.getAttackers());
CardList attackersWithLure = new CardList();
for (Card attacker : attackers) {
final CardList attackers = new CardList(combat.getAttackers());
final CardList attackersWithLure = new CardList();
for (final Card attacker : attackers) {
if (attacker.hasStartOfKeyword("All creatures able to block CARDNAME do so.")
|| (attacker.hasStartOfKeyword("CARDNAME must be blocked if able.")
&& combat.getBlockers(attacker).isEmpty())) {
|| (attacker.hasStartOfKeyword("CARDNAME must be blocked if able.") && combat.getBlockers(attacker)
.isEmpty())) {
attackersWithLure.add(attacker);
}
}
@@ -466,7 +467,8 @@ public class CombatUtil {
if (CombatUtil.canBeBlocked(attacker, combat) && CombatUtil.canBlock(attacker, blocker)) {
boolean canBe = true;
if (attacker.hasKeyword("CARDNAME can't be blocked except by two or more creatures.")) {
CardList blockers = combat.getDefendingPlayer().getCardsIn(Zone.Battlefield).getType("Creature");
final CardList blockers = combat.getDefendingPlayer().getCardsIn(Zone.Battlefield)
.getType("Creature");
blockers.remove(blocker);
if (!CombatUtil.canBeBlocked(attacker, blockers)) {
canBe = false;
@@ -482,7 +484,8 @@ public class CombatUtil {
if (CombatUtil.canBeBlocked(attacker, combat) && CombatUtil.canBlock(attacker, blocker)) {
boolean canBe = true;
if (attacker.hasKeyword("CARDNAME can't be blocked except by two or more creatures.")) {
CardList blockers = combat.getDefendingPlayer().getCardsIn(Zone.Battlefield).getType("Creature");
final CardList blockers = combat.getDefendingPlayer().getCardsIn(Zone.Battlefield)
.getType("Creature");
blockers.remove(blocker);
if (!CombatUtil.canBeBlocked(attacker, blockers)) {
canBe = false;
@@ -707,7 +710,7 @@ public class CombatUtil {
public static boolean canAttack(final Card c, final Combat combat) {
for (final Card card : AllZoneUtil.getCardsIn(Constant.Zone.Battlefield)) {
for (String keyword : card.getKeyword()) {
for (final String keyword : card.getKeyword()) {
if (keyword.equals("No more than one creature can attack each combat.")
&& (combat.getAttackers().length > 0)) {
return false;
@@ -721,8 +724,7 @@ public class CombatUtil {
&& card.getController().getOpponent().isPlayer(c.getController())) {
return false;
}
if (keyword.equals("CARDNAME can only attack alone.")
&& card.isAttacking()) {
if (keyword.equals("CARDNAME can only attack alone.") && card.isAttacking()) {
return false;
}
}
@@ -1063,8 +1065,9 @@ public class CombatUtil {
final CardList blockers = combat.getBlockers(attacker);
if (blockers.size() == 0 || attacker.hasKeyword("You may have CARDNAME assign its combat damage "
+ "as though it weren't blocked.")) {
if ((blockers.size() == 0)
|| attacker.hasKeyword("You may have CARDNAME assign its combat damage "
+ "as though it weren't blocked.")) {
unblocked.add(attacker);
} else if (attacker.hasKeyword("Trample")
&& (CombatUtil.getAttack(attacker) > CombatUtil.totalShieldDamage(attacker, blockers))) {
@@ -1104,8 +1107,9 @@ public class CombatUtil {
final CardList blockers = combat.getBlockers(attacker);
if (blockers.size() == 0 || attacker.hasKeyword("You may have CARDNAME assign its combat damage"
+ " as though it weren't blocked.")) {
if ((blockers.size() == 0)
|| attacker.hasKeyword("You may have CARDNAME assign its combat damage"
+ " as though it weren't blocked.")) {
unblocked.add(attacker);
} else if (attacker.hasKeyword("Trample")
&& (CombatUtil.getAttack(attacker) > CombatUtil.totalShieldDamage(attacker, blockers))) {
@@ -1140,7 +1144,7 @@ public class CombatUtil {
return false;
}
//check for creatures that must be blocked
// check for creatures that must be blocked
final CardList attackers = combat.sortAttackerByDefender()[0];
for (final Card attacker : attackers) {
@@ -1194,7 +1198,7 @@ public class CombatUtil {
return false;
}
//check for creatures that must be blocked
// check for creatures that must be blocked
final CardList attackers = combat.sortAttackerByDefender()[0];
for (final Card attacker : attackers) {
@@ -1437,8 +1441,8 @@ public class CombatUtil {
}
if (trigParams.containsKey("ValidCard")) {
if (!TriggerReplacementBase.matchesValid(attacker, trigParams.get("ValidCard").split(","), source)
&& !(combat.isAttacking(source) && TriggerReplacementBase.matchesValid(source, trigParams.get("ValidCard")
.split(","), source))) {
&& !(combat.isAttacking(source) && TriggerReplacementBase.matchesValid(source,
trigParams.get("ValidCard").split(","), source))) {
return false;
}
}
@@ -1518,10 +1522,11 @@ public class CombatUtil {
power += defender.getKeywordMagnitude("Bushido");
//look out for continuous static abilities that only care for blocking creatures
CardList cardList = AllZoneUtil.getCardsIn(Constant.Zone.Battlefield);
for (Card card : cardList) {
for (StaticAbility stAb : card.getStaticAbilities()) {
// look out for continuous static abilities that only care for blocking
// creatures
final CardList cardList = AllZoneUtil.getCardsIn(Constant.Zone.Battlefield);
for (final Card card : cardList) {
for (final StaticAbility stAb : card.getStaticAbilities()) {
final HashMap<String, String> params = stAb.getMapParams();
if (!params.get("Mode").equals("Continuous")) {
continue;
@@ -1529,7 +1534,7 @@ public class CombatUtil {
if (!params.containsKey("Affected") || !params.get("Affected").contains("blocking")) {
continue;
}
String valid = params.get("Affected").replace("blocking", "Creature");
final String valid = params.get("Affected").replace("blocking", "Creature");
if (!defender.isValid(valid, card.getController(), card)) {
continue;
}
@@ -1700,10 +1705,11 @@ public class CombatUtil {
theTriggers.addAll(defender.getTriggers());
}
//look out for continuous static abilities that only care for attacking creatures
CardList cardList = AllZoneUtil.getCardsIn(Constant.Zone.Battlefield);
for (Card card : cardList) {
for (StaticAbility stAb : card.getStaticAbilities()) {
// look out for continuous static abilities that only care for attacking
// creatures
final CardList cardList = AllZoneUtil.getCardsIn(Constant.Zone.Battlefield);
for (final Card card : cardList) {
for (final StaticAbility stAb : card.getStaticAbilities()) {
final HashMap<String, String> params = stAb.getMapParams();
if (!params.get("Mode").equals("Continuous")) {
continue;
@@ -1711,7 +1717,7 @@ public class CombatUtil {
if (!params.containsKey("Affected") || !params.get("Affected").contains("attacking")) {
continue;
}
String valid = params.get("Affected").replace("attacking", "Creature");
final String valid = params.get("Affected").replace("attacking", "Creature");
if (!attacker.isValid(valid, card.getController(), card)) {
continue;
}
@@ -1785,7 +1791,7 @@ public class CombatUtil {
bonus = bonus.replace("TriggerCount$NumBlockers", "Number$1");
}
power += CardFactoryUtil.xCount(source, bonus);
}
}
return power;
@@ -1815,10 +1821,11 @@ public class CombatUtil {
theTriggers.addAll(defender.getTriggers());
}
//look out for continuous static abilities that only care for attacking creatures
CardList cardList = AllZoneUtil.getCardsIn(Constant.Zone.Battlefield);
for (Card card : cardList) {
for (StaticAbility stAb : card.getStaticAbilities()) {
// look out for continuous static abilities that only care for attacking
// creatures
final CardList cardList = AllZoneUtil.getCardsIn(Constant.Zone.Battlefield);
for (final Card card : cardList) {
for (final StaticAbility stAb : card.getStaticAbilities()) {
final HashMap<String, String> params = stAb.getMapParams();
if (!params.get("Mode").equals("Continuous")) {
continue;
@@ -1826,7 +1833,7 @@ public class CombatUtil {
if (!params.containsKey("Affected") || !params.get("Affected").contains("attacking")) {
continue;
}
String valid = params.get("Affected").replace("attacking", "Creature");
final String valid = params.get("Affected").replace("attacking", "Creature");
if (!attacker.isValid(valid, card.getController(), card)) {
continue;
}
@@ -1919,7 +1926,7 @@ public class CombatUtil {
bonus = bonus.replace("TriggerCount$NumBlockers", "Number$1");
}
toughness += CardFactoryUtil.xCount(source, bonus);
}
}
return toughness;
@@ -1964,10 +1971,10 @@ public class CombatUtil {
if (((attacker.hasKeyword("Indestructible") || (ComputerUtil.canRegenerate(attacker) && !withoutAbilities)) && !(defender
.hasKeyword("Wither") || defender.hasKeyword("Infect")))
|| (attacker.hasKeyword("Persist") && !attacker.canHaveCountersPlacedOnIt(Counters.M1M1)
&& attacker.getCounters(Counters.M1M1) == 0)
|| (attacker.hasKeyword("Undying") && !attacker.canHaveCountersPlacedOnIt(Counters.P1P1)
&& attacker.getCounters(Counters.P1P1) == 0)) {
|| (attacker.hasKeyword("Persist") && !attacker.canHaveCountersPlacedOnIt(Counters.M1M1) && (attacker
.getCounters(Counters.M1M1) == 0))
|| (attacker.hasKeyword("Undying") && !attacker.canHaveCountersPlacedOnIt(Counters.P1P1) && (attacker
.getCounters(Counters.P1P1) == 0))) {
return false;
}
@@ -2098,10 +2105,10 @@ public class CombatUtil {
if (((defender.hasKeyword("Indestructible") || (ComputerUtil.canRegenerate(defender) && !withoutAbilities)) && !(attacker
.hasKeyword("Wither") || attacker.hasKeyword("Infect")))
|| (defender.hasKeyword("Persist") && !defender.canHaveCountersPlacedOnIt(Counters.M1M1)
&& defender.getCounters(Counters.M1M1) == 0)
|| (defender.hasKeyword("Undying") && !defender.canHaveCountersPlacedOnIt(Counters.P1P1)
&& defender.getCounters(Counters.P1P1) == 0)) {
|| (defender.hasKeyword("Persist") && !defender.canHaveCountersPlacedOnIt(Counters.M1M1) && (defender
.getCounters(Counters.M1M1) == 0))
|| (defender.hasKeyword("Undying") && !defender.canHaveCountersPlacedOnIt(Counters.P1P1) && (defender
.getCounters(Counters.P1P1) == 0))) {
return false;
}
@@ -2200,7 +2207,7 @@ public class CombatUtil {
* @return a String
*/
public static String getCombatAttackForLog() {
StringBuilder sb = new StringBuilder();
final StringBuilder sb = new StringBuilder();
// Loop through Defenders
// Append Defending Player/Planeswalker
@@ -2215,7 +2222,7 @@ public class CombatUtil {
}
sb.append(combat.getAttackingPlayer()).append(" declared ");
for (Card attacker : attackers[def]) {
for (final Card attacker : attackers[def]) {
sb.append(attacker).append(" ");
}
@@ -2231,7 +2238,7 @@ public class CombatUtil {
* @return a String
*/
public static String getCombatBlockForLog() {
StringBuilder sb = new StringBuilder();
final StringBuilder sb = new StringBuilder();
Card[] defend = null;

View File

@@ -920,36 +920,29 @@ public class ComputerUtil {
* @return a {@link java.util.ArrayList} object.
* @since 1.0.15
*/
/*public static ArrayList<String> getProduceableColors(final AbilityMana m, final Player player) {
final ArrayList<String> colors = new ArrayList<String>();
// if the mana ability is not avaiable move to the next one
m.setActivatingPlayer(player);
if (!m.canPlay()) {
return colors;
}
if (!colors.contains(Constant.Color.BLACK) && m.isBasic() && m.mana().equals("B")) {
colors.add(Constant.Color.BLACK);
}
if (!colors.contains(Constant.Color.WHITE) && m.isBasic() && m.mana().equals("W")) {
colors.add(Constant.Color.WHITE);
}
if (!colors.contains(Constant.Color.GREEN) && m.isBasic() && m.mana().equals("G")) {
colors.add(Constant.Color.GREEN);
}
if (!colors.contains(Constant.Color.RED) && m.isBasic() && m.mana().equals("R")) {
colors.add(Constant.Color.RED);
}
if (!colors.contains(Constant.Color.BLUE) && m.isBasic() && m.mana().equals("U")) {
colors.add(Constant.Color.BLUE);
}
if (!colors.contains(Constant.Color.COLORLESS) && m.isBasic() && m.mana().equals("1")) {
colors.add(Constant.Color.COLORLESS);
}
return colors;
}*/
/*
* public static ArrayList<String> getProduceableColors(final AbilityMana m,
* final Player player) { final ArrayList<String> colors = new
* ArrayList<String>();
*
* // if the mana ability is not avaiable move to the next one
* m.setActivatingPlayer(player); if (!m.canPlay()) { return colors; }
*
* if (!colors.contains(Constant.Color.BLACK) && m.isBasic() &&
* m.mana().equals("B")) { colors.add(Constant.Color.BLACK); } if
* (!colors.contains(Constant.Color.WHITE) && m.isBasic() &&
* m.mana().equals("W")) { colors.add(Constant.Color.WHITE); } if
* (!colors.contains(Constant.Color.GREEN) && m.isBasic() &&
* m.mana().equals("G")) { colors.add(Constant.Color.GREEN); } if
* (!colors.contains(Constant.Color.RED) && m.isBasic() &&
* m.mana().equals("R")) { colors.add(Constant.Color.RED); } if
* (!colors.contains(Constant.Color.BLUE) && m.isBasic() &&
* m.mana().equals("U")) { colors.add(Constant.Color.BLUE); } if
* (!colors.contains(Constant.Color.COLORLESS) && m.isBasic() &&
* m.mana().equals("1")) { colors.add(Constant.Color.COLORLESS); }
*
* return colors; }
*/
/**
* <p>
@@ -1094,58 +1087,43 @@ public class ComputerUtil {
* @return a {@link java.util.ArrayList} object.
* @since 1.0.15
*/
/*public static ArrayList<AbilityMana> sortForNeeded(final ManaCost cost, final ArrayList<AbilityMana> manaAbilities,
final Player player) {
ArrayList<String> colors;
final ArrayList<String> colorsNeededToAvoidNegativeEffect = cost.getManaNeededToAvoidNegativeEffect();
final ArrayList<AbilityMana> res = new ArrayList<AbilityMana>();
final ManaCost onlyColored = new ManaCost(cost.toString());
onlyColored.removeColorlessMana();
for (final AbilityMana am : manaAbilities) {
colors = ComputerUtil.getProduceableColors(am, player);
for (int j = 0; j < colors.size(); j++) {
if (onlyColored.isNeeded(colors.get(j))) {
res.add(am);
break;
}
for (final String col : colorsNeededToAvoidNegativeEffect) {
if (col.equalsIgnoreCase(colors.get(j))
|| CardUtil.getShortColor(col).equalsIgnoreCase(colors.get(j))) {
res.add(am);
}
}
}
}
for (final AbilityMana am : manaAbilities) {
if (res.contains(am)) {
break;
}
colors = ComputerUtil.getProduceableColors(am, player);
for (int j = 0; j < colors.size(); j++) {
if (cost.isNeeded(colors.get(j))) {
res.add(am);
break;
}
for (final String col : colorsNeededToAvoidNegativeEffect) {
if (col.equalsIgnoreCase(colors.get(j))
|| CardUtil.getShortColor(col).equalsIgnoreCase(colors.get(j))) {
res.add(am);
}
}
}
}
return res;
}*/
/*
* public static ArrayList<AbilityMana> sortForNeeded(final ManaCost cost,
* final ArrayList<AbilityMana> manaAbilities, final Player player) {
*
* ArrayList<String> colors;
*
* final ArrayList<String> colorsNeededToAvoidNegativeEffect =
* cost.getManaNeededToAvoidNegativeEffect();
*
* final ArrayList<AbilityMana> res = new ArrayList<AbilityMana>();
*
* final ManaCost onlyColored = new ManaCost(cost.toString());
*
* onlyColored.removeColorlessMana();
*
* for (final AbilityMana am : manaAbilities) { colors =
* ComputerUtil.getProduceableColors(am, player); for (int j = 0; j <
* colors.size(); j++) { if (onlyColored.isNeeded(colors.get(j))) {
* res.add(am); break; } for (final String col :
* colorsNeededToAvoidNegativeEffect) { if
* (col.equalsIgnoreCase(colors.get(j)) ||
* CardUtil.getShortColor(col).equalsIgnoreCase(colors.get(j))) {
* res.add(am); } } } }
*
* for (final AbilityMana am : manaAbilities) {
*
* if (res.contains(am)) { break; }
*
* colors = ComputerUtil.getProduceableColors(am, player); for (int j = 0; j
* < colors.size(); j++) { if (cost.isNeeded(colors.get(j))) { res.add(am);
* break; } for (final String col : colorsNeededToAvoidNegativeEffect) { if
* (col.equalsIgnoreCase(colors.get(j)) ||
* CardUtil.getShortColor(col).equalsIgnoreCase(colors.get(j))) {
* res.add(am); } } } }
*
* return res; }
*/
/**
* <p>
@@ -1942,9 +1920,11 @@ public class ComputerUtil {
/**
* Contains useful keyword.
*
* @param keywords the keywords
* @param card the card
*
* @param keywords
* the keywords
* @param card
* the card
* @return true, if successful
*/
public static boolean containsUsefulKeyword(final ArrayList<String> keywords, final Card card) {
@@ -1958,62 +1938,56 @@ public class ComputerUtil {
/**
* Checks if is useful keyword.
*
* @param keyword the keyword
* @param card the card
*
* @param keyword
* the keyword
* @param card
* the card
* @return true, if is useful keyword
*/
public static boolean isUsefulKeyword(final String keyword, final Card card) {
PhaseHandler ph = AllZone.getPhaseHandler();
Player computer = AllZone.getComputerPlayer();
Player human = AllZone.getHumanPlayer();
final PhaseHandler ph = AllZone.getPhaseHandler();
final Player computer = AllZone.getComputerPlayer();
final Player human = AllZone.getHumanPlayer();
final boolean evasive = (keyword.endsWith("Flying") || keyword.endsWith("Horsemanship")
|| keyword.endsWith("Unblockable") || keyword.endsWith("Fear")
|| keyword.endsWith("Intimidate"));
|| keyword.endsWith("Unblockable") || keyword.endsWith("Fear") || keyword.endsWith("Intimidate"));
if (!CardUtil.isStackingKeyword(keyword) && card.hasKeyword(keyword)) {
return false;
}
// give evasive keywords to creatures that can attack
if (evasive) {
if (ph.isPlayerTurn(human) || !CombatUtil.canAttack(card)
|| ph.isAfter(Constant.Phase.COMBAT_DECLARE_ATTACKERS_INSTANT_ABILITY)
|| (card.getNetCombatDamage() <= 0)
|| AllZoneUtil.getCreaturesInPlay(human).size() < 1) {
|| ph.isAfter(Constant.Phase.COMBAT_DECLARE_ATTACKERS_INSTANT_ABILITY)
|| (card.getNetCombatDamage() <= 0) || (AllZoneUtil.getCreaturesInPlay(human).size() < 1)) {
return false;
}
} else if (keyword.equals("Defender") || keyword.endsWith("CARDNAME can't attack.")) {
if (card.getController().isComputer()
|| ph.isPlayerTurn(computer)
|| !CombatUtil.canAttack(card) || (card.getNetCombatDamage() <= 0)) {
if (card.getController().isComputer() || ph.isPlayerTurn(computer) || !CombatUtil.canAttack(card)
|| (card.getNetCombatDamage() <= 0)) {
return false;
}
} else if (keyword.endsWith("CARDNAME can't block.")) {
if (card.getController().isComputer() || ph.isPlayerTurn(human)
|| !CombatUtil.canBlock(card)) {
if (card.getController().isComputer() || ph.isPlayerTurn(human) || !CombatUtil.canBlock(card)) {
return false;
}
} else if (keyword.endsWith("This card doesn't untap during your next untap step.")) {
if (ph.isBefore(Constant.Phase.MAIN2) || card.isUntapped()
|| ph.isPlayerTurn(human)) {
if (ph.isBefore(Constant.Phase.MAIN2) || card.isUntapped() || ph.isPlayerTurn(human)) {
return false;
}
} else if (keyword.endsWith("CARDNAME attacks each turn if able.")) {
if (ph.isPlayerTurn(human) || !CombatUtil.canAttack(card)
|| !CombatUtil.canBeBlocked(card)) {
if (ph.isPlayerTurn(human) || !CombatUtil.canAttack(card) || !CombatUtil.canBeBlocked(card)) {
return false;
}
} else if (keyword.endsWith("Shroud")) {
//TODO: check stack for spells and abilities
// TODO: check stack for spells and abilities
return false;
} else if (keyword.startsWith("Rampage")) {
if (ph.isPlayerTurn(human) || !CombatUtil.canAttack(card)
|| !CombatUtil.canBeBlocked(card)
|| AllZoneUtil.getCreaturesInPlay(human).size() < 2) {
if (ph.isPlayerTurn(human) || !CombatUtil.canAttack(card) || !CombatUtil.canBeBlocked(card)
|| (AllZoneUtil.getCreaturesInPlay(human).size() < 2)) {
return false;
}
} else if (keyword.endsWith("Haste")) {
if (!card.hasSickness() || ph.isPlayerTurn(human)
|| !CombatUtil.canAttackNextTurn(card) || card.isTapped()
} else if (keyword.endsWith("Haste")) {
if (!card.hasSickness() || ph.isPlayerTurn(human) || !CombatUtil.canAttackNextTurn(card) || card.isTapped()
|| card.hasKeyword("CARDNAME can attack as though it had haste.")
|| ph.isAfter(Constant.Phase.COMBAT_DECLARE_ATTACKERS)) {
return false;

View File

@@ -243,6 +243,15 @@ public class BoosterGenerator {
return temp;
}
/**
* Gets the booster pack.
*
* @param numbers the numbers
* @param nRareSlots the n rare slots
* @param nDoubls the n doubls
* @param nAnyCard the n any card
* @return the booster pack
*/
public final List<CardPrinted> getBoosterPack(final Map<CardRarity, Integer> numbers,
final int nRareSlots, final int nDoubls, final int nAnyCard) {
return getBoosterPack(numbers.get(CardRarity.Common), numbers.get(CardRarity.Uncommon), nRareSlots,

View File

@@ -17,9 +17,9 @@
*/
package forge.card;
import forge.game.GameFormat;
import net.slightlymagic.braids.util.lambda.Lambda1;
import net.slightlymagic.maxmtg.Predicate;
import forge.game.GameFormat;
/**
* <p>
@@ -66,7 +66,8 @@ public final class CardEdition implements Comparable<CardEdition> { // immutable
* @param booster
* the booster
*/
public CardEdition(final int index, final String name, final String code, final String code2, final BoosterData booster) {
public CardEdition(final int index, final String name, final String code, final String code2,
final BoosterData booster) {
this.code = code;
this.code2 = code2;
this.index = index;
@@ -321,7 +322,7 @@ public final class CardEdition implements Comparable<CardEdition> { // immutable
/**
* Gets the total.
*
*
* @return the total
*/
public final int getTotal() {
@@ -346,15 +347,19 @@ public final class CardEdition implements Comparable<CardEdition> { // immutable
/** The Constant canMakeBooster. */
public static final Predicate<CardEdition> CAN_MAKE_BOOSTER = new CanMakeBooster();
private static class CanMakeBooster extends Predicate<CardEdition> {
@Override
public boolean isTrue(final CardEdition subject) {
return subject.canGenerateBooster();
}
}
/**
* Checks if is legal in format.
*
* @param format the format
* @return the predicate
*/
public final static Predicate<CardEdition> isLegalInFormat(final GameFormat format) {
return new LegalInFormat(format);
}

View File

@@ -41,13 +41,21 @@ public final class EditionUtils {
private final List<CardEdition> allSets;
/**
* Gets the all sets.
*
* @return the all sets
*/
public final List<CardEdition> getAllSets() {
return allSets;
return this.allSets;
}
/**
* Instantiates a new edition utils.
*/
public EditionUtils() {
allSets = loadSetData(loadBoosterData());
allBlocks = loadBlockData();
this.allSets = this.loadSetData(this.loadBoosterData());
this.allBlocks = this.loadBlockData();
}
/** Constant <code>setData</code>. */
@@ -60,7 +68,7 @@ public final class EditionUtils {
* @return the blocks
*/
public List<CardBlock> getBlocks() {
return allBlocks;
return this.allBlocks;
}
/**
@@ -71,7 +79,7 @@ public final class EditionUtils {
* @return the sets the by code
*/
public CardEdition getEditionByCode(final String code) {
return setsByCode.get(code);
return this.setsByCode.get(code);
}
/**
@@ -82,7 +90,7 @@ public final class EditionUtils {
* @return the sets the by code or throw
*/
public CardEdition getEditionByCodeOrThrow(final String code) {
final CardEdition set = setsByCode.get(code);
final CardEdition set = this.setsByCode.get(code);
if (null == set) {
throw new RuntimeException(String.format("Edition with code '%s' not found", code));
}
@@ -98,7 +106,7 @@ public final class EditionUtils {
* @return the code2 by code
*/
public String getCode2ByCode(final String code) {
final CardEdition set = setsByCode.get(code);
final CardEdition set = this.setsByCode.get(code);
return set == null ? "" : set.getCode2();
}
@@ -146,26 +154,24 @@ public final class EditionUtils {
private List<CardEdition> loadSetData(final Map<String, CardEdition.BoosterData> boosters) {
final ArrayList<String> fData = FileUtil.readFile("res/blockdata/setdata.txt");
final List<CardEdition> allSets = new ArrayList<CardEdition>();
for (final String s : fData) {
if (StringUtils.isBlank(s)) {
continue;
}
FileSection section = FileSection.parse(s, ":", "|");
String code = section.get("code3");
int index = section.getInt("index", -1);
String code2 = section.get("code2");
String name = section.get("name");
String alias = section.get("alias");
final FileSection section = FileSection.parse(s, ":", "|");
final String code = section.get("code3");
final int index = section.getInt("index", -1);
final String code2 = section.get("code2");
final String name = section.get("name");
final String alias = section.get("alias");
final CardEdition set = new CardEdition(index, name, code, code2, boosters.get(code));
//boosters.remove(code);
setsByCode.put(code, set);
// boosters.remove(code);
this.setsByCode.put(code, set);
if (alias != null) {
setsByCode.put(alias, set);
this.setsByCode.put(alias, set);
}
allSets.add(set);
}
@@ -199,9 +205,9 @@ public final class EditionUtils {
} else if ("index".equals(key)) {
index = Integer.parseInt(kv[1]);
} else if ("set0".equals(key) || "set1".equals(key) || "set2".equals(key)) {
sets.add(getEditionByCodeOrThrow(kv[1]));
sets.add(this.getEditionByCodeOrThrow(kv[1]));
} else if ("landsetcode".equals(key)) {
landSet = getEditionByCodeOrThrow(kv[1]);
landSet = this.getEditionByCodeOrThrow(kv[1]);
} else if ("draftpacks".equals(key)) {
draftBoosters = Integer.parseInt(kv[1]);
} else if ("sealedpacks".equals(key)) {

View File

@@ -1,3 +1,20 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.card;
import java.util.ArrayList;
@@ -12,6 +29,9 @@ import org.apache.commons.lang3.StringUtils;
import forge.game.GameFormat;
import forge.util.FileUtil;
/**
* The Class FormatUtils.
*/
public final class FormatUtils {
private final Map<String, GameFormat> formats = new TreeMap<String, GameFormat>(String.CASE_INSENSITIVE_ORDER);
@@ -53,6 +73,9 @@ public final class FormatUtils {
return formats.values();
}
/**
* Instantiates a new format utils.
*/
public FormatUtils() {
final List<String> fData = FileUtil.readFile("res/blockdata/formats.txt");

View File

@@ -68,7 +68,7 @@ public class AbilityFactory {
* </p>
*
* @param af
* a AbilityFactory object.
* a AbilityFactory object.
*/
public AbilityFactory(final AbilityFactory af) {
this.abCost = af.getAbCost();
@@ -100,11 +100,12 @@ public class AbilityFactory {
* <p>
* setHostCard.
* </p>
*
* @param host
* a Card object.
*
*/
public final void setHostCard(Card host) {
public final void setHostCard(final Card host) {
this.hostC = host;
}
@@ -212,10 +213,11 @@ public class AbilityFactory {
* <p>
* Setter for the field <code>abTgt</code>.
* </p>
*
* @param target
* a target object.
*/
public final void setAbTgt(Target target) {
public final void setAbTgt(final Target target) {
this.abTgt = target;
}
@@ -1487,7 +1489,7 @@ public class AbilityFactory {
/**
* <p>
* isInstantSpeed. To be used for mana abilities like Lion's Eye Diamond
* isInstantSpeed. To be used for mana abilities like Lion's Eye Diamond
* </p>
*
* @param sa
@@ -1552,7 +1554,7 @@ public class AbilityFactory {
// Add whole Remembered list to handlePaid
final CardList list = new CardList();
if (card.getRemembered().isEmpty()) {
Card newCard = AllZoneUtil.getCardState(card);
final Card newCard = AllZoneUtil.getCardState(card);
for (final Object o : newCard.getRemembered()) {
if (o instanceof Card) {
list.add(AllZoneUtil.getCardState((Card) o));
@@ -1692,7 +1694,7 @@ public class AbilityFactory {
// isn't made yet
return 0;
}
//cost hasn't been paid yet
// cost hasn't been paid yet
if (amount.startsWith("Cost")) {
return 0;
}
@@ -1729,12 +1731,15 @@ public class AbilityFactory {
if (defined.equals("Self")) {
c = hostCard;
}
// The Wretched
else if (defined.equals("TriggeredBlocker.blocking")) {
final SpellAbility root = sa.getRootSpellAbility();
final Object crd = root.getTriggeringObject("Blocker");
if (AllZoneUtil.getCardState((Card) crd).isBlocking()); {
if (AllZoneUtil.getCardState((Card) crd).isBlocking()) {
;
}
{
c = AllZoneUtil.getCardState((Card) crd);
}
}
@@ -1749,10 +1754,9 @@ public class AbilityFactory {
else if (defined.equals("Enchanted")) {
c = hostCard.getEnchantingCard();
if (c == null
&& AbilityFactory.findRootAbility(sa) != null
&& AbilityFactory.findRootAbility(sa).getPaidList("Sacrificed") != null
&& !AbilityFactory.findRootAbility(sa).getPaidList("Sacrificed").isEmpty()) {
if ((c == null) && (AbilityFactory.findRootAbility(sa) != null)
&& (AbilityFactory.findRootAbility(sa).getPaidList("Sacrificed") != null)
&& !AbilityFactory.findRootAbility(sa).getPaidList("Sacrificed").isEmpty()) {
c = AbilityFactory.findRootAbility(sa).getPaidList("Sacrificed").get(0).getEnchantingCard();
}
}
@@ -1796,7 +1800,7 @@ public class AbilityFactory {
}
} else if (defined.equals("Remembered")) {
if (hostCard.getRemembered().isEmpty()) {
Card newCard = AllZoneUtil.getCardState(hostCard);
final Card newCard = AllZoneUtil.getCardState(hostCard);
for (final Object o : newCard.getRemembered()) {
if (o instanceof Card) {
cards.add(AllZoneUtil.getCardState((Card) o));
@@ -1915,7 +1919,7 @@ public class AbilityFactory {
}
for (final SpellAbility s : sas) {
final Player p = s.getActivatingPlayer();
//final Player p = s.getSourceCard().getController();
// final Player p = s.getSourceCard().getController();
if (!players.contains(p)) {
players.add(p);
}
@@ -2569,8 +2573,7 @@ public class AbilityFactory {
};
if (payer.isHuman()) {
GameActionUtil.payCostDuringAbilityResolve(source + "\r\n", source, unlessCost, paidCommand,
unpaidCommand);
GameActionUtil.payCostDuringAbilityResolve(source + "\r\n", source, unlessCost, paidCommand, unpaidCommand);
} else {
if (ComputerUtil.canPayCost(ability) && CostUtil.checkLifeCost(cost, source, 4)) {
ComputerUtil.playNoStack(ability); // Unless cost was payed - no

View File

@@ -208,8 +208,8 @@ public final class AbilityFactoryChangeZone {
* @return a boolean.
*/
public static boolean isKnown(final String origin) {
return (origin.equals("Graveyard") || origin.equals("Exile") || origin.equals("Battlefield") || origin
.equals("Stack") || origin.equals("Ante"));
return (origin.equals("Graveyard") || origin.equals("Exile") || origin.equals("Battlefield")
|| origin.equals("Stack") || origin.equals("Ante"));
}
/**
@@ -315,9 +315,9 @@ public final class AbilityFactoryChangeZone {
return false;
}
return changeZoneTriggerAINoCost(af, sa, mandatory);
return AbilityFactoryChangeZone.changeZoneTriggerAINoCost(af, sa, mandatory);
}
/**
* <p>
* changeZoneTriggerAINoCost.
@@ -331,7 +331,8 @@ public final class AbilityFactoryChangeZone {
* a boolean.
* @return a boolean.
*/
private static boolean changeZoneTriggerAINoCost(final AbilityFactory af, final SpellAbility sa, final boolean mandatory) {
private static boolean changeZoneTriggerAINoCost(final AbilityFactory af, final SpellAbility sa,
final boolean mandatory) {
final HashMap<String, String> params = af.getMapParams();
String origin = "";
if (params.containsKey("Origin")) {
@@ -457,7 +458,7 @@ public final class AbilityFactoryChangeZone {
if ((tgt != null) && tgt.canTgtPlayer()) {
if (af.isCurse() && sa.canTarget(AllZone.getHumanPlayer())) {
tgt.addTarget(AllZone.getHumanPlayer());
} else if (!af.isCurse() && sa.canTarget(AllZone.getComputerPlayer())){
} else if (!af.isCurse() && sa.canTarget(AllZone.getComputerPlayer())) {
tgt.addTarget(AllZone.getComputerPlayer());
}
pDefined = tgt.getTargetPlayers();
@@ -526,7 +527,7 @@ public final class AbilityFactoryChangeZone {
if ((tgt != null) && tgt.canTgtPlayer()) {
if (af.isCurse() && sa.canTarget(AllZone.getHumanPlayer())) {
tgt.addTarget(AllZone.getHumanPlayer());
} else if (!af.isCurse() && sa.canTarget(AllZone.getComputerPlayer())){
} else if (!af.isCurse() && sa.canTarget(AllZone.getComputerPlayer())) {
tgt.addTarget(AllZone.getComputerPlayer());
} else {
return false;
@@ -670,8 +671,7 @@ public final class AbilityFactoryChangeZone {
if (params.containsKey("ExileFaceDown")) {
sb.append(" face down");
}
}
else if (destination.equals("Ante")) {
} else if (destination.equals("Ante")) {
sb.append("Add the top card of your library to the ante");
}
sb.append(".");
@@ -848,14 +848,14 @@ public final class AbilityFactoryChangeZone {
}
}
int changeNum = params.containsKey("ChangeNum") ? AbilityFactory.calculateAmount(card,
params.get("ChangeNum"), sa) : 1;
int changeNum = params.containsKey("ChangeNum") ? AbilityFactory.calculateAmount(card, params.get("ChangeNum"),
sa) : 1;
CardList fetchList;
if (defined) {
fetchList = new CardList(AbilityFactory.getDefinedCards(card, params.get("Defined"), sa));
if (!params.containsKey("ChangeNum")) {
changeNum = fetchList.size();
changeNum = fetchList.size();
}
} else if (!origin.contains(Zone.Library) && !origin.contains(Zone.Hand)) {
fetchList = AllZoneUtil.getCardsIn(origin);
@@ -866,7 +866,8 @@ public final class AbilityFactoryChangeZone {
if (!defined) {
if (origin.contains(Zone.Library) && !defined) { // Look at whole
// library before
// moving onto choosing
// moving onto
// choosing
// a card{
GuiUtils.getChoiceOptional(af.getHostCard().getName() + " - Looking at Library",
player.getCardsIn(Zone.Library).toArray());
@@ -874,8 +875,8 @@ public final class AbilityFactoryChangeZone {
// Look at opponents hand before moving onto choosing a card
if (origin.contains(Zone.Hand) && player.isComputer()) {
GuiUtils.getChoiceOptional(af.getHostCard().getName() + " - Looking at Opponent's Hand",
player.getCardsIn(Zone.Hand).toArray());
GuiUtils.getChoiceOptional(af.getHostCard().getName() + " - Looking at Opponent's Hand", player
.getCardsIn(Zone.Hand).toArray());
}
fetchList = AbilityFactory.filterListByType(fetchList, params.get("ChangeType"), sa);
}
@@ -929,12 +930,14 @@ public final class AbilityFactoryChangeZone {
}
if (params.containsKey("AttachedTo")) {
ArrayList<Card> list = AbilityFactory.getDefinedCards(sa.getSourceCard(), params.get("AttachedTo"), sa);
final ArrayList<Card> list = AbilityFactory.getDefinedCards(sa.getSourceCard(),
params.get("AttachedTo"), sa);
if (!list.isEmpty()) {
Card attachedTo = list.get(0);
final Card attachedTo = list.get(0);
if (c.isEnchanting()) {
// If this Card is already Enchanting something
// Need to unenchant it, then clear out the commands
// Need to unenchant it, then clear out the
// commands
final GameEntity oldEnchanted = c.getEnchanting();
c.removeEnchanting(oldEnchanted);
c.clearEnchantCommand();
@@ -1020,14 +1023,14 @@ public final class AbilityFactoryChangeZone {
type = "Card";
}
int changeNum = params.containsKey("ChangeNum") ? AbilityFactory.calculateAmount(card,
params.get("ChangeNum"), sa) : 1;
int changeNum = params.containsKey("ChangeNum") ? AbilityFactory.calculateAmount(card, params.get("ChangeNum"),
sa) : 1;
CardList fetchList;
if (defined) {
fetchList = new CardList(AbilityFactory.getDefinedCards(card, params.get("Defined"), sa));
if (!params.containsKey("ChangeNum")) {
changeNum = fetchList.size();
changeNum = fetchList.size();
}
} else if (!origin.contains(Zone.Library) && !origin.contains(Zone.Hand)) {
fetchList = AllZoneUtil.getCardsIn(origin);
@@ -1113,9 +1116,10 @@ public final class AbilityFactoryChangeZone {
}
if (params.containsKey("AttachedTo")) {
ArrayList<Card> list = AbilityFactory.getDefinedCards(sa.getSourceCard(), params.get("AttachedTo"), sa);
final ArrayList<Card> list = AbilityFactory.getDefinedCards(sa.getSourceCard(),
params.get("AttachedTo"), sa);
if (!list.isEmpty()) {
Card attachedTo = list.get(0);
final Card attachedTo = list.get(0);
if (c.isEnchanting()) {
// If this Card is already Enchanting something
// Need to unenchant it, then clear out the commands
@@ -1521,7 +1525,8 @@ public final class AbilityFactoryChangeZone {
if (origin.equals(Zone.Battlefield)
&& destination.equals(Zone.Exile)
&& (subAPI.equals("DelayedTrigger") || (subAPI.equals("ChangeZone") && subAffected.equals("Remembered")))
&& !(AllZone.getPhaseHandler().is(Constant.Phase.COMBAT_DECLARE_ATTACKERS_INSTANT_ABILITY) || sa.isAbility())) {
&& !(AllZone.getPhaseHandler().is(Constant.Phase.COMBAT_DECLARE_ATTACKERS_INSTANT_ABILITY) || sa
.isAbility())) {
return false;
}
@@ -1704,9 +1709,10 @@ public final class AbilityFactoryChangeZone {
if (sa.getTarget() == null) {
// Just in case of Defined cases
if (!mandatory && params.containsKey("AttachedTo")) {
ArrayList<Card> list = AbilityFactory.getDefinedCards(sa.getSourceCard(), params.get("AttachedTo"), sa);
final ArrayList<Card> list = AbilityFactory.getDefinedCards(sa.getSourceCard(),
params.get("AttachedTo"), sa);
if (!list.isEmpty()) {
Card attachedTo = list.get(0);
final Card attachedTo = list.get(0);
// This code is for the Dragon auras
if (attachedTo.getController().isHuman()) {
return false;
@@ -1932,12 +1938,15 @@ public final class AbilityFactoryChangeZone {
tgtC.addController(af.getHostCard());
}
if (params.containsKey("AttachedTo")) {
ArrayList<Card> list = AbilityFactory.getDefinedCards(sa.getSourceCard(), params.get("AttachedTo"), sa);
final ArrayList<Card> list = AbilityFactory.getDefinedCards(sa.getSourceCard(),
params.get("AttachedTo"), sa);
if (!list.isEmpty()) {
Card attachedTo = list.get(0);
final Card attachedTo = list.get(0);
if (tgtC.isEnchanting()) {
// If this Card is already Enchanting something
// Need to unenchant it, then clear out the commands
// If this Card is already Enchanting
// something
// Need to unenchant it, then clear out the
// commands
final GameEntity oldEnchanted = tgtC.getEnchanting();
tgtC.removeEnchanting(oldEnchanted);
tgtC.clearEnchantCommand();
@@ -1955,7 +1964,8 @@ public final class AbilityFactoryChangeZone {
}
}
movedCard = Singletons.getModel().getGameAction().moveTo(tgtC.getController().getZone(destination), tgtC);
movedCard = Singletons.getModel().getGameAction()
.moveTo(tgtC.getController().getZone(destination), tgtC);
if (params.containsKey("Ninjutsu") || params.containsKey("Attacking")) {
AllZone.getCombat().addAttacker(tgtC);

View File

@@ -2240,21 +2240,28 @@ public final class AbilityFactoryReveal {
}
}
/**
* Gets the revealed list.
*
* @param player the player
* @param valid the valid
* @param max the max
* @return the revealed list
*/
public static CardList getRevealedList(final Player player, final CardList valid, final int max) {
final CardList chosen = new CardList();
final int validamount = Math.min(valid.size(), max);
for (int i = 0; i < validamount; i++) {
if (player.isHuman()) {
final Object o = GuiUtils.getChoiceOptional("Choose card(s) to reveal", valid.toArray());
if (o != null) {
chosen.add((Card) o);
valid.remove((Card) o);
} else {
break;
}
} else { //Computer
if (o != null) {
chosen.add((Card) o);
valid.remove((Card) o);
} else {
break;
}
} else { // Computer
chosen.add(valid.get(0));
valid.remove(valid.get(0));
}

View File

@@ -468,7 +468,7 @@ public class AbilityFactorySacrifice {
card.addRemembered(toSac);
}
}
} else if (valid.equals("TriggeredCard")) {
} else if (valid.equals("TriggeredCard")) {
final Card equipee = (Card) sa.getTriggeringObject("Card");
if (tgts.contains(card.getController()) && AllZoneUtil.isCardInPlay(equipee)) {
Singletons.getModel().getGameAction().sacrifice(equipee);
@@ -549,7 +549,7 @@ public class AbilityFactorySacrifice {
*/
private static CardList sacrificeHuman(final Player p, final int amount, final String valid, final SpellAbility sa,
final boolean destroy, final boolean optional) {
CardList saccedList = new CardList();
final CardList saccedList = new CardList();
CardList list = p.getCardsIn(Zone.Battlefield);
list = list.getValidCards(valid.split(","), sa.getActivatingPlayer(), sa.getSourceCard());

View File

@@ -592,7 +592,7 @@ public class CardFactoryUtil {
value -= 20; // not used atm
}
for (SpellAbility sa : c.getSpellAbilities()) {
for (final SpellAbility sa : c.getSpellAbilities()) {
if (sa.isAbility()) {
value += 10;
}
@@ -1339,7 +1339,8 @@ public class CardFactoryUtil {
// An animated artifact equipmemt can't equip a creature
@Override
public boolean canPlay() {
return super.canPlay() && !sourceCard.isCreature() && PhaseHandler.canCastSorcery(sourceCard.getController());
return super.canPlay() && !sourceCard.isCreature()
&& PhaseHandler.canCastSorcery(sourceCard.getController());
}
@Override
@@ -1359,8 +1360,8 @@ public class CardFactoryUtil {
@Override
public boolean addCard(final Card c) {
return c.isCreature()
&& (CombatUtil.canAttack(c) || (CombatUtil.canAttackNextTurn(c) && AllZone.getPhaseHandler()
.is(Constant.Phase.MAIN2)))
&& (CombatUtil.canAttack(c) || (CombatUtil.canAttackNextTurn(c) && AllZone
.getPhaseHandler().is(Constant.Phase.MAIN2)))
&& (((c.getNetDefense() + tough) > 0) || sourceCard.getName().equals("Skullclamp"));
}
});
@@ -1763,7 +1764,8 @@ public class CardFactoryUtil {
@Override
public void selectCard(final Card card, final PlayerZone zone) {
if (targeted && !card.canBeTargetedBy(spell)) {
Singletons.getControl().getControlMatch().showMessage("Cannot target this card (Shroud? Protection?).");
Singletons.getControl().getControlMatch()
.showMessage("Cannot target this card (Shroud? Protection?).");
} else if (choices.contains(card)) {
spell.setTargetCard(card);
if (spell.getManaCost().equals("0") || free) {
@@ -1879,56 +1881,36 @@ public class CardFactoryUtil {
* @return input
*/
/*
public static Input inputDiscardRecall(final int numCards, final Card recall, final SpellAbility sa) {
final Input target = new Input() {
private static final long serialVersionUID = 1942999595292561944L;
private int n = 0;
@Override
public void showMessage() {
if (AllZone.getHumanPlayer().getZone(Zone.Hand).size() == 0) {
this.stop();
}
Singletons.getControl().getControlMatch().showMessage("Select a card to discard");
ButtonUtil.disableAll();
}
@Override
public void selectCard(final Card card, final PlayerZone zone) {
if (zone.is(Constant.Zone.Hand)) {
card.getController().discard(card, sa);
this.n++;
// in case no more cards in hand
if ((this.n == numCards) || (AllZone.getHumanPlayer().getZone(Zone.Hand).size() == 0)) {
this.done();
} else {
this.showMessage();
}
}
}
void done() {
Singletons.getControl().getControlMatch().showMessage("Returning cards to hand.");
Singletons.getModel().getGameAction().exile(recall);
final CardList grave = AllZone.getHumanPlayer().getCardsIn(Zone.Graveyard);
for (int i = 1; i <= this.n; i++) {
final String title = "Return card from grave to hand";
final Object o = GuiUtils.getChoice(title, grave.toArray());
if (o == null) {
break;
}
final Card toHand = (Card) o;
grave.remove(toHand);
Singletons.getModel().getGameAction().moveToHand(toHand);
}
this.stop();
}
};
return target;
} // input_discardRecall()
*/
* public static Input inputDiscardRecall(final int numCards, final Card
* recall, final SpellAbility sa) { final Input target = new Input() {
* private static final long serialVersionUID = 1942999595292561944L;
* private int n = 0;
*
* @Override public void showMessage() { if
* (AllZone.getHumanPlayer().getZone(Zone.Hand).size() == 0) { this.stop();
* }
*
* Singletons.getControl().getControlMatch().showMessage(
* "Select a card to discard"); ButtonUtil.disableAll(); }
*
* @Override public void selectCard(final Card card, final PlayerZone zone)
* { if (zone.is(Constant.Zone.Hand)) { card.getController().discard(card,
* sa); this.n++;
*
* // in case no more cards in hand if ((this.n == numCards) ||
* (AllZone.getHumanPlayer().getZone(Zone.Hand).size() == 0)) { this.done();
* } else { this.showMessage(); } } }
*
* void done() { Singletons.getControl().getControlMatch().showMessage(
* "Returning cards to hand.");
* Singletons.getModel().getGameAction().exile(recall); final CardList grave
* = AllZone.getHumanPlayer().getCardsIn(Zone.Graveyard); for (int i = 1; i
* <= this.n; i++) { final String title = "Return card from grave to hand";
* final Object o = GuiUtils.getChoice(title, grave.toArray()); if (o ==
* null) { break; } final Card toHand = (Card) o; grave.remove(toHand);
* Singletons.getModel().getGameAction().moveToHand(toHand); } this.stop();
* } }; return target; } // input_discardRecall()
*/
/**
* <p>
@@ -2384,7 +2366,8 @@ public class CardFactoryUtil {
// returns the number of equipments named "e" card c is equipped by
/**
* <p>
* Gets the number of equipments with a given name that a given card is equipped by.
* Gets the number of equipments with a given name that a given card is
* equipped by.
* </p>
*
* @param card
@@ -2421,14 +2404,14 @@ public class CardFactoryUtil {
* @return a {@link forge.CardList} object.
*/
public static CardList getExternalZoneActivationCards(final Player activator) {
CardList cl = new CardList();
Player opponent = activator.getOpponent();
final CardList cl = new CardList();
final Player opponent = activator.getOpponent();
cl.addAll(getActivateablesFromZone(activator.getZone(Constant.Zone.Graveyard), activator));
cl.addAll(getActivateablesFromZone(activator.getZone(Constant.Zone.Exile), activator));
cl.addAll(getActivateablesFromZone(activator.getZone(Constant.Zone.Library), activator));
cl.addAll(getActivateablesFromZone(activator.getZone(Constant.Zone.Command), activator));
cl.addAll(getActivateablesFromZone(opponent.getZone(Constant.Zone.Exile), activator));
cl.addAll(CardFactoryUtil.getActivateablesFromZone(activator.getZone(Constant.Zone.Graveyard), activator));
cl.addAll(CardFactoryUtil.getActivateablesFromZone(activator.getZone(Constant.Zone.Exile), activator));
cl.addAll(CardFactoryUtil.getActivateablesFromZone(activator.getZone(Constant.Zone.Library), activator));
cl.addAll(CardFactoryUtil.getActivateablesFromZone(activator.getZone(Constant.Zone.Command), activator));
cl.addAll(CardFactoryUtil.getActivateablesFromZone(opponent.getZone(Constant.Zone.Exile), activator));
return cl;
}
@@ -2448,7 +2431,7 @@ public class CardFactoryUtil {
CardList cl = new CardList(zone.getCards());
//Only check the top card of the library
// Only check the top card of the library
if (zone.is(Constant.Zone.Library) && !cl.isEmpty()) {
cl = new CardList(cl.get(0));
}
@@ -2463,9 +2446,9 @@ public class CardFactoryUtil {
}
}
if (c.isLand() && (c.hasKeyword("May be played")
|| c.hasKeyword("May be played by your opponent")
|| c.hasKeyword("May be played without paying its mana cost"))) {
if (c.isLand()
&& (c.hasKeyword("May be played") || c.hasKeyword("May be played by your opponent") || c
.hasKeyword("May be played without paying its mana cost"))) {
return true;
}
@@ -2476,11 +2459,10 @@ public class CardFactoryUtil {
}
if (sa.isSpell()
&& (c.hasKeyword("May be played")
|| c.hasKeyword("May be played by your Opponent")
|| c.hasKeyword("May be played without paying its mana cost")
|| (c.hasStartOfKeyword("Flashback") && zone
.is(Zone.Graveyard))) && restrictZone.equals(Zone.Hand)) {
&& (c.hasKeyword("May be played") || c.hasKeyword("May be played by your Opponent")
|| c.hasKeyword("May be played without paying its mana cost") || (c
.hasStartOfKeyword("Flashback") && zone.is(Zone.Graveyard)))
&& restrictZone.equals(Zone.Hand)) {
return true;
}
}
@@ -2714,7 +2696,7 @@ public class CardFactoryUtil {
if (l[0].startsWith("SVar$")) {
final String sVar = l[0].replace("SVar$", "");
return CardFactoryUtil.doXMath(xCount(c, c.getSVar(sVar)), m, c);
return CardFactoryUtil.doXMath(CardFactoryUtil.xCount(c, c.getSVar(sVar)), m, c);
}
// Manapool
@@ -2761,7 +2743,7 @@ public class CardFactoryUtil {
}
return highest;
}
if (l[0].contains("HighestCMCRemembered")) {
final CardList list = new CardList();
int highest = 0;
@@ -2932,13 +2914,13 @@ public class CardFactoryUtil {
// Count$YourTypeDamageThisTurn Type
if (sq[0].contains("OppTypeDamageThisTurn")) {
String[] type = sq[0].split(" ");
final String[] type = sq[0].split(" ");
return CardFactoryUtil.doXMath(c.getController().getOpponent().getAssignedDamage(type[1]), m, c);
}
// Count$YourTypeDamageThisTurn Type
if (sq[0].contains("YourTypeDamageThisTurn")) {
String[] type = sq[0].split(" ");
final String[] type = sq[0].split(" ");
return CardFactoryUtil.doXMath(c.getController().getAssignedDamage(type[1]), m, c);
}
@@ -3013,8 +2995,8 @@ public class CardFactoryUtil {
// Count$wasCastFrom<Zone>.<true>.<false>
if (sq[0].startsWith("wasCastFrom")) {
String strZone = sq[0].substring(11);
Zone realZone = Zone.smartValueOf(strZone);
final String strZone = sq[0].substring(11);
final Zone realZone = Zone.smartValueOf(strZone);
if (c.getCastFrom() == realZone) {
return CardFactoryUtil.doXMath(Integer.parseInt(sq[1]), m, c);
} else {
@@ -3679,8 +3661,8 @@ public class CardFactoryUtil {
/**
* <p>
* Get the total cost to pay for an attacker c, due to cards like Propaganda,
* Ghostly Prison, Collective Restraint, ...
* Get the total cost to pay for an attacker c, due to cards like
* Propaganda, Ghostly Prison, Collective Restraint, ...
* </p>
*
* @param c
@@ -3812,7 +3794,7 @@ public class CardFactoryUtil {
for (final String kw : intrinsicKeywords) {
if (kw.startsWith("HIDDEN")) {
temp.addExtrinsicKeyword(kw);
//extrinsic keywords won't survive the copyStats treatment
// extrinsic keywords won't survive the copyStats treatment
} else {
temp.addIntrinsicKeyword(kw);
}
@@ -4105,8 +4087,8 @@ public class CardFactoryUtil {
* "When CARDNAME becomes the target of a spell or ability, return CARDNAME to its owner's hand."
* ) ) { // || (c.isCreature() && AllZoneUtil.isCardInPlay("Cowardice"))
* SpellAbility ability = new Ability(c, "0") { public void resolve() {
* Singletons.getModel().getGameAction().moveToHand(c); } }; StringBuilder sb = new
* StringBuilder();
* Singletons.getModel().getGameAction().moveToHand(c); } }; StringBuilder
* sb = new StringBuilder();
* sb.append(c).append(" - return CARDNAME to its owner's hand.");
* ability.setStackDescription(sb.toString());
*
@@ -4115,15 +4097,15 @@ public class CardFactoryUtil {
* ) || AllZoneUtil.isCardInPlay("Horobi, Death's Wail")) {
*
* SpellAbility ability = new Ability(c, "0") { public void resolve() {
* Singletons.getModel().getGameAction().destroy(c); } }; StringBuilder sb = new
* StringBuilder(); sb.append(c).append(" - destroy CARDNAME.");
* Singletons.getModel().getGameAction().destroy(c); } }; StringBuilder sb =
* new StringBuilder(); sb.append(c).append(" - destroy CARDNAME.");
* ability.setStackDescription(sb.toString());
*
* AllZone.getStack().add(ability); } if (c.hasKeyword(
* "When CARDNAME becomes the target of a spell or ability, sacrifice it."))
* { SpellAbility ability = new Ability(c, "0") { public void resolve() {
* Singletons.getModel().getGameAction().sacrifice(c); } }; StringBuilder sb = new
* StringBuilder(); sb.append(c).append(" - sacrifice CARDNAME.");
* Singletons.getModel().getGameAction().sacrifice(c); } }; StringBuilder sb
* = new StringBuilder(); sb.append(c).append(" - sacrifice CARDNAME.");
* ability.setStackDescription(sb.toString());
*
* AllZone.getStack().add(ability); }
@@ -4157,12 +4139,12 @@ public class CardFactoryUtil {
* if(action[0].startsWith("exile")) {
* Singletons.getModel().getGameAction().exile(target); } else
* if(action[0].startsWith("destroy")) { if(noRegen) {
* Singletons.getModel().getGameAction().destroyNoRegeneration(target); } else {
* Singletons.getModel().getGameAction().destroy(target); } } else
* Singletons.getModel().getGameAction().destroyNoRegeneration(target); }
* else { Singletons.getModel().getGameAction().destroy(target); } } else
* if(action[0].startsWith("sacrifice")) {
* Singletons.getModel().getGameAction().sacrifice(target); } else { throw new
* IllegalArgumentException("There is a problem in the keyword " + keyword +
* "for card \"" + c.getName() + "\""); } } };
* Singletons.getModel().getGameAction().sacrifice(target); } else { throw
* new IllegalArgumentException("There is a problem in the keyword " +
* keyword + "for card \"" + c.getName() + "\""); } } };
*
* saTrigger.setStackDescription(stackDesc);
*
@@ -4756,7 +4738,8 @@ public class CardFactoryUtil {
AllZone.getStack().add(haunterDiesWork);
this.stop();
} else {
Singletons.getControl().getControlMatch().showMessage("Cannot target this card (Shroud? Protection?).");
Singletons.getControl().getControlMatch()
.showMessage("Cannot target this card (Shroud? Protection?).");
}
}
};

View File

@@ -991,7 +991,7 @@ public abstract class SpellAbility {
/**
* Gets the replacing objects.
*
*
* @return the replacing objects
*/
public HashMap<String, Object> getReplacingObjects() {
@@ -1000,8 +1000,9 @@ public abstract class SpellAbility {
/**
* Sets the all replacing objects.
*
* @param replacedObjects the replaced objects
*
* @param replacedObjects
* the replaced objects
*/
public void setAllReplacingObjects(final HashMap<String, Object> replacedObjects) {
this.replacingObjects = replacedObjects;
@@ -1009,9 +1010,11 @@ public abstract class SpellAbility {
/**
* Sets the replacing object.
*
* @param type the type
* @param o the o
*
* @param type
* the type
* @param o
* the o
*/
public void setReplacingObject(final String type, final Object o) {
this.replacingObjects.put(type, o);
@@ -1019,19 +1022,21 @@ public abstract class SpellAbility {
/**
* Gets the replacing object.
*
* @param type the type
*
* @param type
* the type
* @return the replacing object
*/
public Object getReplacingObject(final String type) {
Object res = this.replacingObjects.get(type);
final Object res = this.replacingObjects.get(type);
return res;
}
/**
* Checks for replacing object.
*
* @param type the type
*
* @param type
* the type
* @return true, if successful
*/
public boolean hasReplacingObject(final String type) {
@@ -1602,7 +1607,7 @@ public abstract class SpellAbility {
return res;
}
/**
* <p>
* canTarget.
@@ -1613,7 +1618,7 @@ public abstract class SpellAbility {
* @return a boolean.
*/
public final boolean canTarget(final GameEntity entity) {
if (entity.isValid(this.getTarget().getValidTgts(), this.getActivatingPlayer(), this.getSourceCard())
if (entity.isValid(this.getTarget().getValidTgts(), this.getActivatingPlayer(), this.getSourceCard())
&& entity.canBeTargetedBy(this)) {
return true;
}

View File

@@ -1,3 +1,20 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.control.home;
import java.awt.event.MouseAdapter;
@@ -25,54 +42,73 @@ import forge.properties.NewConstants.Lang;
import forge.view.home.ViewUtilities;
import forge.view.toolbox.FSkin;
/**
/**
* Controls logic and listeners for Utilities panel of the home screen.
*
*
*/
public class ControlUtilities {
private ViewUtilities view;
private final ViewUtilities view;
private final MouseListener madLicensing;
private final Command cmdDeckEditor, cmdPicDownload, cmdSetDownload,
cmdQuestImages, cmdReportBug, cmdImportPictures, cmdHowToPlay, cmdDownloadPrices;
private final Command cmdDeckEditor, cmdPicDownload, cmdSetDownload, cmdQuestImages, cmdReportBug,
cmdImportPictures, cmdHowToPlay, cmdDownloadPrices;
/**
*
* Controls logic and listeners for Utilities panel of the home screen.
*
* @param v0 &emsp; ViewUtilities
* @param v0
* &emsp; ViewUtilities
*/
@SuppressWarnings("serial")
public ControlUtilities(ViewUtilities v0) {
public ControlUtilities(final ViewUtilities v0) {
this.view = v0;
madLicensing = new MouseAdapter() {
this.madLicensing = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
view.showLicensing();
public void mouseClicked(final MouseEvent e) {
ControlUtilities.this.view.showLicensing();
}
@Override
public void mouseEntered(MouseEvent e) {
view.getLblLicensing().setForeground(FSkin.getColor(FSkin.Colors.CLR_HOVER));
public void mouseEntered(final MouseEvent e) {
ControlUtilities.this.view.getLblLicensing().setForeground(FSkin.getColor(FSkin.Colors.CLR_HOVER));
}
@Override
public void mouseExited(MouseEvent e) {
view.getLblLicensing().setForeground(FSkin.getColor(FSkin.Colors.CLR_TEXT));
public void mouseExited(final MouseEvent e) {
ControlUtilities.this.view.getLblLicensing().setForeground(FSkin.getColor(FSkin.Colors.CLR_TEXT));
}
};
cmdDeckEditor = new Command() { @Override
public void execute() { showDeckEditor(GameType.Constructed, null); } };
this.cmdDeckEditor = new Command() {
@Override
public void execute() {
ControlUtilities.this.showDeckEditor(GameType.Constructed, null);
}
};
cmdPicDownload = new Command() { @Override
public void execute() { doDownloadPics(); } };
this.cmdPicDownload = new Command() {
@Override
public void execute() {
ControlUtilities.this.doDownloadPics();
}
};
cmdSetDownload = new Command() { @Override
public void execute() { doDownloadSetPics(); } };
this.cmdSetDownload = new Command() {
@Override
public void execute() {
ControlUtilities.this.doDownloadSetPics();
}
};
cmdQuestImages = new Command() { @Override
public void execute() { doDownloadQuestImages(); } };
this.cmdQuestImages = new Command() {
@Override
public void execute() {
ControlUtilities.this.doDownloadQuestImages();
}
};
cmdReportBug = new Command() {
this.cmdReportBug = new Command() {
@Override
public void execute() {
final BugzReporter br = new BugzReporter();
@@ -80,7 +116,7 @@ public class ControlUtilities {
}
};
cmdImportPictures = new Command() {
this.cmdImportPictures = new Command() {
@Override
public void execute() {
final GuiImportPicture ip = new GuiImportPicture(null);
@@ -88,7 +124,7 @@ public class ControlUtilities {
}
};
cmdHowToPlay = new Command() {
this.cmdHowToPlay = new Command() {
@Override
public void execute() {
final String text = ForgeProps.getLocalized(Lang.HowTo.MESSAGE);
@@ -104,7 +140,7 @@ public class ControlUtilities {
}
};
cmdDownloadPrices = new Command() {
this.cmdDownloadPrices = new Command() {
@Override
public void execute() {
final GuiDownloadPrices gdp = new GuiDownloadPrices();
@@ -112,27 +148,33 @@ public class ControlUtilities {
}
};
addListeners();
this.addListeners();
}
/** @return ViewUtilities */
/**
* Gets the view.
*
* @return ViewUtilities
*/
public ViewUtilities getView() {
return view;
return this.view;
}
/** */
/**
* Adds the listeners.
*/
public void addListeners() {
this.view.getBtnDownloadPics().setCommand(cmdPicDownload);
this.view.getBtnDownloadSetPics().setCommand(cmdSetDownload);
this.view.getBtnDownloadQuestImages().setCommand(cmdQuestImages);
this.view.getBtnReportBug().setCommand(cmdReportBug);
this.view.getBtnImportPictures().setCommand(cmdImportPictures);
this.view.getBtnHowToPlay().setCommand(cmdHowToPlay);
this.view.getBtnDownloadPrices().setCommand(cmdDownloadPrices);
this.view.getBtnDeckEditor().setCommand(cmdDeckEditor);
this.view.getBtnDownloadPics().setCommand(this.cmdPicDownload);
this.view.getBtnDownloadSetPics().setCommand(this.cmdSetDownload);
this.view.getBtnDownloadQuestImages().setCommand(this.cmdQuestImages);
this.view.getBtnReportBug().setCommand(this.cmdReportBug);
this.view.getBtnImportPictures().setCommand(this.cmdImportPictures);
this.view.getBtnHowToPlay().setCommand(this.cmdHowToPlay);
this.view.getBtnDownloadPrices().setCommand(this.cmdDownloadPrices);
this.view.getBtnDeckEditor().setCommand(this.cmdDeckEditor);
this.view.getLblLicensing().removeMouseListener(madLicensing);
this.view.getLblLicensing().addMouseListener(madLicensing);
this.view.getLblLicensing().removeMouseListener(this.madLicensing);
this.view.getLblLicensing().addMouseListener(this.madLicensing);
}
private void doDownloadPics() {
@@ -148,11 +190,14 @@ public class ControlUtilities {
}
/**
* Show deck editor.
*
* @param <T> the generic type
* @param gt0 &emsp; GameType
* @param d0 &emsp; Deck
*/
@SuppressWarnings("unchecked")
public <T> void showDeckEditor(GameType gt0, T d0) {
public <T> void showDeckEditor(final GameType gt0, final T d0) {
DeckEditorBase<?, T> editor = null;
if (gt0 == GameType.Constructed) {
@@ -163,14 +208,13 @@ public class ControlUtilities {
editor = (DeckEditorBase<?, T>) new DeckEditorLimited(Singletons.getModel().getDecks().getSealed());
}
final Command exit = new Command() {
private static final long serialVersionUID = -9133358399503226853L;
@Override
public void execute() {
Singletons.getControl().getControlHome().getControlConstructed().updateDeckLists();
//view.getParentView().getControlSealed().updateDeckLists();
// view.getParentView().getControlSealed().updateDeckLists();
}
};

View File

@@ -1,17 +1,33 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.deck;
import java.io.File;
import forge.deck.io.DeckSerializer;
import forge.deck.io.DeckGroupSerializer;
import forge.deck.io.DeckSerializer;
import forge.deck.io.OldDeckParser;
import forge.util.FolderMap;
import forge.util.IFolderMap;
/**
* Holds editable maps of decks saved to disk.
* Adding or removing items to(from) such map turns into immediate file update
/**
* Holds editable maps of decks saved to disk. Adding or removing items to(from)
* such map turns into immediate file update
*/
public class CardCollections {
private final IFolderMap<Deck> constructed;
@@ -21,35 +37,54 @@ public class CardCollections {
/**
* TODO: Write javadoc for Constructor.
* @param file
*
* @param file the file
*/
public CardCollections(File file) {
constructed = new FolderMap<Deck>(new DeckSerializer(new File(file, "constructed")));
draft = new FolderMap<DeckGroup>(new DeckGroupSerializer(new File(file, "draft")));
sealed = new FolderMap<DeckGroup>(new DeckGroupSerializer(new File(file, "sealed")));
cube = new FolderMap<Deck>(new DeckSerializer(new File(file, "cube")));
public CardCollections(final File file) {
this.constructed = new FolderMap<Deck>(new DeckSerializer(new File(file, "constructed")));
this.draft = new FolderMap<DeckGroup>(new DeckGroupSerializer(new File(file, "draft")));
this.sealed = new FolderMap<DeckGroup>(new DeckGroupSerializer(new File(file, "sealed")));
this.cube = new FolderMap<Deck>(new DeckSerializer(new File(file, "cube")));
// remove this after most people have been switched to new layout
OldDeckParser oldParser = new OldDeckParser(file, constructed, draft, sealed, cube);
final OldDeckParser oldParser = new OldDeckParser(file, this.constructed, this.draft, this.sealed, this.cube);
oldParser.tryParse();
}
/**
* Gets the constructed.
*
* @return the constructed
*/
public final IFolderMap<Deck> getConstructed() {
return constructed;
return this.constructed;
}
/**
* Gets the draft.
*
* @return the draft
*/
public final IFolderMap<DeckGroup> getDraft() {
return draft;
return this.draft;
}
/**
* Gets the cubes.
*
* @return the cubes
*/
public final IFolderMap<Deck> getCubes() {
return cube;
return this.cube;
}
/**
* Gets the sealed.
*
* @return the sealed
*/
public IFolderMap<DeckGroup> getSealed() {
return sealed;
return this.sealed;
}
}

View File

@@ -66,9 +66,16 @@ public class Deck extends DeckBase implements Serializable, IHasName {
* Decks have their named finalled.
* </p>
*/
public Deck() { this(""); }
public Deck() {
this("");
}
public Deck(String name0) {
/**
* Instantiates a new deck.
*
* @param name0 the name0
*/
public Deck(final String name0) {
super(name0);
this.main = new DeckSection();
this.sideboard = new DeckSection();
@@ -92,7 +99,6 @@ public class Deck extends DeckBase implements Serializable, IHasName {
return this.getName();
}
/**
* <p>
* Getter for the field <code>main</code>.
@@ -115,53 +121,79 @@ public class Deck extends DeckBase implements Serializable, IHasName {
return this.sideboard;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.item.CardCollectionBase#getCardPool()
*/
@Override
public ItemPoolView<CardPrinted> getCardPool() {
return main;
return this.main;
}
protected void cloneFieldsTo(DeckBase clone) {
/* (non-Javadoc)
* @see forge.deck.DeckBase#cloneFieldsTo(forge.deck.DeckBase)
*/
@Override
protected void cloneFieldsTo(final DeckBase clone) {
super.cloneFieldsTo(clone);
Deck result = (Deck) clone;
final Deck result = (Deck) clone;
result.main.addAll(this.main);
result.sideboard.addAll(this.sideboard);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.DeckBase#newInstance(java.lang.String)
*/
@Override
protected DeckBase newInstance(String name0) {
protected DeckBase newInstance(final String name0) {
return new Deck(name0);
}
/**
* From file.
*
* @param deckFile the deck file
* @return the deck
*/
public static Deck fromFile(final File deckFile) {
return fromSections(SectionUtil.parseSections(FileUtil.readFile(deckFile)));
return Deck.fromSections(SectionUtil.parseSections(FileUtil.readFile(deckFile)));
}
public static Deck fromSections(Map<String, List<String>> sections) {
return fromSections(sections, false);
/**
* From sections.
*
* @param sections the sections
* @return the deck
*/
public static Deck fromSections(final Map<String, List<String>> sections) {
return Deck.fromSections(sections, false);
}
public static Deck fromSections(Map<String, List<String>> sections, boolean canThrowExtendedErrors) {
if (sections == null || sections.isEmpty()) {
/**
* From sections.
*
* @param sections the sections
* @param canThrowExtendedErrors the can throw extended errors
* @return the deck
*/
public static Deck fromSections(final Map<String, List<String>> sections, final boolean canThrowExtendedErrors) {
if ((sections == null) || sections.isEmpty()) {
return null;
}
DeckFileHeader dh = DeckSerializer.readDeckMetadata(sections, canThrowExtendedErrors);
final DeckFileHeader dh = DeckSerializer.readDeckMetadata(sections, canThrowExtendedErrors);
if (dh == null) {
return null;
return null;
}
final Deck d = new Deck(dh.getName());
d.setComment(dh.getComment());
d.getMain().set(readCardList(sections.get("main")));
d.getSideboard().set(readCardList(sections.get("sideboard")));
d.getMain().set(Deck.readCardList(sections.get("main")));
d.getSideboard().set(Deck.readCardList(sections.get("sideboard")));
return d;
}
@@ -213,37 +245,29 @@ public class Deck extends DeckBase implements Serializable, IHasName {
return out;
}
/**
* <p>
* writeDeck.
* </p>
*
* @param d
* a {@link forge.deck.Deck} object.
* @param out
* a {@link java.io.BufferedWriter} object.
* @throws java.io.IOException
* if any.
*
* @return the list
*/
public List<String> save() {
final List<String> out = new ArrayList<String>();
out.add(String.format("[metadata]"));
out.add(String.format("%s=%s", DeckFileHeader.NAME, getName().replaceAll("\n", "")));
out.add(String.format("%s=%s", DeckFileHeader.NAME, this.getName().replaceAll("\n", "")));
// these are optional
if (getComment() != null) {
out.add(String.format("%s=%s", DeckFileHeader.COMMENT, getComment().replaceAll("\n", "")));
if (this.getComment() != null) {
out.add(String.format("%s=%s", DeckFileHeader.COMMENT, this.getComment().replaceAll("\n", "")));
}
out.add(String.format("%s", "[main]"));
out.addAll(writeCardPool(getMain()));
out.addAll(Deck.writeCardPool(this.getMain()));
out.add(String.format("%s", "[sideboard]"));
out.addAll(writeCardPool(getSideboard()));
out.addAll(Deck.writeCardPool(this.getSideboard()));
return out;
}
}

View File

@@ -1,13 +1,31 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.deck;
import java.io.Serializable;
import forge.item.CardPrinted;
import forge.item.ItemPoolView;
import forge.util.IHasName;
/**
/**
* TODO: Write javadoc for this type.
*
*
*/
public abstract class DeckBase implements IHasName, Serializable, Comparable<DeckBase> {
private static final long serialVersionUID = -7538150536939660052L;
@@ -16,10 +34,18 @@ public abstract class DeckBase implements IHasName, Serializable, Comparable<Dec
private final String name;
private String comment = null;
public DeckBase(String name0) {
name = name0;
/**
* Instantiates a new deck base.
*
* @param name0 the name0
*/
public DeckBase(final String name0) {
this.name = name0;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(final DeckBase d) {
return this.getName().compareTo(d.getName());
@@ -35,13 +61,26 @@ public abstract class DeckBase implements IHasName, Serializable, Comparable<Dec
return false;
}
/* (non-Javadoc)
* @see forge.util.IHasName#getName()
*/
@Override
public String getName() {
return this.name;
}
/**
* Gets the card pool.
*
* @return the card pool
*/
public abstract ItemPoolView<CardPrinted> getCardPool();
/**
* Sets the comment.
*
* @param comment the new comment
*/
public void setComment(final String comment) {
this.comment = comment;
}
@@ -57,20 +96,42 @@ public abstract class DeckBase implements IHasName, Serializable, Comparable<Dec
return this.comment;
}
/**
* New instance.
*
* @param name0 the name0
* @return the deck base
*/
protected abstract DeckBase newInstance(String name0);
protected void cloneFieldsTo(DeckBase clone) {
/**
* Clone fields to.
*
* @param clone the clone
*/
protected void cloneFieldsTo(final DeckBase clone) {
clone.comment = this.comment;
}
public DeckBase copyTo(String name0) {
DeckBase obj = newInstance(name0);
cloneFieldsTo(obj);
/**
* Copy to.
*
* @param name0 the name0
* @return the deck base
*/
public DeckBase copyTo(final String name0) {
final DeckBase obj = this.newInstance(name0);
this.cloneFieldsTo(obj);
return obj;
}
/**
* Gets the best file name.
*
* @return the best file name
*/
public final String getBestFileName() {
final char[] c = getName().toCharArray();
final char[] c = this.getName().toCharArray();
final StringBuilder sb = new StringBuilder();
for (int i = 0; (i < c.length) && (i < 20); i++) {
if (Character.isLetterOrDigit(c[i]) || (c[i] == '-')) {

View File

@@ -1,3 +1,20 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.deck;
import java.util.ArrayList;
@@ -7,51 +24,90 @@ import forge.item.CardPrinted;
import forge.item.ItemPoolView;
import forge.util.IHasName;
/**
/**
* TODO: Write javadoc for this type.
*
*
*/
public class DeckGroup extends DeckBase implements IHasName {
public DeckGroup(String name0) {
/**
* Instantiates a new deck group.
*
* @param name0 the name0
*/
public DeckGroup(final String name0) {
super(name0);
}
private static final long serialVersionUID = -1628725522049635829L;
private Deck humanDeck;
private List<Deck> aiDecks = new ArrayList<Deck>();
private final List<Deck> aiDecks = new ArrayList<Deck>();
/**
* Gets the human deck.
*
* @return the human deck
*/
public final Deck getHumanDeck() {
return humanDeck;
return this.humanDeck;
}
public final List<Deck> getAiDecks() {
return aiDecks;
}
public final void setHumanDeck(Deck humanDeck) { this.humanDeck = humanDeck; }
public final void addAiDeck(Deck aiDeck) {
/**
* Gets the ai decks.
*
* @return the ai decks
*/
public final List<Deck> getAiDecks() {
return this.aiDecks;
}
/**
* Sets the human deck.
*
* @param humanDeck the new human deck
*/
public final void setHumanDeck(final Deck humanDeck) {
this.humanDeck = humanDeck;
}
/**
* Adds the ai deck.
*
* @param aiDeck the ai deck
*/
public final void addAiDeck(final Deck aiDeck) {
if (aiDeck == null) {
return;
}
this.aiDecks.add(aiDeck);
}
/* (non-Javadoc)
* @see forge.deck.DeckBase#getCardPool()
*/
@Override
public ItemPoolView<CardPrinted> getCardPool() {
return getHumanDeck().getMain();
return this.getHumanDeck().getMain();
}
public void addAiDecks(Deck[] computer) {
for (int i = 0; i < computer.length; i++) {
aiDecks.add(computer[i]);
/**
* Adds the ai decks.
*
* @param computer the computer
*/
public void addAiDecks(final Deck[] computer) {
for (final Deck element : computer) {
this.aiDecks.add(element);
}
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.DeckBase#newInstance(java.lang.String)
*/
@Override
protected DeckBase newInstance(String name0) {
protected DeckBase newInstance(final String name0) {
return new DeckGroup(name0);
}

View File

@@ -198,7 +198,7 @@ public class DeckRecognizer {
if (CardDb.instance().isCardSupported(name)) {
return Token.knownCard(CardDb.instance().getCard(name, true), n);
}
// TODO: recognize format: http://topdeck.ru/forum/index.php?showtopic=12711
//final Matcher foundEditionName = READ_SEPARATED_EDITION.matcher(name);

View File

@@ -38,15 +38,21 @@ public class DeckSection extends ItemPool<CardPrinted> {
super(CardPrinted.class);
}
public DeckSection(Iterable<Entry<CardPrinted, Integer>> cards) {
/**
* Instantiates a new deck section.
*
* @param cards the cards
*/
public DeckSection(final Iterable<Entry<CardPrinted, Integer>> cards) {
this();
addAll(cards);
this.addAll(cards);
}
/**
* Sets the.
*
* @param cardNames the card names
*
* @param cardNames
* the card names
*/
public void set(final Iterable<String> cardNames) {
this.clear();
@@ -55,8 +61,9 @@ public class DeckSection extends ItemPool<CardPrinted> {
/**
* Adds the.
*
* @param card the card
*
* @param card
* the card
*/
public void add(final Card card) {
this.add(CardDb.instance().getCard(card));
@@ -64,9 +71,11 @@ public class DeckSection extends ItemPool<CardPrinted> {
/**
* Adds the.
*
* @param cardName the card name
* @param setCode the set code
*
* @param cardName
* the card name
* @param setCode
* the set code
*/
public void add(final String cardName, final String setCode) {
this.add(CardDb.instance().getCard(cardName, setCode));
@@ -77,15 +86,17 @@ public class DeckSection extends ItemPool<CardPrinted> {
*
* @param cardName the card name
* @param setCode the set code
* @param amount the amount
*/
public void add(final String cardName, final String setCode, int amount) {
public void add(final String cardName, final String setCode, final int amount) {
this.add(CardDb.instance().getCard(cardName, setCode), amount);
}
/**
* Adds the.
*
* @param cardList the card list
*
* @param cardList
* the card list
*/
public void add(final CardList cardList) {
for (final Card c : cardList) {
@@ -95,9 +106,10 @@ public class DeckSection extends ItemPool<CardPrinted> {
/**
* TODO: Write javadoc for this method.
* @param string
*
* @param cardName the card name
*/
public void add(String cardName) {
public void add(final String cardName) {
this.add(CardDb.instance().getCard(cardName));
}

View File

@@ -26,8 +26,8 @@ import org.apache.commons.lang3.StringUtils;
import forge.deck.Deck;
import forge.deck.DeckGroup;
import forge.util.FileUtil;
import forge.util.StorageReaderFolder;
import forge.util.IItemSerializer;
import forge.util.StorageReaderFolder;
/**
* TODO: Write javadoc for this type.
@@ -36,42 +36,49 @@ import forge.util.IItemSerializer;
public class DeckGroupSerializer extends StorageReaderFolder<DeckGroup> implements IItemSerializer<DeckGroup> {
private final String HUMAN_DECK_FILE = "human.dck";
public DeckGroupSerializer(File deckDir0) {
/**
* Instantiates a new deck group serializer.
*
* @param deckDir0 the deck dir0
*/
public DeckGroupSerializer(final File deckDir0) {
super(deckDir0);
}
/** The Constant MAX_DRAFT_PLAYERS. */
public final static int MAX_DRAFT_PLAYERS = 8;
/**
*
* Write draft Decks.
*
* @param drafts
* a Deck[]
*
* @param unit the unit
*/
@Override
public void save(DeckGroup unit) {
final File f = makeFileFor(unit);
public void save(final DeckGroup unit) {
final File f = this.makeFileFor(unit);
f.mkdir();
FileUtil.writeFile(new File(f, HUMAN_DECK_FILE), unit.getHumanDeck().save());
List<Deck> aiDecks = unit.getAiDecks();
FileUtil.writeFile(new File(f, this.HUMAN_DECK_FILE), unit.getHumanDeck().save());
final List<Deck> aiDecks = unit.getAiDecks();
for (int i = 1; i <= aiDecks.size(); i++) {
FileUtil.writeFile(new File(f, "ai-" + i + ".dck"), aiDecks.get(i - 1).save());
}
}
protected final DeckGroup read(File file) {
/* (non-Javadoc)
* @see forge.util.StorageReaderFolder#read(java.io.File)
*/
@Override
protected final DeckGroup read(final File file) {
Deck human = Deck.fromFile(new File(file, HUMAN_DECK_FILE));
final Deck human = Deck.fromFile(new File(file, this.HUMAN_DECK_FILE));
if (null == human) {
return null;
}
final DeckGroup d = new DeckGroup(human.getName());
d.setHumanDeck(human);
for (int i = 1; i < MAX_DRAFT_PLAYERS; i++) {
File theFile = new File(file, "ai-" + i + ".dck");
for (int i = 1; i < DeckGroupSerializer.MAX_DRAFT_PLAYERS; i++) {
final File theFile = new File(file, "ai-" + i + ".dck");
if (!theFile.exists()) {
break;
}
@@ -81,25 +88,35 @@ public class DeckGroupSerializer extends StorageReaderFolder<DeckGroup> implemen
return d;
}
/* (non-Javadoc)
* @see forge.deck.IDeckSerializer#erase(forge.item.CardCollectionBase, java.io.File)
/*
* (non-Javadoc)
*
* @see forge.deck.IDeckSerializer#erase(forge.item.CardCollectionBase,
* java.io.File)
*/
@Override
public void erase(DeckGroup unit) {
File dir = makeFileFor(unit);
public void erase(final DeckGroup unit) {
final File dir = this.makeFileFor(unit);
final File[] files = dir.listFiles();
for (File f : files) {
for (final File f : files) {
f.delete();
}
dir.delete();
}
/**
* Make file for.
*
* @param decks the decks
* @return the file
*/
public File makeFileFor(final DeckGroup decks) {
return new File(getDirectory(), decks.getBestFileName());
return new File(this.getDirectory(), decks.getBestFileName());
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.io.DeckSerializerBase#getFileFilter()
*/
@Override
@@ -107,10 +124,11 @@ public class DeckGroupSerializer extends StorageReaderFolder<DeckGroup> implemen
return new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
boolean isVisibleFolder = dir.isDirectory() && !dir.isHidden();
boolean hasGoodName = StringUtils.isNotEmpty(name) && !name.startsWith(".");
return isVisibleFolder && hasGoodName && new File(dir, HUMAN_DECK_FILE).exists();
public boolean accept(final File dir, final String name) {
final boolean isVisibleFolder = dir.isDirectory() && !dir.isHidden();
final boolean hasGoodName = StringUtils.isNotEmpty(name) && !name.startsWith(".");
return isVisibleFolder && hasGoodName
&& new File(dir, DeckGroupSerializer.this.HUMAN_DECK_FILE).exists();
}
};
}

View File

@@ -39,9 +39,9 @@ import forge.item.CardPrinted;
import forge.util.FileSection;
import forge.util.FileSectionManual;
import forge.util.FileUtil;
import forge.util.IItemSerializer;
import forge.util.SectionUtil;
import forge.util.StorageReaderFolder;
import forge.util.IItemSerializer;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
@@ -53,11 +53,15 @@ import freemarker.template.TemplateException;
*/
public class DeckSerializer extends StorageReaderFolder<Deck> implements IItemSerializer<Deck> {
public DeckSerializer(File deckDir0) {
/**
* Instantiates a new deck serializer.
*
* @param deckDir0 the deck dir0
*/
public DeckSerializer(final File deckDir0) {
super(deckDir0);
}
/** Constant <code>DCKFileFilter</code>. */
public static final FilenameFilter DCK_FILE_FILTER = new FilenameFilter() {
@Override
@@ -90,7 +94,6 @@ public class DeckSerializer extends StorageReaderFolder<Deck> implements IItemSe
}
};
/**
* <p>
* writeDeck.
@@ -203,72 +206,85 @@ public class DeckSerializer extends StorageReaderFolder<Deck> implements IItemSe
}
}
/* (non-Javadoc)
* @see forge.deck.IDeckSerializer#save(forge.item.CardCollectionBase, java.io.File)
/*
* (non-Javadoc)
*
* @see forge.deck.IDeckSerializer#save(forge.item.CardCollectionBase,
* java.io.File)
*/
@Override
public void save(Deck unit) {
FileUtil.writeFile(makeFileFor(unit), unit.save());
public void save(final Deck unit) {
FileUtil.writeFile(this.makeFileFor(unit), unit.save());
}
/* (non-Javadoc)
* @see forge.deck.IDeckSerializer#erase(forge.item.CardCollectionBase, java.io.File)
/*
* (non-Javadoc)
*
* @see forge.deck.IDeckSerializer#erase(forge.item.CardCollectionBase,
* java.io.File)
*/
@Override
public void erase(Deck unit) {
makeFileFor(unit).delete();
public void erase(final Deck unit) {
this.makeFileFor(unit).delete();
}
/**
*
* Make file name.
*
* @param deckName
* a String
* @param deckType
* a GameType
*
* @param deck the deck
* @return a File
*/
public File makeFileFor(final Deck deck) {
return new File(getDirectory(), deck.getBestFileName() + ".dck");
return new File(this.getDirectory(), deck.getBestFileName() + ".dck");
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.io.DeckSerializerBase#read(java.io.File)
*/
@Override
protected Deck read(File file) {
Map<String,List<String>> sections = SectionUtil.parseSections(FileUtil.readFile(file));
protected Deck read(final File file) {
final Map<String, List<String>> sections = SectionUtil.parseSections(FileUtil.readFile(file));
return Deck.fromSections(sections, true);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.io.DeckSerializerBase#getFileFilter()
*/
@Override
protected FilenameFilter getFileFilter() {
return DCK_FILE_FILTER;
return DeckSerializer.DCK_FILE_FILTER;
}
public static DeckFileHeader readDeckMetadata(final Map<String, List<String>> map, boolean canThrow) {
if (map == null) { return null; }
List<String> metadata = map.get("metadata");
if (metadata != null) {
/**
* Read deck metadata.
*
* @param map the map
* @param canThrow the can throw
* @return the deck file header
*/
public static DeckFileHeader readDeckMetadata(final Map<String, List<String>> map, final boolean canThrow) {
if (map == null) {
return null;
}
final List<String> metadata = map.get("metadata");
if (metadata != null) {
return new DeckFileHeader(FileSection.parse(metadata, "="));
}
List<String> general = map.get("general");
if ( general != null )
{
if ( canThrow ) {
}
final List<String> general = map.get("general");
if (general != null) {
if (canThrow) {
throw new OldDeckFileFormatException();
}
FileSectionManual fs = new FileSectionManual();
final FileSectionManual fs = new FileSectionManual();
fs.put(DeckFileHeader.NAME, StringUtils.join(map.get(""), " "));
fs.put(DeckFileHeader.DECK_TYPE, StringUtils.join(general, " "));
return new DeckFileHeader(fs);
}
return null;
}

View File

@@ -1,3 +1,20 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.deck.io;
import java.io.File;
@@ -20,9 +37,9 @@ import forge.util.FileUtil;
import forge.util.IFolderMap;
import forge.util.SectionUtil;
/**
/**
* TODO: Write javadoc for this type.
*
*
*/
public class OldDeckParser {
@@ -36,35 +53,65 @@ public class OldDeckParser {
/**
* TODO: Write javadoc for Constructor.
* @param file
* @param constructed2
* @param draft2
* @param sealed2
* @param cube2
*
* @param file the file
* @param constructed2 the constructed2
* @param draft2 the draft2
* @param sealed2 the sealed2
* @param cube2 the cube2
*/
public OldDeckParser(File file, IFolderMap<Deck> constructed2, IFolderMap<DeckGroup> draft2,
IFolderMap<DeckGroup> sealed2, IFolderMap<Deck> cube2) {
deckDir = file;
sealed = sealed2;
constructed = constructed2;
cube = cube2;
draft = draft2;
public OldDeckParser(final File file, final IFolderMap<Deck> constructed2, final IFolderMap<DeckGroup> draft2,
final IFolderMap<DeckGroup> sealed2, final IFolderMap<Deck> cube2) {
this.deckDir = file;
this.sealed = sealed2;
this.constructed = constructed2;
this.cube = cube2;
this.draft = draft2;
}
/**
* Gets the sealed.
*
* @return the sealed
*/
protected final IFolderMap<DeckGroup> getSealed() {
return sealed;
return this.sealed;
}
/**
* Gets the constructed.
*
* @return the constructed
*/
protected final IFolderMap<Deck> getConstructed() {
return constructed;
return this.constructed;
}
/**
* Gets the draft.
*
* @return the draft
*/
protected final IFolderMap<DeckGroup> getDraft() {
return draft;
return this.draft;
}
/**
* Gets the cube.
*
* @return the cube
*/
protected final IFolderMap<Deck> getCube() {
return cube;
return this.cube;
}
/**
* Gets the deck dir.
*
* @return the deck dir
*/
protected final File getDeckDir() {
return deckDir;
return this.deckDir;
}
private final IFolderMap<DeckGroup> sealed;
@@ -72,23 +119,24 @@ public class OldDeckParser {
private final IFolderMap<DeckGroup> draft;
private final IFolderMap<Deck> cube;
private final File deckDir;
/**
* TODO: Write javadoc for this method.
*/
public void tryParse() {
convertConstructedAndSealed();
convertDrafts();
this.convertConstructedAndSealed();
this.convertDrafts();
}
private void convertDrafts() {
for (File f : deckDir.listFiles(bdkFileFilter)) {
for (final File f : this.deckDir.listFiles(OldDeckParser.bdkFileFilter)) {
boolean gotError = false;
Deck human = Deck.fromFile(new File(f, "0.dck"));
final Deck human = Deck.fromFile(new File(f, "0.dck"));
final DeckGroup d = new DeckGroup(human.getName());
d.setHumanDeck(human);
for (int i = 1; i < DeckGroupSerializer.MAX_DRAFT_PLAYERS; i++) {
Deck nextAi = Deck.fromFile(new File(f, i + ".dck"));
final Deck nextAi = Deck.fromFile(new File(f, i + ".dck"));
if (nextAi == null) {
gotError = true;
break;
@@ -98,14 +146,15 @@ public class OldDeckParser {
boolean mayDelete = !gotError;
if (!gotError) {
draft.add(d);
this.draft.add(d);
} else {
String msg = String.format("Draft '%s' lacked some decks.%n%nShould it be deleted?");
mayDelete = JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, msg, "Draft loading error", JOptionPane.YES_NO_OPTION);
final String msg = String.format("Draft '%s' lacked some decks.%n%nShould it be deleted?");
mayDelete = JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, msg, "Draft loading error",
JOptionPane.YES_NO_OPTION);
}
if (mayDelete) {
for (File f1 : f.listFiles()) {
for (final File f1 : f.listFiles()) {
f1.delete();
}
f.delete();
@@ -115,102 +164,114 @@ public class OldDeckParser {
}
private void convertConstructedAndSealed() {
boolean allowDeleteUnsupportedConstructed = false;
Map<String, Pair<DeckGroup, MutablePair<File, File>>> sealedDecks = new TreeMap<String, Pair<DeckGroup, MutablePair<File, File>>>(String.CASE_INSENSITIVE_ORDER);
boolean allowDeleteUnsupportedConstructed = false;
final Map<String, Pair<DeckGroup, MutablePair<File, File>>> sealedDecks = new TreeMap<String, Pair<DeckGroup, MutablePair<File, File>>>(
String.CASE_INSENSITIVE_ORDER);
for (File f : deckDir.listFiles(DeckSerializer.DCK_FILE_FILTER)) {
boolean importedOk = false;
for (final File f : this.deckDir.listFiles(DeckSerializer.DCK_FILE_FILTER)) {
boolean importedOk = false;
List<String> fileLines = FileUtil.readFile(f);
Map<String, List<String>> sections = SectionUtil.parseSections(fileLines);
DeckFileHeader dh = DeckSerializer.readDeckMetadata(sections, false);
String name = dh.getName();
final List<String> fileLines = FileUtil.readFile(f);
final Map<String, List<String>> sections = SectionUtil.parseSections(fileLines);
final DeckFileHeader dh = DeckSerializer.readDeckMetadata(sections, false);
String name = dh.getName();
if (dh.isCustomPool()) {
try {
cube.add(Deck.fromSections(sections));
importedOk = true;
} catch (NoSuchElementException ex) {
if (!allowDeleteUnsupportedConstructed) {
String msg = String.format("Can not convert deck '%s' for some unsupported cards it contains. %n%s%n%nMay Forge delete all such decks?", name, ex.getMessage());
allowDeleteUnsupportedConstructed = JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, msg, "Problem converting decks", JOptionPane.YES_NO_OPTION);
}
}
if (importedOk || allowDeleteUnsupportedConstructed) {
f.delete();
}
continue;
}
if (dh.isCustomPool()) {
try {
this.cube.add(Deck.fromSections(sections));
importedOk = true;
} catch (final NoSuchElementException ex) {
if (!allowDeleteUnsupportedConstructed) {
final String msg = String
.format("Can not convert deck '%s' for some unsupported cards it contains. %n%s%n%nMay Forge delete all such decks?",
name, ex.getMessage());
allowDeleteUnsupportedConstructed = JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(
null, msg, "Problem converting decks", JOptionPane.YES_NO_OPTION);
}
}
if (importedOk || allowDeleteUnsupportedConstructed) {
f.delete();
}
continue;
}
switch(dh.getDeckType()) {
case Constructed:
try {
constructed.add(Deck.fromSections(sections));
importedOk = true;
} catch (NoSuchElementException ex) {
if (!allowDeleteUnsupportedConstructed) {
String msg = String.format("Can not convert deck '%s' for some unsupported cards it contains. %n%s%n%nMay Forge delete all such decks?", name, ex.getMessage());
allowDeleteUnsupportedConstructed = JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, msg, "Problem converting decks", JOptionPane.YES_NO_OPTION);
}
}
if (importedOk || allowDeleteUnsupportedConstructed) {
f.delete();
}
break;
switch (dh.getDeckType()) {
case Constructed:
try {
this.constructed.add(Deck.fromSections(sections));
importedOk = true;
} catch (final NoSuchElementException ex) {
if (!allowDeleteUnsupportedConstructed) {
final String msg = String
.format("Can not convert deck '%s' for some unsupported cards it contains. %n%s%n%nMay Forge delete all such decks?",
name, ex.getMessage());
allowDeleteUnsupportedConstructed = JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(
null, msg, "Problem converting decks", JOptionPane.YES_NO_OPTION);
}
}
if (importedOk || allowDeleteUnsupportedConstructed) {
f.delete();
}
break;
case Sealed:
boolean isAi = dh.getPlayerType() == PlayerType.COMPUTER;
name = name.startsWith("AI_") ? name.replace("AI_", "") : name;
case Sealed:
final boolean isAi = dh.getPlayerType() == PlayerType.COMPUTER;
name = name.startsWith("AI_") ? name.replace("AI_", "") : name;
Pair<DeckGroup, MutablePair<File, File>> stored = sealedDecks.get(name);
if (null == stored) {
stored = ImmutablePair.of(new DeckGroup(name), MutablePair.of((File) null, (File) null));
}
Pair<DeckGroup, MutablePair<File, File>> stored = sealedDecks.get(name);
if (null == stored) {
stored = ImmutablePair.of(new DeckGroup(name), MutablePair.of((File) null, (File) null));
}
Deck deck = Deck.fromSections(sections);
if (isAi) {
stored.getLeft().addAiDeck(deck);
stored.getRight().setRight(f);
} else {
stored.getLeft().setHumanDeck(deck);
stored.getRight().setLeft(f);
}
final Deck deck = Deck.fromSections(sections);
if (isAi) {
stored.getLeft().addAiDeck(deck);
stored.getRight().setRight(f);
} else {
stored.getLeft().setHumanDeck(deck);
stored.getRight().setLeft(f);
}
if (stored.getLeft().getHumanDeck() != null && !stored.getLeft().getAiDecks().isEmpty()) {
// have both parts of sealed deck, may convert
sealed.add(stored.getLeft());
stored.getRight().getLeft().delete();
stored.getRight().getRight().delete();
if ((stored.getLeft().getHumanDeck() != null) && !stored.getLeft().getAiDecks().isEmpty()) {
// have both parts of sealed deck, may convert
this.sealed.add(stored.getLeft());
stored.getRight().getLeft().delete();
stored.getRight().getRight().delete();
// there stay only orphans
sealedDecks.remove(name);
} else {
sealedDecks.put(name, stored);
}
break;
}
}
// there stay only orphans
sealedDecks.remove(name);
} else {
sealedDecks.put(name, stored);
}
break;
}
}
// advise to kill orphaned decks
if (!sealedDecks.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Pair<DeckGroup, MutablePair<File, File>> s : sealedDecks.values()) {
String missingPart = s.getRight().getLeft() == null ? "human" : "computer";
sb.append(String.format("Sealed deck '%s' has no matching '%s' deck.%n", s.getKey().getName(), missingPart));
}
sb.append(System.getProperty("line.separator"));
sb.append("May Forge delete these decks?");
int response = JOptionPane.showConfirmDialog(null, sb.toString(), "Some of your sealed decks are orphaned", JOptionPane.YES_NO_OPTION);
if (response == JOptionPane.YES_OPTION) {
for (Pair<DeckGroup, MutablePair<File, File>> s : sealedDecks.values()) {
if (s.getRight().getLeft() != null) { s.getRight().getLeft().delete(); }
if (s.getRight().getRight() != null) { s.getRight().getRight().delete(); }
}
}
}
// advise to kill orphaned decks
if (!sealedDecks.isEmpty()) {
final StringBuilder sb = new StringBuilder();
for (final Pair<DeckGroup, MutablePair<File, File>> s : sealedDecks.values()) {
final String missingPart = s.getRight().getLeft() == null ? "human" : "computer";
sb.append(String.format("Sealed deck '%s' has no matching '%s' deck.%n", s.getKey().getName(),
missingPart));
}
sb.append(System.getProperty("line.separator"));
sb.append("May Forge delete these decks?");
final int response = JOptionPane.showConfirmDialog(null, sb.toString(),
"Some of your sealed decks are orphaned", JOptionPane.YES_NO_OPTION);
if (response == JOptionPane.YES_OPTION) {
for (final Pair<DeckGroup, MutablePair<File, File>> s : sealedDecks.values()) {
if (s.getRight().getLeft() != null) {
s.getRight().getLeft().delete();
}
if (s.getRight().getRight() != null) {
s.getRight().getRight().delete();
}
}
}
}
}
/**
* @return the deckDir
*/

View File

@@ -56,9 +56,9 @@ public enum GameType {
/**
* Smart value of.
*
* @param value
* the value
*
* @param value the value
* @param defaultValue the default value
* @return the game type
*/
public static GameType smartValueOf(final String value, GameType defaultValue) {

View File

@@ -43,9 +43,10 @@ public class CustomLimited extends DeckBase {
/**
* TODO: Write javadoc for Constructor.
* @param name0
*
* @param name0 the name0
*/
public CustomLimited(String name0) {
public CustomLimited(final String name0) {
super(name0);
}
@@ -60,7 +61,6 @@ public class CustomLimited extends DeckBase {
/** The Num cards. */
private int numCards = 15;
private final Map<CardRarity, Integer> numRarity = new EnumMap<CardRarity, Integer>(CardRarity.class);
/** The Num packs. */
@@ -83,14 +83,14 @@ public class CustomLimited extends DeckBase {
/**
* Parses the.
*
* @param dfData
* the df data
*
* @param dfData the df data
* @param cubes the cubes
* @return the custom limited
*/
public static CustomLimited parse(final List<String> dfData, IFolderMapView<Deck> cubes) {
public static CustomLimited parse(final List<String> dfData, final IFolderMapView<Deck> cubes) {
FileSection data = FileSection.parse(dfData, ":");
final FileSection data = FileSection.parse(dfData, ":");
final CustomLimited cd = new CustomLimited(data.get("Name"));
cd.setIgnoreRarity(data.getBoolean("IgnoreRarity"));
@@ -107,9 +107,10 @@ public class CustomLimited extends DeckBase {
cd.numPacks = data.getInt("NumPacks");
String deckName = data.get("DeckFile");
Deck deckCube = cubes.get(deckName);
cd.cardPool = deckCube == null ? ItemPool.createFrom(CardDb.instance().getAllUniqueCards(), CardPrinted.class) : deckCube.getMain();
final String deckName = data.get("DeckFile");
final Deck deckCube = cubes.get(deckName);
cd.cardPool = deckCube == null ? ItemPool.createFrom(CardDb.instance().getAllUniqueCards(), CardPrinted.class)
: deckCube.getMain();
return cd;
}
@@ -209,30 +210,33 @@ public class CustomLimited extends DeckBase {
this.landSetCode = landSetCodeIn;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.item.CardCollectionBase#getCardPool()
*/
@Override
public ItemPoolView<CardPrinted> getCardPool() {
return cardPool;
return this.cardPool;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.DeckBase#getInstance(java.lang.String)
*/
@Override
protected DeckBase newInstance(String name0) {
protected DeckBase newInstance(final String name0) {
return new CustomLimited(name0);
}
/**
* TODO: Write javadoc for this method.
* @return
*
* @return the numbers by rarity
*/
public Map<CardRarity, Integer> getNumbersByRarity() {
return numRarity;
return this.numRarity;
}
}

View File

@@ -1,7 +1,25 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.gui.deckeditor;
import java.awt.Component;
import java.util.ArrayList;
import net.slightlymagic.braids.util.lambda.Lambda0;
import org.apache.commons.lang3.StringUtils;
@@ -9,9 +27,10 @@ import org.apache.commons.lang3.StringUtils;
import forge.deck.DeckBase;
import forge.util.IFolderMap;
/**
/**
* TODO: Write javadoc for this type.
*
* @param <T> the generic type
*/
public class DeckController<T extends DeckBase> implements IDeckController<T> {
@@ -22,184 +41,219 @@ public class DeckController<T extends DeckBase> implements IDeckController<T> {
private final DeckEditorBase<?, T> view;
private final Lambda0<T> newModelCreator;
public DeckController(IFolderMap<T> folder0, DeckEditorBase<?, T> view0, Lambda0<T> newModelCreator0)
{
folder = folder0;
view = view0;
model = null;
saved = true;
modelInStore = false;
newModelCreator = newModelCreator0;
/**
* Instantiates a new deck controller.
*
* @param folder0 the folder0
* @param view0 the view0
* @param newModelCreator0 the new model creator0
*/
public DeckController(final IFolderMap<T> folder0, final DeckEditorBase<?, T> view0,
final Lambda0<T> newModelCreator0) {
this.folder = folder0;
this.view = view0;
this.model = null;
this.saved = true;
this.modelInStore = false;
this.newModelCreator = newModelCreator0;
}
/**
* Gets the model.
*
* @return the document
*/
@Override
public T getModel() {
return model;
return this.model;
}
/**
* @param document0 the document to set
* Sets the model.
*
* @param document the new model
*/
public void setModel(T document) {
setModel(document, false);
@Override
public void setModel(final T document) {
this.setModel(document, false);
}
public void setModel(T document, boolean isStored) {
modelInStore = isStored;
/**
* Sets the model.
*
* @param document the document
* @param isStored the is stored
*/
public void setModel(final T document, final boolean isStored) {
this.modelInStore = isStored;
this.model = document;
view.updateView();
saved = true; // unless set to false in notify
if (!isModelInSyncWithFolder()) {
notifyModelChanged();
this.view.updateView();
this.saved = true; // unless set to false in notify
if (!this.isModelInSyncWithFolder()) {
this.notifyModelChanged();
}
}
private boolean isModelInSyncWithFolder() {
T modelStored = folder.get(model.getName());
final T modelStored = this.folder.get(this.model.getName());
// checks presence in dictionary only.
if (modelStored == model) {
if (modelStored == this.model) {
return true;
}
if (null == modelStored) {
return false;
}
return modelStored.equals(model);
return modelStored.equals(this.model);
}
/**
* Gets the view.
*
* @return the view
*/
@Override
public DeckEditorBase<?, T> getView() {
return view;
return this.view;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#notifyModelChanged()
*/
@Override
public void notifyModelChanged() {
saved = false;
//view.setTitle();
this.saved = false;
// view.setTitle();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#getOwnerWindow()
*/
@Override
public Component getOwnerWindow() {
return getView();
return this.getView();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#getSavedModelNames()
*/
@Override
public ArrayList<String> getSavedNames() {
return new ArrayList<String>(folder.getNames());
return new ArrayList<String>(this.folder.getNames());
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#load(java.lang.String)
*/
@Override
public void load(String name) {
setModel(folder.get(name), true);
public void load(final String name) {
this.setModel(this.folder.get(name), true);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#save()
*/
@Override
public void save() {
folder.add(model);
saved = true;
modelInStore = true;
this.folder.add(this.model);
this.saved = true;
this.modelInStore = true;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#rename(java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
public void saveAs(String name0) {
setModel((T) model.copyTo(name0), false);
save();
public void saveAs(final String name0) {
this.setModel((T) this.model.copyTo(name0), false);
this.save();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#isSaved()
*/
@Override
public boolean isSaved() {
return saved;
return this.saved;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#delete()
*/
@Override
public void delete() {
if (StringUtils.isNotBlank(model.getName())) {
folder.delete(model.getName());
if (StringUtils.isNotBlank(this.model.getName())) {
this.folder.delete(this.model.getName());
}
modelInStore = false;
newModel();
this.modelInStore = false;
this.newModel();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#isGoodName(java.lang.String)
*/
@Override
public boolean fileExists(String deckName) {
return !folder.isUnique(deckName);
public boolean fileExists(final String deckName) {
return !this.folder.isUnique(deckName);
}
@Override
public boolean isGoodName(String deckName) {
return StringUtils.isNotBlank(deckName) && folder.isUnique(deckName);
}
/* (non-Javadoc)
* @see forge.gui.deckeditor.IDeckController#isGoodName(java.lang.String)
*/
@Override
public boolean isGoodName(final String deckName) {
return StringUtils.isNotBlank(deckName) && this.folder.isUnique(deckName);
}
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#importDeck(forge.deck.Deck)
*/
@Override
public void importDeck(T newDeck) {
setModel(newDeck);
public void importDeck(final T newDeck) {
this.setModel(newDeck);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#isModelInStore()
*/
@Override
public boolean isModelInStore() {
return modelInStore;
return this.modelInStore;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.IDeckController#newModel()
*/
@Override
public void newModel() {
model = newModelCreator.apply();
saved = true;
view.updateView();
this.model = this.newModelCreator.apply();
this.saved = true;
this.view.updateView();
}
}

View File

@@ -39,6 +39,9 @@ import forge.item.ItemPoolView;
/**
* The Class DeckEditorBase.
*
* @param <T> the generic type
* @param <TModel> the generic type
*/
public abstract class DeckEditorBase<T extends InventoryItem, TModel> extends JFrame {
private static final long serialVersionUID = -401223933343539977L;
@@ -78,6 +81,11 @@ public abstract class DeckEditorBase<T extends InventoryItem, TModel> extends JF
*
* @see forge.gui.deckeditor.DeckDisplay#getTop()
*/
/**
* Gets the top.
*
* @return the top
*/
public final ItemPoolView<T> getTop() {
return this.getTopTableWithCards().getCards();
}
@@ -88,11 +96,20 @@ public abstract class DeckEditorBase<T extends InventoryItem, TModel> extends JF
*
* @see forge.gui.deckeditor.DeckDisplay#getBottom()
*/
/**
* Gets the bottom.
*
* @return the bottom
*/
public final ItemPoolView<T> getBottom() {
return this.getBottomTableWithCards().getCards();
}
/**
* Gets the controller.
*
* @return the controller
*/
public abstract IDeckController<TModel> getController();
// THIS IS HERE FOR OVERLOADING!!!1
@@ -105,7 +122,13 @@ public abstract class DeckEditorBase<T extends InventoryItem, TModel> extends JF
*/
protected abstract Predicate<T> buildFilter();
/**
* Show.
*
* @param exitCommand the exit command
*/
public abstract void show(final Command exitCommand);
/**
* Analysis button_action performed.
*
@@ -126,17 +149,17 @@ public abstract class DeckEditorBase<T extends InventoryItem, TModel> extends JF
}
}
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckDisplay#setItems(forge.item.ItemPoolView,
* forge.item.ItemPoolView, forge.game.GameType)
*/
/**
* Update view.
*/
public abstract void updateView();
/**
* Update display.
*/

View File

@@ -76,12 +76,14 @@ public final class DeckEditorConstructed extends DeckEditorBase<CardPrinted, Dec
private FilterNameTypeSetPanel filterNameTypeSet;
private final IDeckController<Deck> controller;
/**
* Show.
*
* @param exitCommand
* the exit command
*/
@Override
public void show(final Command exitCommand) {
final Command exit = new Command() {
private static final long serialVersionUID = 5210924838133689758L;
@@ -93,13 +95,15 @@ public final class DeckEditorConstructed extends DeckEditorBase<CardPrinted, Dec
}
};
final MenuCommon menu = new MenuCommon(getController(), exit);
final MenuCommon menu = new MenuCommon(this.getController(), exit);
this.setJMenuBar(menu);
// do not change this!!!!
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent ev) { menu.close(); }
public void windowClosing(final WindowEvent ev) {
menu.close();
}
});
this.setup();
@@ -113,15 +117,24 @@ public final class DeckEditorConstructed extends DeckEditorBase<CardPrinted, Dec
private void setup() {
final List<TableColumnInfo<InventoryItem>> columns = new ArrayList<TableColumnInfo<InventoryItem>>();
columns.add(new TableColumnInfo<InventoryItem>("Qty", 30, PresetColumns.FN_QTY_COMPARE, PresetColumns.FN_QTY_GET));
columns.add(new TableColumnInfo<InventoryItem>("Name", 175, PresetColumns.FN_NAME_COMPARE, PresetColumns.FN_NAME_GET));
columns.add(new TableColumnInfo<InventoryItem>("Cost", 75, PresetColumns.FN_COST_COMPARE, PresetColumns.FN_COST_GET));
columns.add(new TableColumnInfo<InventoryItem>("Color", 60, PresetColumns.FN_COLOR_COMPARE, PresetColumns.FN_COLOR_GET));
columns.add(new TableColumnInfo<InventoryItem>("Type", 100, PresetColumns.FN_TYPE_COMPARE, PresetColumns.FN_TYPE_GET));
columns.add(new TableColumnInfo<InventoryItem>("Stats", 60, PresetColumns.FN_STATS_COMPARE, PresetColumns.FN_STATS_GET));
columns.add(new TableColumnInfo<InventoryItem>("R", 25, PresetColumns.FN_RARITY_COMPARE, PresetColumns.FN_RARITY_GET));
columns.add(new TableColumnInfo<InventoryItem>("Set", 40, PresetColumns.FN_SET_COMPARE, PresetColumns.FN_SET_GET));
columns.add(new TableColumnInfo<InventoryItem>("AI", 30, PresetColumns.FN_AI_STATUS_COMPARE, PresetColumns.FN_AI_STATUS_GET));
columns.add(new TableColumnInfo<InventoryItem>("Qty", 30, PresetColumns.FN_QTY_COMPARE,
PresetColumns.FN_QTY_GET));
columns.add(new TableColumnInfo<InventoryItem>("Name", 175, PresetColumns.FN_NAME_COMPARE,
PresetColumns.FN_NAME_GET));
columns.add(new TableColumnInfo<InventoryItem>("Cost", 75, PresetColumns.FN_COST_COMPARE,
PresetColumns.FN_COST_GET));
columns.add(new TableColumnInfo<InventoryItem>("Color", 60, PresetColumns.FN_COLOR_COMPARE,
PresetColumns.FN_COLOR_GET));
columns.add(new TableColumnInfo<InventoryItem>("Type", 100, PresetColumns.FN_TYPE_COMPARE,
PresetColumns.FN_TYPE_GET));
columns.add(new TableColumnInfo<InventoryItem>("Stats", 60, PresetColumns.FN_STATS_COMPARE,
PresetColumns.FN_STATS_GET));
columns.add(new TableColumnInfo<InventoryItem>("R", 25, PresetColumns.FN_RARITY_COMPARE,
PresetColumns.FN_RARITY_GET));
columns.add(new TableColumnInfo<InventoryItem>("Set", 40, PresetColumns.FN_SET_COMPARE,
PresetColumns.FN_SET_GET));
columns.add(new TableColumnInfo<InventoryItem>("AI", 30, PresetColumns.FN_AI_STATUS_COMPARE,
PresetColumns.FN_AI_STATUS_GET));
columns.get(2).setCellRenderer(new ManaCostRenderer());
this.getTopTableWithCards().setup(columns, this.getCardView());
@@ -136,9 +149,7 @@ public final class DeckEditorConstructed extends DeckEditorBase<CardPrinted, Dec
/**
* Instantiates a new deck editor common.
*
* @param gameType
* the game type
*
*/
public DeckEditorConstructed() {
try {
@@ -153,8 +164,13 @@ public final class DeckEditorConstructed extends DeckEditorBase<CardPrinted, Dec
ErrorViewer.showError(ex);
}
Lambda0<Deck> newCreator = new Lambda0<Deck>() { @Override public Deck apply() { return new Deck(); } };
controller = new DeckController<Deck>(Singletons.getModel().getDecks().getConstructed(), this, newCreator);
final Lambda0<Deck> newCreator = new Lambda0<Deck>() {
@Override
public Deck apply() {
return new Deck();
}
};
this.controller = new DeckController<Deck>(Singletons.getModel().getDecks().getConstructed(), this, newCreator);
}
private void jbInit() {
@@ -206,7 +222,7 @@ public final class DeckEditorConstructed extends DeckEditorBase<CardPrinted, Dec
// Type filtering
final Font f = new Font("Tahoma", Font.PLAIN, 10);
for (final JCheckBox box : this.getFilterBoxes().getAllTypes()) {
box.setFont(f);
box.setFont(f);
box.setOpaque(false);
}
@@ -373,23 +389,26 @@ public final class DeckEditorConstructed extends DeckEditorBase<CardPrinted, Dec
dImport.setVisible(true);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#updateView()
*/
@Override
public void updateView() {
// if constructed, can add the all cards above
getTopTableWithCards().setDeck(ItemPool.createFrom(CardDb.instance().getAllCards(), CardPrinted.class));
getBottomTableWithCards().setDeck(controller.getModel().getMain());
this.getTopTableWithCards().setDeck(ItemPool.createFrom(CardDb.instance().getAllCards(), CardPrinted.class));
this.getBottomTableWithCards().setDeck(this.controller.getModel().getMain());
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#getController()
*/
@Override
public IDeckController<Deck> getController() {
return controller;
return this.controller;
}
}

View File

@@ -80,6 +80,7 @@ public final class DeckEditorLimited extends DeckEditorBase<CardPrinted, DeckGro
* @param exitCommand
* the exit command
*/
@Override
public void show(final Command exitCommand) {
final Command exit = new Command() {
private static final long serialVersionUID = 5210924838133689758L;
@@ -91,7 +92,7 @@ public final class DeckEditorLimited extends DeckEditorBase<CardPrinted, DeckGro
}
};
final MenuLimited menu = new MenuLimited(getController(), exit);
final MenuLimited menu = new MenuLimited(this.getController(), exit);
this.setJMenuBar(menu);
@@ -112,15 +113,24 @@ public final class DeckEditorLimited extends DeckEditorBase<CardPrinted, DeckGro
private void setup() {
final List<TableColumnInfo<InventoryItem>> columns = new ArrayList<TableColumnInfo<InventoryItem>>();
columns.add(new TableColumnInfo<InventoryItem>("Qty", 30, PresetColumns.FN_QTY_COMPARE, PresetColumns.FN_QTY_GET));
columns.add(new TableColumnInfo<InventoryItem>("Name", 175, PresetColumns.FN_NAME_COMPARE, PresetColumns.FN_NAME_GET));
columns.add(new TableColumnInfo<InventoryItem>("Cost", 75, PresetColumns.FN_COST_COMPARE, PresetColumns.FN_COST_GET));
columns.add(new TableColumnInfo<InventoryItem>("Color", 60, PresetColumns.FN_COLOR_COMPARE, PresetColumns.FN_COLOR_GET));
columns.add(new TableColumnInfo<InventoryItem>("Type", 100, PresetColumns.FN_TYPE_COMPARE, PresetColumns.FN_TYPE_GET));
columns.add(new TableColumnInfo<InventoryItem>("Stats", 60, PresetColumns.FN_STATS_COMPARE, PresetColumns.FN_STATS_GET));
columns.add(new TableColumnInfo<InventoryItem>("R", 25, PresetColumns.FN_RARITY_COMPARE, PresetColumns.FN_RARITY_GET));
columns.add(new TableColumnInfo<InventoryItem>("Set", 40, PresetColumns.FN_SET_COMPARE, PresetColumns.FN_SET_GET));
columns.add(new TableColumnInfo<InventoryItem>("AI", 30, PresetColumns.FN_AI_STATUS_COMPARE, PresetColumns.FN_AI_STATUS_GET));
columns.add(new TableColumnInfo<InventoryItem>("Qty", 30, PresetColumns.FN_QTY_COMPARE,
PresetColumns.FN_QTY_GET));
columns.add(new TableColumnInfo<InventoryItem>("Name", 175, PresetColumns.FN_NAME_COMPARE,
PresetColumns.FN_NAME_GET));
columns.add(new TableColumnInfo<InventoryItem>("Cost", 75, PresetColumns.FN_COST_COMPARE,
PresetColumns.FN_COST_GET));
columns.add(new TableColumnInfo<InventoryItem>("Color", 60, PresetColumns.FN_COLOR_COMPARE,
PresetColumns.FN_COLOR_GET));
columns.add(new TableColumnInfo<InventoryItem>("Type", 100, PresetColumns.FN_TYPE_COMPARE,
PresetColumns.FN_TYPE_GET));
columns.add(new TableColumnInfo<InventoryItem>("Stats", 60, PresetColumns.FN_STATS_COMPARE,
PresetColumns.FN_STATS_GET));
columns.add(new TableColumnInfo<InventoryItem>("R", 25, PresetColumns.FN_RARITY_COMPARE,
PresetColumns.FN_RARITY_GET));
columns.add(new TableColumnInfo<InventoryItem>("Set", 40, PresetColumns.FN_SET_COMPARE,
PresetColumns.FN_SET_GET));
columns.add(new TableColumnInfo<InventoryItem>("AI", 30, PresetColumns.FN_AI_STATUS_COMPARE,
PresetColumns.FN_AI_STATUS_GET));
columns.get(2).setCellRenderer(new ManaCostRenderer());
this.getTopTableWithCards().setup(columns, this.getCardView());
@@ -135,11 +145,10 @@ public final class DeckEditorLimited extends DeckEditorBase<CardPrinted, DeckGro
/**
* Instantiates a new deck editor common.
*
* @param gameType
* the game type
*
* @param deckMap the deck map
*/
public DeckEditorLimited(IFolderMap<DeckGroup> deckMap) {
public DeckEditorLimited(final IFolderMap<DeckGroup> deckMap) {
try {
this.setFilterBoxes(new FilterCheckBoxes(true));
this.setTopTableWithCards(new TableView<CardPrinted>("Avaliable Cards", true, true, CardPrinted.class));
@@ -152,8 +161,13 @@ public final class DeckEditorLimited extends DeckEditorBase<CardPrinted, DeckGro
ErrorViewer.showError(ex);
}
Lambda0<DeckGroup> newCreator = new Lambda0<DeckGroup>() { @Override public DeckGroup apply() { return new DeckGroup(""); } };
controller = new DeckController<DeckGroup>(deckMap, this, newCreator);
final Lambda0<DeckGroup> newCreator = new Lambda0<DeckGroup>() {
@Override
public DeckGroup apply() {
return new DeckGroup("");
}
};
this.controller = new DeckController<DeckGroup>(deckMap, this, newCreator);
}
private void jbInit() {
@@ -197,7 +211,7 @@ public final class DeckEditorLimited extends DeckEditorBase<CardPrinted, DeckGro
// Type filtering
final Font f = new Font("Tahoma", Font.PLAIN, 10);
for (final JCheckBox box : this.getFilterBoxes().getAllTypes()) {
box.setFont(f);
box.setFont(f);
box.setOpaque(false);
}
@@ -333,20 +347,22 @@ public final class DeckEditorLimited extends DeckEditorBase<CardPrinted, DeckGro
this.getBottomTableWithCards().addCard(card);
this.getTopTableWithCards().removeCard(card);
/* update model
Deck model = getSelectedDeck(getController().getModel());
model.getMain().add(card);
model.getSideboard().remove(card); */
/*
* update model Deck model =
* getSelectedDeck(getController().getModel());
* model.getMain().add(card); model.getSideboard().remove(card);
*/
this.getController().notifyModelChanged();
}
/**
* TODO: Write javadoc for this method.
*
* @param model
* @return
*/
private Deck getSelectedDeck(DeckGroup model) {
private Deck getSelectedDeck(final DeckGroup model) {
return model.getHumanDeck();
}
@@ -367,31 +383,34 @@ public final class DeckEditorLimited extends DeckEditorBase<CardPrinted, DeckGro
this.getBottomTableWithCards().removeCard(card);
this.getTopTableWithCards().addCard(card);
/* update model
Deck model = getSelectedDeck(getController().getModel());
model.getMain().remove(card);
model.getSideboard().add(card);*/
/*
* update model Deck model =
* getSelectedDeck(getController().getModel());
* model.getMain().remove(card); model.getSideboard().add(card);
*/
this.getController().notifyModelChanged();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#getController()
*/
@Override
public IDeckController<DeckGroup> getController() {
return controller;
return this.controller;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#updateView()
*/
@Override
public void updateView() {
getTopTableWithCards().setDeck(getSelectedDeck(controller.getModel()).getSideboard());
getBottomTableWithCards().setDeck(getSelectedDeck(controller.getModel()).getMain());
this.getTopTableWithCards().setDeck(this.getSelectedDeck(this.controller.getModel()).getSideboard());
this.getBottomTableWithCards().setDeck(this.getSelectedDeck(this.controller.getModel()).getMain());
}
}

View File

@@ -27,6 +27,7 @@ import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
@@ -82,6 +83,7 @@ public final class DeckEditorQuest extends DeckEditorBase<CardPrinted, Deck> {
* @param exitCommand
* the exit command
*/
@Override
public void show(final Command exitCommand) {
final Command exit = new Command() {
private static final long serialVersionUID = -7428793574300520612L;
@@ -101,10 +103,13 @@ public final class DeckEditorQuest extends DeckEditorBase<CardPrinted, Deck> {
// do not change this!!!!
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent ev) { menu.close(); }
public void windowClosing(final WindowEvent ev) {
menu.close();
}
});
Deck deck = Constant.Runtime.HUMAN_DECK[0] == null ? null : this.questData.getMyDecks().get(Constant.Runtime.HUMAN_DECK[0].getName());
Deck deck = Constant.Runtime.HUMAN_DECK[0] == null ? null : this.questData.getMyDecks().get(
Constant.Runtime.HUMAN_DECK[0].getName());
if (deck == null) {
deck = new Deck();
@@ -112,7 +117,6 @@ public final class DeckEditorQuest extends DeckEditorBase<CardPrinted, Deck> {
// tell Gui_Quest_DeckEditor the name of the deck
this.getController().setModel(deck);
// this affects the card pool
@@ -156,7 +160,8 @@ public final class DeckEditorQuest extends DeckEditorBase<CardPrinted, Deck> {
this.filterNameTypeSet.setListeners(new OnChangeTextUpdateDisplay(), this.getItemListenerUpdatesDisplay());
// Window is too tall, lower height to min size used by constructed mode deck editor
// Window is too tall, lower height to min size used by constructed mode
// deck editor
// this.setSize(1024, 768);
this.setSize(1024, 740);
GuiUtils.centerFrame(this);
@@ -188,8 +193,13 @@ public final class DeckEditorQuest extends DeckEditorBase<CardPrinted, Deck> {
ErrorViewer.showError(ex);
}
Lambda0<Deck> newCreator = new Lambda0<Deck>() { @Override public Deck apply() { return new Deck(); } };
controller = new DeckController<Deck>(questData2.getMyDecks(), this, newCreator);
final Lambda0<Deck> newCreator = new Lambda0<Deck>() {
@Override
public Deck apply() {
return new Deck();
}
};
this.controller = new DeckController<Deck>(questData2.getMyDecks(), this, newCreator);
}
private void jbInit() throws Exception {
@@ -255,7 +265,8 @@ public final class DeckEditorQuest extends DeckEditorBase<CardPrinted, Deck> {
/**
* Color filtering
*/
// Raise the color filtering boxes to top of window and move to the left.
// Raise the color filtering boxes to top of window and move to the
// left.
this.getFilterBoxes().getWhite().setBounds(17, 10, 67, 20);
this.getFilterBoxes().getBlue().setBounds(94, 10, 60, 20);
this.getFilterBoxes().getBlack().setBounds(162, 10, 65, 20);
@@ -350,28 +361,32 @@ public final class DeckEditorQuest extends DeckEditorBase<CardPrinted, Deck> {
this.questData.getCards().getCardpool().add(card);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#getController()
*/
@Override
public IDeckController<Deck> getController() {
return controller;
return this.controller;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#updateView()
*/
@Override
public void updateView() {
Deck deck = controller.getModel();
final Deck deck = this.controller.getModel();
final ItemPool<CardPrinted> cardpool = new ItemPool<CardPrinted>(CardPrinted.class);
cardpool.addAll(this.questData.getCards().getCardpool());
// remove bottom cards that are in the deck from the card pool
cardpool.removeAll(deck.getMain());
// show cards, makes this user friendly
getTopTableWithCards().setDeck(cardpool);
getBottomTableWithCards().setDeck(deck.getMain());
this.getTopTableWithCards().setDeck(cardpool);
this.getBottomTableWithCards().setDeck(deck.getMain());
}
}

View File

@@ -331,7 +331,10 @@ public class DraftingProcess extends DeckEditorBase<CardPrinted, DeckGroup> {
// DeckManager deckManager = new
// DeckManager(ForgeProps.getFile(NEW_DECKS));
Singletons.getModel().getDecks().getDraft().add(finishedDraft); // write file right here
Singletons.getModel().getDecks().getDraft().add(finishedDraft); // write
// file
// right
// here
// close and open next screen
this.dispose();
@@ -350,7 +353,9 @@ public class DraftingProcess extends DeckEditorBase<CardPrinted, DeckGroup> {
return Predicate.getTrue(CardPrinted.class);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#getController()
*/
@Override
@@ -358,18 +363,22 @@ public class DraftingProcess extends DeckEditorBase<CardPrinted, DeckGroup> {
return null;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#updateView()
*/
@Override
public void updateView() {
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#show(forge.Command)
*/
@Override
public void show(Command exitCommand) {
public void show(final Command exitCommand) {
this.setup();
this.showChoices(this.boosterDraft.nextChoice());
this.getBottomTableWithCards().setDeck((Iterable<InventoryItem>) null);

View File

@@ -1,54 +1,146 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.gui.deckeditor;
import java.awt.Component;
import java.util.List;
/**
/**
* TODO: Write javadoc for this type.
*
* @param <T> the generic type
*/
public interface IDeckController<T> {
/**
* New model.
*/
void newModel();
/**
* Sets the model.
*
* @param model the new model
*/
void setModel(T model);
/**
* Gets the model.
*
* @return the model
*/
T getModel();
/** Call this anytime model becomes different from the saved on disk state.*/
/** Call this anytime model becomes different from the saved on disk state. */
void notifyModelChanged();
/**
* Gets the owner window.
*
* @return the owner window
*/
Component getOwnerWindow();
/**
* Gets the view.
*
* @return the view
*/
DeckEditorBase<?, T> getView();
/** Gets names of saved models in folder / questData. */
/**
* Gets names of saved models in folder / questData.
*
* @return the saved names
*/
List<String> getSavedNames();
/**
* Load.
*
* @param name the name
*/
void load(String name);
/**
* Save.
*/
void save();
/**
* Save as.
*
* @param name0 the name0
*/
void saveAs(String name0);
/**
* Checks if is saved.
*
* @return true, if is saved
*/
boolean isSaved();
/**
* Delete.
*/
void delete();
/** Returns true if no object exists with that name. */
/**
* Returns true if no object exists with that name.
*
* @param deckName the deck name
* @return true, if is good name
*/
boolean isGoodName(String deckName);
/** Import in quest adds add cards to pool, unlike constructed. */
/**
* Import in quest adds add cards to pool, unlike constructed.
*
* @param newDeck the new deck
*/
void importDeck(T newDeck);
/** Tells if this deck was already saved to disk / questData. */
/**
* Tells if this deck was already saved to disk / questData.
*
* @return true, if is model in store
*/
boolean isModelInStore();
/**
* TODO: Write javadoc for this method.
* @param deckName
* @return
*
* @param deckName the deck name
* @return true, if successful
*/
boolean fileExists(String deckName);
/*
// IMPORT DECK CODE
this.questData.addDeck(newDeck);
final ItemPool<CardPrinted> cardpool = ItemPool.createFrom(this.questData.getCards().getCardpool(),
CardPrinted.class);
final ItemPool<CardPrinted> decklist = new ItemPool<CardPrinted>(CardPrinted.class);
for (final Entry<CardPrinted, Integer> s : newDeck.getMain()) {
final CardPrinted cp = s.getKey();
decklist.add(cp, s.getValue());
cardpool.add(cp, s.getValue());
this.questData.getCards().getCardpool().add(cp, s.getValue());
}
this.controller.showItems(cardpool, decklist);
* // IMPORT DECK CODE this.questData.addDeck(newDeck);
*
* final ItemPool<CardPrinted> cardpool =
* ItemPool.createFrom(this.questData.getCards().getCardpool(),
* CardPrinted.class); final ItemPool<CardPrinted> decklist = new
* ItemPool<CardPrinted>(CardPrinted.class); for (final Entry<CardPrinted,
* Integer> s : newDeck.getMain()) { final CardPrinted cp = s.getKey();
* decklist.add(cp, s.getValue()); cardpool.add(cp, s.getValue());
* this.questData.getCards().getCardpool().add(cp, s.getValue()); }
* this.controller.showItems(cardpool, decklist);
*/
}

View File

@@ -38,7 +38,8 @@ import forge.gui.GuiUtils;
* <p>
* Gui_DeckEditor_Menu class.
* </p>
*
*
* @param <T> the generic type
* @author Forge
* @version $Id: DeckEditorCommonMenu.java 13590 2012-01-27 20:46:27Z Max mtg $
*/
@@ -49,15 +50,10 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
private final IDeckController<T> controller;
/**
*
* Menu for Deck Editor.
*
* @param inDisplay
* a DeckDisplay
* @param dckManager
* a DeckManager
* @param exit
* a Command
*
* @param ctrl the ctrl
* @param exit a Command
*/
public MenuBase(final IDeckController<T> ctrl, final Command exit) {
this.controller = ctrl;
@@ -66,13 +62,21 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
this.setupMenu();
}
/**
* Gets the controller.
*
* @return the controller
*/
protected final IDeckController<T> getController() {
return controller;
return this.controller;
}
/**
* Setup menu.
*/
protected void setupMenu() {
this.add(getDefaultFileMenu());
this.add(getSortMenu());
this.add(this.getDefaultFileMenu());
this.add(this.getSortMenu());
}
/**
@@ -89,6 +93,11 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
this.controller.newModel();
}
/**
* Gets the user input open deck.
*
* @return the user input open deck
*/
protected final String getUserInputOpenDeck() {
final List<String> choices = this.controller.getSavedNames();
if (choices.isEmpty()) {
@@ -102,15 +111,25 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
// deck.setName(currentDeckName);
/**
* Open.
*/
protected final void open() {
if (!this.canLeaveCurrentDeck()) { return; }
if (!this.canLeaveCurrentDeck()) {
return;
}
final String name = this.getUserInputOpenDeck();
if (StringUtils.isBlank(name)) { return; }
controller.load(name);
if (StringUtils.isBlank(name)) {
return;
}
this.controller.load(name);
}
/**
* Save.
*/
protected final void save() {
if (StringUtils.isBlank(controller.getModel().getName())) {
if (StringUtils.isBlank(this.controller.getModel().getName())) {
this.saveAs();
return;
}
@@ -118,19 +137,24 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
this.controller.save();
}
/**
* Save as.
*/
protected final void saveAs() {
final String name = this.getDeckNameFromDialog();
if (StringUtils.isBlank(name)) {
final int n = JOptionPane.showConfirmDialog(null, "This name is incorrect. Enter another one?", "Cannot save", JOptionPane.YES_NO_OPTION);
final int n = JOptionPane.showConfirmDialog(null, "This name is incorrect. Enter another one?",
"Cannot save", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.NO_OPTION) {
return;
}
}
if (controller.fileExists(name)) {
final int m = JOptionPane.showConfirmDialog(null, "There is already saved an item named '" + name + "'. Would you like to overwrite it?", "Confirm overwrite", JOptionPane.YES_NO_OPTION);
if (this.controller.fileExists(name)) {
final int m = JOptionPane.showConfirmDialog(null, "There is already saved an item named '" + name
+ "'. Would you like to overwrite it?", "Confirm overwrite", JOptionPane.YES_NO_OPTION);
if (m == JOptionPane.NO_OPTION) {
return;
@@ -140,13 +164,16 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
this.controller.saveAs(name);
}
/**
* Delete.
*/
protected final void delete() {
if (!controller.isModelInStore()) {
if (!this.controller.isModelInStore()) {
return;
}
final int n = JOptionPane.showConfirmDialog(null, "Do you want to delete this deck " + controller.getModel().getName()
+ " ?", "Delete", JOptionPane.YES_NO_OPTION);
final int n = JOptionPane.showConfirmDialog(null, "Do you want to delete this deck "
+ this.controller.getModel().getName() + " ?", "Delete", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.NO_OPTION) {
return;
@@ -166,8 +193,13 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
this.exitCommand.execute();
}
/**
* Can leave current deck.
*
* @return true, if successful
*/
protected final boolean canLeaveCurrentDeck() {
if (controller.isSaved()) {
if (this.controller.isSaved()) {
return true;
}
final String message = String.format("Do you wish to save changes you made to your current deck '%s'?",
@@ -182,12 +214,10 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
return true;
}
save();
this.save();
return true;
}
/**
* <p>
* getUserInput_GetDeckName.
@@ -203,7 +233,7 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
}
final String deckName = o.toString();
final boolean isGoodName = controller.isGoodName(deckName);
final boolean isGoodName = this.controller.isGoodName(deckName);
if (isGoodName) {
return deckName;
@@ -213,6 +243,11 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
return this.getDeckNameFromDialog();
}
/**
* Gets the default file menu.
*
* @return the default file menu
*/
protected JMenu getDefaultFileMenu() {
final JMenu fileMenu = new JMenu("Deck");
@@ -317,7 +352,12 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
return fileMenu;
}
protected void appendCloseMenuItemTo(JMenu fileMenu) {
/**
* Append close menu item to.
*
* @param fileMenu the file menu
*/
protected void appendCloseMenuItemTo(final JMenu fileMenu) {
final JMenuItem close = new JMenuItem("Close");
fileMenu.addSeparator();
fileMenu.add(close);
@@ -344,6 +384,8 @@ public class MenuBase<T extends DeckBase> extends JMenuBar {
* <p>
* setupSortMenu.
* </p>
*
* @return the sort menu
*/
protected final JMenuItem getSortMenu() {
final JMenuItem name = new JMenuItem("Card Name");

View File

@@ -50,15 +50,10 @@ public final class MenuCommon extends MenuBase<Deck> {
private static File previousDirectory = null;
/**
*
* Menu for Deck Editor.
*
* @param inDisplay
* a DeckDisplay
* @param dckManager
* a DeckManager
* @param exit
* a Command
*
* @param ctrl the ctrl
* @param exit a Command
*/
public MenuCommon(final IDeckController<Deck> ctrl, final Command exit) {
super(ctrl, exit);
@@ -73,7 +68,7 @@ public final class MenuCommon extends MenuBase<Deck> {
return;
}
Deck randomDeck = new Deck();
final Deck randomDeck = new Deck();
// The only remaining reference to global variable!
final CardList random = new CardList(forge.AllZone.getCardFactory().getRandomCombinationWithoutRepetition(
@@ -87,7 +82,7 @@ public final class MenuCommon extends MenuBase<Deck> {
randomDeck.getMain().add("Forest");
randomDeck.getMain().add("Terramorphic Expanse");
getController().setModel(randomDeck);
this.getController().setModel(randomDeck);
}
private final void newGenerateConstructed() {
@@ -95,9 +90,9 @@ public final class MenuCommon extends MenuBase<Deck> {
return;
}
Deck genConstructed = new Deck();
final Deck genConstructed = new Deck();
genConstructed.getMain().add((new Generate2ColorDeck("AI", "AI")).get2ColorDeck(60, PlayerType.HUMAN));
getController().setModel(genConstructed);
this.getController().setModel(genConstructed);
}
private File getImportFilename() {
@@ -119,7 +114,7 @@ public final class MenuCommon extends MenuBase<Deck> {
if (file == null) {
} else if (file.getName().endsWith(".dck")) {
try {
getController().setModel(Deck.fromFile(file));
this.getController().setModel(Deck.fromFile(file));
} catch (final Exception ex) {
ErrorViewer.showError(ex);
@@ -141,7 +136,7 @@ public final class MenuCommon extends MenuBase<Deck> {
}
try {
DeckSerializer.writeDeck(getController().getModel(), filename);
DeckSerializer.writeDeck(this.getController().getModel(), filename);
} catch (final Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("Gui_DeckEditor_Menu : exportDeck() error, " + ex);
@@ -177,7 +172,7 @@ public final class MenuCommon extends MenuBase<Deck> {
}
try {
DeckSerializer.writeDeckHtml(getController().getModel(), filename);
DeckSerializer.writeDeckHtml(this.getController().getModel(), filename);
} catch (final Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("Gui_DeckEditor_Menu : printProxies() error, " + ex);
@@ -203,6 +198,10 @@ public final class MenuCommon extends MenuBase<Deck> {
// deck.setName(currentDeckName);
/* (non-Javadoc)
* @see forge.gui.deckeditor.MenuBase#getDefaultFileMenu()
*/
@Override
protected JMenu getDefaultFileMenu() {
final JMenu fileMenu = super.getDefaultFileMenu();
@@ -213,12 +212,9 @@ public final class MenuCommon extends MenuBase<Deck> {
final JMenuItem exportDeck = new JMenuItem("Export Deck...");
// JMenuItem downloadDeck = new JMenuItem("Download Deck");
// newDraftItem = newDraft;
// newDraftItem.setEnabled(false);
// fileMenu.add(newSealed);
// fileMenu.add(newDraft);
fileMenu.addSeparator();
@@ -229,14 +225,13 @@ public final class MenuCommon extends MenuBase<Deck> {
final JMenuItem generateProxies = new JMenuItem("Generate Proxies...");
fileMenu.add(generateProxies);
// fileMenu.add(downloadDeck);
fileMenu.addSeparator();
fileMenu.add(newRandomConstructed);
fileMenu.add(newGenerateConstructed);
appendCloseMenuItemTo(fileMenu);
this.appendCloseMenuItemTo(fileMenu);
generateProxies.addActionListener(new ActionListener() {
@Override

View File

@@ -34,15 +34,10 @@ public final class MenuLimited extends MenuBase<DeckGroup> {
private static final long serialVersionUID = -4037993759604768755L;
/**
*
* Menu for Deck Editor.
*
* @param inDisplay
* a DeckDisplay
* @param dckManager
* a DeckManager
* @param exit
* a Command
*
* @param ctrl the ctrl
* @param exit a Command
*/
public MenuLimited(final IDeckController<DeckGroup> ctrl, final Command exit) {
super(ctrl, exit);

View File

@@ -50,21 +50,17 @@ public class MenuQuest extends MenuBase<Deck> {
/** Constant <code>serialVersionUID=-4052319220021158574L</code>. */
private static final long serialVersionUID = -4052319220021158574L;
// used for import and export, try to made the gui user friendly
/** Constant <code>previousDirectory</code>. */
private static File previousDirectory = null;
/**
* <p>
* Constructor for Gui_Quest_DeckEditor_Menu.
* </p>
*
* @param q
* the q
* @param d
* a {@link forge.gui.deckeditor.IDeckDisplay} object.
* @param exit
* a {@link forge.Command} object.
*
* @param d a {@link forge.gui.deckeditor.IDeckDisplay} object.
* @param exit a {@link forge.Command} object.
*/
public MenuQuest(final IDeckController<Deck> d, final Command exit) {
@@ -73,7 +69,6 @@ public class MenuQuest extends MenuBase<Deck> {
this.setupMenu();
}
/**
* <p>
* importDeck.
@@ -82,10 +77,10 @@ public class MenuQuest extends MenuBase<Deck> {
private final void importDeck() {
final File file = this.getImportFilename();
if (file != null && file.getName().endsWith(".dck")) {
if ((file != null) && file.getName().endsWith(".dck")) {
try {
final Deck newDeck = Deck.fromFile(file);
getController().importDeck(newDeck);
this.getController().importDeck(newDeck);
} catch (final Exception ex) {
ErrorViewer.showError(ex);
@@ -133,11 +128,16 @@ public class MenuQuest extends MenuBase<Deck> {
// use standard forge's list selection dialog
final ListChooser<String> c = new ListChooser<String>("Cheat - Add Card to Your Cardpool", 0, 1, cards);
if (c.show()) {
((DeckEditorQuest) getController().getView()).addCheatCard(CardDb.instance().getCard(c.getSelectedValue()));
((DeckEditorQuest) MenuQuest.this.getController().getView()).addCheatCard(CardDb.instance().getCard(
c.getSelectedValue()));
}
}
};
/* (non-Javadoc)
* @see forge.gui.deckeditor.MenuBase#getDefaultFileMenu()
*/
@Override
protected JMenu getDefaultFileMenu() {
final JMenu deckMenu = super.getDefaultFileMenu();
@@ -145,7 +145,6 @@ public class MenuQuest extends MenuBase<Deck> {
addCard.addActionListener(this.addCardActionListener);
if (Constant.Runtime.DEV_MODE[0]) {
deckMenu.addSeparator();
deckMenu.add(addCard);
@@ -154,8 +153,8 @@ public class MenuQuest extends MenuBase<Deck> {
deckMenu.addSeparator();
this.addImportExport(deckMenu, true);
appendCloseMenuItemTo(deckMenu);
return deckMenu;
this.appendCloseMenuItemTo(deckMenu);
return deckMenu;
}
@@ -199,7 +198,7 @@ public class MenuQuest extends MenuBase<Deck> {
}
try {
DeckSerializer.writeDeck(getController().getModel(), filename);
DeckSerializer.writeDeck(this.getController().getModel(), filename);
} catch (final Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("Gui_DeckEditor_Menu : exportDeck() error, " + ex);
@@ -207,7 +206,7 @@ public class MenuQuest extends MenuBase<Deck> {
}
private final File getExportFilename() {
final JFileChooser save = new JFileChooser(previousDirectory);
final JFileChooser save = new JFileChooser(MenuQuest.previousDirectory);
save.setDialogTitle("Export Deck Filename");
save.setDialogType(JFileChooser.SAVE_DIALOG);
save.setFileFilter(DeckSerializer.DCK_FILTER);
@@ -216,7 +215,7 @@ public class MenuQuest extends MenuBase<Deck> {
final File file = save.getSelectedFile();
final String check = file.getAbsolutePath();
previousDirectory = file.getParentFile();
MenuQuest.previousDirectory = file.getParentFile();
return check.endsWith(".dck") ? file : new File(check + ".dck");
}

View File

@@ -23,9 +23,9 @@ import java.util.regex.Pattern;
import net.slightlymagic.braids.util.lambda.Lambda1;
import forge.Singletons;
import forge.card.CardColor;
import forge.card.CardEdition;
import forge.card.CardManaCost;
import forge.card.CardRarity;
import forge.card.CardEdition;
import forge.item.CardPrinted;
import forge.item.InventoryItem;
import forge.item.InventoryItemFromSet;
@@ -55,8 +55,8 @@ public abstract class PresetColumns {
}
private static CardEdition toSetCmp(final InventoryItem i) {
return i instanceof InventoryItemFromSet ? Singletons.getModel().getEditions().getEditionByCode(((InventoryItemFromSet) i).getEdition())
: CardEdition.UNKNOWN;
return i instanceof InventoryItemFromSet ? Singletons.getModel().getEditions()
.getEditionByCode(((InventoryItemFromSet) i).getEdition()) : CardEdition.UNKNOWN;
}
private static String toSetStr(final InventoryItem i) {
@@ -101,8 +101,8 @@ public abstract class PresetColumns {
public static final Lambda1<Object, Entry<InventoryItem, Integer>> FN_NAME_GET = new Lambda1<Object, Entry<InventoryItem, Integer>>() {
@Override
public Object apply(final Entry<InventoryItem, Integer> from) {
String name = from.getKey().getName();
return name.contains("AE") ? AE_FINDER.matcher(name).replaceAll("\u00C6") : name;
final String name = from.getKey().getName();
return name.contains("AE") ? PresetColumns.AE_FINDER.matcher(name).replaceAll("\u00C6") : name;
}
};

View File

@@ -70,7 +70,8 @@ public final class QuestCardShop extends DeckEditorBase<InventoryItem, Object> {
private final JButton sellButton = new JButton();
private final JLabel creditsLabel = new JLabel();
// We will remove the label below as the other deck editors do not display this text.
// We will remove the label below as the other deck editors do not display
// this text.
// private final JLabel jLabel1 = new JLabel();
private final JLabel sellPercentageLabel = new JLabel();
@@ -89,6 +90,7 @@ public final class QuestCardShop extends DeckEditorBase<InventoryItem, Object> {
* @param exitCommand
* the exit command
*/
@Override
public void show(final Command exitCommand) {
final Command exit = new Command() {
private static final long serialVersionUID = -7428793574300520612L;
@@ -123,8 +125,8 @@ public final class QuestCardShop extends DeckEditorBase<InventoryItem, Object> {
final ItemPool<InventoryItem> ownedItems = new ItemPool<InventoryItem>(InventoryItem.class);
ownedItems.addAll(this.questData.getCards().getCardpool().getView());
getTopTableModel().setDeck(forSale);
getBottomTableWithCards().setDeck(ownedItems);
this.getTopTableModel().setDeck(forSale);
this.getBottomTableWithCards().setDeck(ownedItems);
final double multiPercent = this.multiplier * 100;
final NumberFormat formatter = new DecimalFormat("#0.00");
@@ -189,7 +191,8 @@ public final class QuestCardShop extends DeckEditorBase<InventoryItem, Object> {
columnsBelow.add(new TableColumnInfo<InventoryItem>("Price", 45, this.fnPriceCompare, this.fnPriceSellGet));
this.getBottomTableWithCards().setup(columnsBelow, this.getCardView());
// Window is too tall, lower height to min size used by constructed mode deck editor.
// Window is too tall, lower height to min size used by constructed mode
// deck editor.
// this.setSize(1024, 768);
this.setSize(1024, 740);
GuiUtils.centerFrame(this);
@@ -263,7 +266,8 @@ public final class QuestCardShop extends DeckEditorBase<InventoryItem, Object> {
this.sellPercentageLabel.setBounds(new Rectangle(380, 395, 450, 31));
this.sellPercentageLabel.setText("(Sell percentage: " + this.multiplier + ")");
this.sellPercentageLabel.setFont(new java.awt.Font("Dialog", 0, 13));
// We will remove the label below as the other deck editors do not display this text.
// We will remove the label below as the other deck editors do not
// display this text.
// this.jLabel1.setText("Click on the column name (like name or color) to sort the cards");
// this.jLabel1.setBounds(new Rectangle(20, 1, 400, 19));
@@ -274,7 +278,8 @@ public final class QuestCardShop extends DeckEditorBase<InventoryItem, Object> {
this.getContentPane().add(this.buyButton, null);
this.getContentPane().add(this.sellButton, null);
this.getContentPane().add(this.sellPercentageLabel, null);
// We will remove the label below as the other deck editors do not display this text.
// We will remove the label below as the other deck editors do not
// display this text.
// this.getContentPane().add(this.jLabel1, null);
}
@@ -342,11 +347,12 @@ public final class QuestCardShop extends DeckEditorBase<InventoryItem, Object> {
for (final CardPrinted card : deck.getDeck().getMain().toFlatList()) {
this.getBottomTableWithCards().addCard(card);
}
JOptionPane.showMessageDialog(null, String.format("Deck '%s' was added to your decklist.%n%nCards from it were also added to your pool.", deck.getName()), "Thanks for purchasing!", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, String.format(
"Deck '%s' was added to your decklist.%n%nCards from it were also added to your pool.",
deck.getName()), "Thanks for purchasing!", JOptionPane.INFORMATION_MESSAGE);
}
this.creditsLabel.setText("Total credits: " + this.questData.getCredits());
} else {
JOptionPane.showMessageDialog(null, "Not enough credits!");
@@ -416,7 +422,9 @@ public final class QuestCardShop extends DeckEditorBase<InventoryItem, Object> {
}
};
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#getController()
*/
@Override
@@ -424,7 +432,9 @@ public final class QuestCardShop extends DeckEditorBase<InventoryItem, Object> {
return null;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.gui.deckeditor.DeckEditorBase#updateView()
*/
@Override

View File

@@ -62,7 +62,8 @@ import forge.view.toolbox.FSkin;
* this class must be either private or public static final.
*/
public enum FModel {
/** */
/** The SINGLETO n_ instance. */
SINGLETON_INSTANCE;
// private static final int NUM_INIT_PHASES = 1;
@@ -77,12 +78,12 @@ public enum FModel {
private final QuestEventManager questEventManager;
private final GameState gameState;
private final FMatchState matchState;
private final EditionUtils setUtils;
private final FormatUtils formats;
// have to implement lazy initialization - at the moment of FModel.ctor() CardDb is not ready yet.
// have to implement lazy initialization - at the moment of FModel.ctor()
// CardDb is not ready yet.
private CardCollections decks;
/**
@@ -102,7 +103,7 @@ public enum FModel {
try {
this.logFileStream = new FileOutputStream(logFile);
} catch (FileNotFoundException e) {
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
@@ -155,7 +156,6 @@ public enum FModel {
FModel.loadDynamicGamedata();
}
/**
* Load dynamic gamedata.
*/
@@ -275,7 +275,7 @@ public enum FModel {
/**
* Gets the builds the info.
*
*
* @return {@link forge.model.BuildInfo}
*/
public final BuildInfo getBuildInfo() {
@@ -284,8 +284,9 @@ public enum FModel {
/**
* Sets the builds the info.
*
* @param bi0 &emsp; {@link forge.model.BuildInfo}
*
* @param bi0
* &emsp; {@link forge.model.BuildInfo}
*/
protected final void setBuildInfo(final BuildInfo bi0) {
this.buildInfo = bi0;
@@ -293,7 +294,7 @@ public enum FModel {
/**
* Gets the preferences.
*
*
* @return {@link forge.properties.ForgePreferences}
*/
public final ForgePreferences getPreferences() {
@@ -302,7 +303,7 @@ public enum FModel {
/**
* Gets the quest preferences.
*
*
* @return {@link forge.quest.data.QuestPreferences}
*/
public final QuestPreferences getQuestPreferences() {
@@ -311,7 +312,7 @@ public enum FModel {
/**
* Gets the quest preferences.
*
*
* @return {@link forge.quest.data.QuestEventManager}
*/
public final QuestEventManager getQuestEventManager() {
@@ -320,18 +321,19 @@ public enum FModel {
/**
* Returns all player's decks for constructed, sealed and whatever.
*
* @return {@link forge.decks.CardCollections}
*/
public final CardCollections getDecks() {
if (decks == null) {
if (this.decks == null) {
this.decks = new CardCollections(ForgeProps.getFile(NewConstants.NEW_DECKS));
}
return decks;
return this.decks;
}
/**
* Gets the game action model.
*
*
* @return {@link forge.GameAction}
*/
public final GameAction getGameAction() {
@@ -340,7 +342,7 @@ public enum FModel {
/**
* Gets the game state model - that is, the data stored for a single game.
*
*
* @return {@link forge.game.GameState}
*/
public final GameState getGameState() {
@@ -348,8 +350,9 @@ public enum FModel {
}
/**
* Gets the match state model - that is, the data stored over multiple games.
*
* Gets the match state model - that is, the data stored over multiple
* games.
*
* @return {@link forge.model.FMatchState}
*/
public final FMatchState getMatchState() {
@@ -358,7 +361,7 @@ public enum FModel {
/**
* Gets the game summary.
*
*
* @return {@link forge.game.GameSummary}
*/
public final GameSummary getGameSummary() {
@@ -367,23 +370,27 @@ public enum FModel {
/**
* TODO: Write javadoc for this method.
* @return
*
* @return the editions
*/
public final EditionUtils getEditions() {
return setUtils;
return this.setUtils;
}
/**
* Gets the formats.
*
* @return the formats
*/
public final FormatUtils getFormats() {
return formats;
return this.formats;
}
/**
* TODO: Needs to be reworked for efficiency with rest of prefs saves in
* codebase.
*
*
* @return true, if successful
*/
public final boolean savePrefs() {
@@ -436,7 +443,7 @@ public enum FModel {
/**
* TODO: Needs to be reworked for efficiency with rest of prefs loads in
* codebase.
*
*
* @return true, if successful
*/
public final boolean loadPrefs() {
@@ -483,9 +490,8 @@ public enum FModel {
}
/**
* Finalizer, generally should be avoided, but here
* closes the log file stream and
* resets the system output streams.
* Finalizer, generally should be avoided, but here closes the log file
* stream and resets the system output streams.
*/
public final void close() {
System.setOut(this.oldSystemOut);

View File

@@ -1,34 +1,57 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.quest.data;
import java.io.File;
import java.io.FilenameFilter;
import forge.deck.io.DeckSerializer;
import forge.item.PreconDeck;
import forge.util.StorageReaderFolder;
/**
/**
* TODO: Write javadoc for this type.
*
*
*/
public class PreconReader extends StorageReaderFolder<PreconDeck> {
/**
* TODO: Write javadoc for Constructor.
* @param deckDir0
*
* @param deckDir0 the deck dir0
*/
public PreconReader(File deckDir0) {
public PreconReader(final File deckDir0) {
super(deckDir0);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.io.DeckSerializerBase#read(java.io.File)
*/
@Override
protected PreconDeck read(File file) {
protected PreconDeck read(final File file) {
return new PreconDeck(file);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.io.DeckSerializerBase#getFileFilter()
*/
@Override
@@ -36,9 +59,10 @@ public class PreconReader extends StorageReaderFolder<PreconDeck> {
return DeckSerializer.DCK_FILE_FILTER;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.util.IItemReader#readAll()
*/
}

View File

@@ -20,6 +20,7 @@ package forge.quest.data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.slightlymagic.maxmtg.Predicate;
import forge.Singletons;
import forge.deck.Deck;
@@ -121,7 +122,7 @@ public final class QuestData {
// Cards associated with quest
/** The card pool. */
private ItemPool<CardPrinted> cardPool = new ItemPool<CardPrinted>(CardPrinted.class); // player's
private final ItemPool<CardPrinted> cardPool = new ItemPool<CardPrinted>(CardPrinted.class); // player's
// belonging
/** The shop list. */
private ItemPool<InventoryItem> shopList = new ItemPool<InventoryItem>(InventoryItem.class); // the
@@ -168,7 +169,8 @@ public final class QuestData {
private transient QuestUtilCards myCards;
// This is used by shop. Had no idea where else to place this
private static transient IFolderMapView<PreconDeck> preconManager = new FolderMapView<PreconDeck>(new PreconReader(ForgeProps.getFile(NewConstants.Quest.PRECONS)));
private static transient IFolderMapView<PreconDeck> preconManager = new FolderMapView<PreconDeck>(new PreconReader(
ForgeProps.getFile(NewConstants.Quest.PRECONS)));
/** The Constant RANK_TITLES. */
public static final String[] RANK_TITLES = new String[] { "Level 0 - Confused Wizard", "Level 1 - Mana Mage",
@@ -182,7 +184,9 @@ public final class QuestData {
"What Do You Do With The Other Hand?", "Freelance Sorcerer, Works Weekends",
"Should We Hire Commentators?", "Saltblasted For Your Talent", "Serra Angel Is Your Girlfriend", };
/** */
/**
* Instantiates a new quest data.
*/
public QuestData() {
this("An Unknown Quest");
}
@@ -192,25 +196,25 @@ public final class QuestData {
* Constructor for QuestData.
* </p>
*
* @param s0 &emsp; String name
* @param s0
* &emsp; String name
*/
public QuestData(String s0) {
public QuestData(final String s0) {
this.initTransients();
this.setName(s0);
QuestPreferences prefs = Singletons.getModel().getQuestPreferences();
ItemPoolView<CardPrinted> lands = QuestUtilCards.generateBasicLands(prefs.getPreferenceInt(QPref.STARTING_BASIC_LANDS),
prefs.getPreferenceInt(QPref.STARTING_BASIC_LANDS));
final QuestPreferences prefs = Singletons.getModel().getQuestPreferences();
final ItemPoolView<CardPrinted> lands = QuestUtilCards.generateBasicLands(
prefs.getPreferenceInt(QPref.STARTING_BASIC_LANDS), prefs.getPreferenceInt(QPref.STARTING_BASIC_LANDS));
this.getCardPool().addAll(lands);
this.randomizeOpponents();
}
private void initTransients() {
// These are helper classes that hold no data.
this.decks = new QuestDeckMap(myDecks);
this.decks = new QuestDeckMap(this.myDecks);
this.myCards = new QuestUtilCards(this);
// to avoid NPE some pools will be created here if they are null
if (null == this.getNewCardList()) {
this.setNewCardList(new ItemPool<InventoryItem>(InventoryItem.class));
@@ -234,8 +238,8 @@ public final class QuestData {
public void newGame(final int diff, final String m0de, final boolean standardStart) {
this.setDifficulty(diff);
final Predicate<CardPrinted> filter = standardStart ? Singletons.getModel().getFormats().getStandard().getFilterPrinted()
: CardPrinted.Predicates.Presets.IS_TRUE;
final Predicate<CardPrinted> filter = standardStart ? Singletons.getModel().getFormats().getStandard()
.getFilterPrinted() : CardPrinted.Predicates.Presets.IS_TRUE;
this.myCards.setupNewGameCardPool(filter, diff);
this.setCredits(Singletons.getModel().getQuestPreferences().getPreferenceInt(QPref.STARTING_CREDITS, diff));
@@ -382,11 +386,11 @@ public final class QuestData {
public void addLost() {
this.lost++;
if (winstreakCurrent > winstreakBest) {
winstreakBest = winstreakCurrent;
if (this.winstreakCurrent > this.winstreakBest) {
this.winstreakBest = this.winstreakCurrent;
}
winstreakCurrent = 0;
this.winstreakCurrent = 0;
}
/**
@@ -405,11 +409,12 @@ public final class QuestData {
this.win++;
this.winstreakCurrent++;
if (winstreakCurrent > winstreakBest) {
winstreakBest = winstreakCurrent;
if (this.winstreakCurrent > this.winstreakBest) {
this.winstreakBest = this.winstreakCurrent;
}
final int winsToLvlUp = Singletons.getModel().getQuestPreferences().getPreferenceInt(QPref.WINS_RANKUP, this.diffIndex);
final int winsToLvlUp = Singletons.getModel().getQuestPreferences()
.getPreferenceInt(QPref.WINS_RANKUP, this.diffIndex);
if ((this.win % winsToLvlUp) == 0) {
this.rankIndex++;
}
@@ -427,7 +432,9 @@ public final class QuestData {
/**
* Adds n life to maximum.
* @param n &emsp; int
*
* @param n
* &emsp; int
*/
public void addLife(final int n) {
this.life += n;
@@ -435,7 +442,9 @@ public final class QuestData {
/**
* Removes n life from maximum.
* @param n &emsp; int
*
* @param n
* &emsp; int
*/
public void removeLife(final int n) {
this.life -= n;
@@ -542,17 +551,25 @@ public final class QuestData {
return QuestData.RANK_TITLES[this.rankIndex];
}
/** @return int */
/**
* Gets the win streak best.
*
* @return int
*/
public int getWinStreakBest() {
return this.winstreakBest;
}
/** @return int */
/**
* Gets the win streak current.
*
* @return int
*/
public int getWinStreakCurrent() {
return this.winstreakCurrent;
}
// decks management
// decks management
// randomizer - related
/**
@@ -600,7 +617,6 @@ public final class QuestData {
return this.cardPool;
}
/**
* Gets the shop list.
*
@@ -648,10 +664,13 @@ public final class QuestData {
return this.decks;
}
/** @return QuestPreconManager */
/**
* Gets the precons.
*
* @return QuestPreconManager
*/
public static IFolderMapView<PreconDeck> getPrecons() {
return preconManager;
return QuestData.preconManager;
}
/**
@@ -693,12 +712,20 @@ public final class QuestData {
this.versionNumber = versionNumber0;
}
/** @param s0 &emsp; {@link java.lang.String} */
public void setName(String s0) {
/**
* Sets the name.
*
* @param s0 &emsp; {@link java.lang.String}
*/
public void setName(final String s0) {
this.name = s0;
}
/** @return {@link java.lang.String} */
/**
* Gets the name.
*
* @return {@link java.lang.String}
*/
public String getName() {
return this.name;
}

View File

@@ -80,14 +80,14 @@ public class QuestDataIO {
* loadData.
* </p>
*
* @param xmlSaveFile &emsp; {@link java.io.File}
* @param xmlSaveFile
* &emsp; {@link java.io.File}
* @return {@link forge.quest.data.QuestData}
*/
public static QuestData loadData(final File xmlSaveFile) {
try {
QuestData data = null;
String name = xmlSaveFile.getName()
.substring(0, xmlSaveFile.getName().length() - 4);
final String name = xmlSaveFile.getName().substring(0, xmlSaveFile.getName().length() - 4);
if (!xmlSaveFile.exists()) {
return new QuestData(name);
@@ -200,18 +200,19 @@ public class QuestDataIO {
xStream.alias("CardPool", ItemPool.class);
xStream.alias("DeckSection", DeckSection.class);
final File f = new File(ForgeProps.getFile(NewConstants.Quest.DATA_DIR) + File.separator + qd.getName() + ".dat");
final File f = new File(ForgeProps.getFile(NewConstants.Quest.DATA_DIR) + File.separator + qd.getName()
+ ".dat");
final BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(f));
final GZIPOutputStream zout = new GZIPOutputStream(bout);
xStream.toXML(qd, zout);
zout.flush();
zout.close();
//BufferedOutputStream boutUnp = new BufferedOutputStream(new
//FileOutputStream(f + ".xml"));
//xStream.toXML(qd, boutUnp);
//boutUnp.flush();
//boutUnp.close();
// BufferedOutputStream boutUnp = new BufferedOutputStream(new
// FileOutputStream(f + ".xml"));
// xStream.toXML(qd, boutUnp);
// boutUnp.flush();
// boutUnp.close();
} catch (final Exception ex) {
ErrorViewer.showError(ex, "Error saving Quest Data.");
@@ -258,7 +259,12 @@ public class QuestDataIO {
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
final String value = reader.getValue();
return GameType.smartValueOf(value, GameType.Quest); // does not matter - this field is deprecated anyway
return GameType.smartValueOf(value, GameType.Quest); // does not
// matter -
// this field
// is
// deprecated
// anyway
}
}
@@ -332,7 +338,7 @@ public class QuestDataIO {
} else if ("booster".equals(nodename)) {
result.add(this.readBooster(reader), cnt);
} else if ("precon".equals(nodename)) {
PreconDeck toAdd = this.readPreconDeck(reader);
final PreconDeck toAdd = this.readPreconDeck(reader);
if (null != toAdd) {
result.add(toAdd, cnt);
}
@@ -344,7 +350,9 @@ public class QuestDataIO {
protected PreconDeck readPreconDeck(final HierarchicalStreamReader reader) {
String name = reader.getAttribute("name");
if (name == null) { name = reader.getAttribute("s"); }
if (name == null) {
name = reader.getAttribute("s");
}
return QuestData.getPrecons().get(name);
}
@@ -371,6 +379,7 @@ public class QuestDataIO {
public boolean canConvert(final Class clasz) {
return clasz.equals(DeckSection.class);
}
@Override
public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
for (final Entry<CardPrinted, Integer> e : (DeckSection) source) {

View File

@@ -1,3 +1,20 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.quest.data;
import java.util.Collection;
@@ -8,67 +25,88 @@ import java.util.Map;
import forge.deck.Deck;
import forge.util.IFolderMap;
/**
/**
* TODO: Write javadoc for this type.
*
*
*/
public class QuestDeckMap implements IFolderMap<Deck> {
/**
* Instantiates a new quest deck map.
*/
public QuestDeckMap() {
map = new HashMap<String, Deck>();
this.map = new HashMap<String, Deck>();
}
public QuestDeckMap(Map<String, Deck> inMap) {
map = inMap;
/**
* Instantiates a new quest deck map.
*
* @param inMap the in map
*/
public QuestDeckMap(final Map<String, Deck> inMap) {
this.map = inMap;
}
private final Map<String, Deck> map;
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.util.IFolderMapView#get(java.lang.String)
*/
@Override
public Deck get(String name) {
return map.get(name);
public Deck get(final String name) {
return this.map.get(name);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.util.IFolderMapView#getNames()
*/
@Override
public Collection<String> getNames() {
return map.keySet();
return this.map.keySet();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<Deck> iterator() {
return map.values().iterator();
return this.map.values().iterator();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.util.IFolderMap#add(forge.util.IHasName)
*/
@Override
public void add(Deck deck) {
map.put(deck.getName(), deck);
public void add(final Deck deck) {
this.map.put(deck.getName(), deck);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.util.IFolderMap#delete(java.lang.String)
*/
@Override
public void delete(String deckName) {
map.remove(deckName);
public void delete(final String deckName) {
this.map.remove(deckName);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.util.IFolderMap#isUnique(java.lang.String)
*/
@Override
public boolean isUnique(String name) {
return !map.containsKey(name);
public boolean isUnique(final String name) {
return !this.map.containsKey(name);
}
}

View File

@@ -41,7 +41,7 @@ public class QuestEvent {
/** The difficulty. */
private String difficulty = "Medium";
/** Filename of the icon for this event.*/
/** Filename of the icon for this event. */
private String iconFilename = "unknown";
/** The name. */
@@ -191,7 +191,7 @@ public class QuestEvent {
* Sets the icon filename.
*
* @param s0
* filename of the icon to set
* filename of the icon to set
*/
public void setIconFilename(final String s0) {
this.iconFilename = s0;

View File

@@ -82,14 +82,14 @@ public class QuestEventManager {
final File[] allFiles = ForgeProps.getFile(NewConstants.Quest.DECKS).listFiles(DeckSerializer.DCK_FILE_FILTER);
for (final File f : allFiles) {
Map<String, List<String>> contents = SectionUtil.parseSections(FileUtil.readFile(f));
final Map<String, List<String>> contents = SectionUtil.parseSections(FileUtil.readFile(f));
if (contents.containsKey("quest")) {
tempEvent = readChallenge(contents.get("quest"));
tempEvent = this.readChallenge(contents.get("quest"));
this.allChallenges.add((QuestChallenge) tempEvent);
} // End if([quest])
else {
tempEvent = readDuel(contents.get("metadata"));
tempEvent = this.readDuel(contents.get("metadata"));
this.allDuels.add((QuestDuel) tempEvent);
}
@@ -105,15 +105,22 @@ public class QuestEventManager {
/**
* Retrieve single event, using its name.
*
* @param s0 &emsp; {@link java.lang.String}
* @param s0
* &emsp; {@link java.lang.String}
* @return {@link forge.data.QuestEvent}
*/
public QuestEvent getEvent(final String s0) {
for (QuestEvent q : allDuels) {
if (q.getName().equals(s0)) { return q; } }
for (final QuestEvent q : this.allDuels) {
if (q.getName().equals(s0)) {
return q;
}
}
for (QuestChallenge q : allChallenges) {
if (q.getName().equals(s0)) { return q; } }
for (final QuestChallenge q : this.allChallenges) {
if (q.getName().equals(s0)) {
return q;
}
}
return null;
}
@@ -133,7 +140,7 @@ public class QuestEventManager {
String key, value;
for (final String s : contents) {
if (s.equals("")) {
if (s.equals("")) {
continue;
}
@@ -290,10 +297,10 @@ public class QuestEventManager {
*/
private void assembleDuelDifficultyLists() {
easyAIduels.clear();
mediumAIduels.clear();
hardAIduels.clear();
veryHardAIduels.clear();
this.easyAIduels.clear();
this.mediumAIduels.clear();
this.hardAIduels.clear();
this.veryHardAIduels.clear();
String s;
for (final QuestDuel qd : this.allDuels) {
@@ -360,7 +367,9 @@ public class QuestEventManager {
*/
public final List<QuestDuel> generateDuels() {
final QuestPreferences qpref = Singletons.getModel().getQuestPreferences();
if (AllZone.getQuestData() == null) { return null; }
if (AllZone.getQuestData() == null) {
return null;
}
final int index = AllZone.getQuestData().getDifficultyIndex();
final List<QuestDuel> duelOpponents = new ArrayList<QuestDuel>();
@@ -404,10 +413,11 @@ public class QuestEventManager {
* </p>
* Generates an array of new challenge opponents based on current win
* conditions.
*
*
* @param questData the quest data
* @return a {@link java.util.List} object.
*/
public final List<QuestChallenge> generateChallenges(QuestData questData) {
public final List<QuestChallenge> generateChallenges(final QuestData questData) {
final List<QuestChallenge> challengeOpponents = new ArrayList<QuestChallenge>();
int maxChallenges = questData.getWin() / 10;

View File

@@ -31,125 +31,191 @@ import forge.properties.ForgeProps;
import forge.properties.NewConstants.Quest;
/**
* Holds default preference values in an enum.
* Loads preferred values when instantiated.
* If a requested value is not present, default is returned.
* Holds default preference values in an enum. Loads preferred values when
* instantiated. If a requested value is not present, default is returned.
*
* @author Forge
* @version $Id$
*/
@SuppressWarnings("serial")
public class QuestPreferences implements Serializable {
private Map<QPref, String> preferenceValues;
private final Map<QPref, String> preferenceValues;
/**
* Preference identifiers, and their default values.
* When this class is instantiated, these enum values are used
* in a map that is populated with the current preferences
* from the text file.
/**
* Preference identifiers, and their default values. When this class is
* instantiated, these enum values are used in a map that is populated with
* the current preferences from the text file.
*/
public enum QPref { /** */
BOOSTER_COMMONS ("11"), /** */
BOOSTER_UNCOMMONS ("3"), /** */
BOOSTER_RARES ("1"), /** */
BOOSTER_FORMAT ("Standard"), /** */
public enum QPref {
/** The BOOSTE r_ commons. */
BOOSTER_COMMONS("11"),
/** The BOOSTE r_ uncommons. */
BOOSTER_UNCOMMONS("3"),
/** The BOOSTE r_ rares. */
BOOSTER_RARES("1"),
/** The BOOSTE r_ format. */
BOOSTER_FORMAT("Standard"),
/** The PENALT y_ loss. */
PENALTY_LOSS ("15"), /** */
CURRENT_QUEST ("DEFAULT"), /** */
CURRENT_DECK ("DEFAULT"), /** */
PENALTY_LOSS("15"), /** The CURREN t_ quest. */
CURRENT_QUEST("DEFAULT"),
/** The CURREN t_ deck. */
CURRENT_DECK("DEFAULT"),
/** The REWARD s_ base. */
REWARDS_BASE ("25"), /** */
REWARDS_UNDEFEATED ("25"), /** */
REWARDS_WINS_MULTIPLIER ("0.3"), /** */
REWARDS_POISON ("50"), /** */
REWARDS_MILLED ("40"), /** */
REWARDS_MULLIGAN0 ("500"), /** */
REWARDS_ALTERNATIVE ("100"), /** */
REWARDS_TURN15 ("5"), /** */
REWARDS_TURN10 ("50"), /** */
REWARDS_TURN5 ("250"), /** */
REWARDS_TURN1 ("1500"), /** */
REWARDS_BASE("25"), /** The REWARD s_ undefeated. */
REWARDS_UNDEFEATED("25"),
/** The REWARD s_ win s_ multiplier. */
REWARDS_WINS_MULTIPLIER("0.3"),
/** The REWARD s_ poison. */
REWARDS_POISON("50"),
/** The REWARD s_ milled. */
REWARDS_MILLED("40"),
/** The REWARD s_ mulliga n0. */
REWARDS_MULLIGAN0("500"),
/** The REWARD s_ alternative. */
REWARDS_ALTERNATIVE("100"),
/** The REWARD s_ tur n15. */
REWARDS_TURN15("5"),
/** The REWARD s_ tur n10. */
REWARDS_TURN10("50"),
/** The REWARD s_ tur n5. */
REWARDS_TURN5("250"),
/** The REWARD s_ tur n1. */
REWARDS_TURN1("1500"),
/** The STARTIN g_ basi c_ lands. */
STARTING_BASIC_LANDS ("20"), /** */
STARTING_SNOW_LANDS ("5"), /** */
STARTING_BASIC_LANDS("20"), /** The STARTIN g_ sno w_ lands. */
STARTING_SNOW_LANDS("5"),
/** The STARTIN g_ commons. */
STARTING_COMMONS ("DIFFICULTY_INDEX_REQD"), /** */
STARTING_COMMONS_EASY ("82"), /** */
STARTING_COMMONS_MEDIUM ("80"), /** */
STARTING_COMMONS_HARD ("78"), /** */
STARTING_COMMONS_EXPERT ("76"), /** */
STARTING_COMMONS("DIFFICULTY_INDEX_REQD"), /** The STARTIN g_ common s_ easy. */
STARTING_COMMONS_EASY("82"),
/** The STARTIN g_ common s_ medium. */
STARTING_COMMONS_MEDIUM("80"),
/** The STARTIN g_ common s_ hard. */
STARTING_COMMONS_HARD("78"),
/** The STARTIN g_ common s_ expert. */
STARTING_COMMONS_EXPERT("76"),
/** The STARTIN g_ uncommons. */
STARTING_UNCOMMONS ("DIFFICULTY_INDEX_REQD"), /** */
STARTING_UNCOMMONS_EASY ("40"), /** */
STARTING_UNCOMMONS_MEDIUM ("36"), /** */
STARTING_UNCOMMONS_HARD ("32"), /** */
STARTING_UNCOMMONS_EXPERT ("28"), /** */
STARTING_UNCOMMONS("DIFFICULTY_INDEX_REQD"), /** The STARTIN g_ uncommon s_ easy. */
STARTING_UNCOMMONS_EASY("40"),
/** The STARTIN g_ uncommon s_ medium. */
STARTING_UNCOMMONS_MEDIUM("36"),
/** The STARTIN g_ uncommon s_ hard. */
STARTING_UNCOMMONS_HARD("32"),
/** The STARTIN g_ uncommon s_ expert. */
STARTING_UNCOMMONS_EXPERT("28"),
/** The STARTIN g_ rares. */
STARTING_RARES ("DIFFICULTY_INDEX_REQD"), /** */
STARTING_RARES_EASY ("20"), /** */
STARTING_RARES_MEDIUM ("18"), /** */
STARTING_RARES_HARD ("16"), /** */
STARTING_RARES_EXPERT ("15"), /** */
STARTING_RARES("DIFFICULTY_INDEX_REQD"), /** The STARTIN g_ rare s_ easy. */
STARTING_RARES_EASY("20"),
/** The STARTIN g_ rare s_ medium. */
STARTING_RARES_MEDIUM("18"),
/** The STARTIN g_ rare s_ hard. */
STARTING_RARES_HARD("16"),
/** The STARTIN g_ rare s_ expert. */
STARTING_RARES_EXPERT("15"),
/** The STARTIN g_ credits. */
STARTING_CREDITS ("DIFFICULTY_INDEX_REQD"), /** */
STARTING_CREDITS_EASY ("250"), /** */
STARTING_CREDITS_MEDIUM ("200"), /** */
STARTING_CREDITS_HARD ("150"), /** */
STARTING_CREDITS_EXPERT ("100"), /** */
STARTING_CREDITS("DIFFICULTY_INDEX_REQD"), /** The STARTIN g_ credit s_ easy. */
STARTING_CREDITS_EASY("250"),
/** The STARTIN g_ credit s_ medium. */
STARTING_CREDITS_MEDIUM("200"),
/** The STARTIN g_ credit s_ hard. */
STARTING_CREDITS_HARD("150"),
/** The STARTIN g_ credit s_ expert. */
STARTING_CREDITS_EXPERT("100"),
/** The WIN s_ booster. */
WINS_BOOSTER ("DIFFICULTY_INDEX_REQD"), /** */
WINS_BOOSTER_EASY ("1"), /** */
WINS_BOOSTER_MEDIUM ("1"), /** */
WINS_BOOSTER_HARD ("2"), /** */
WINS_BOOSTER_EXPERT ("2"), /** */
WINS_BOOSTER("DIFFICULTY_INDEX_REQD"), /** The WIN s_ booste r_ easy. */
WINS_BOOSTER_EASY("1"),
/** The WIN s_ booste r_ medium. */
WINS_BOOSTER_MEDIUM("1"),
/** The WIN s_ booste r_ hard. */
WINS_BOOSTER_HARD("2"),
/** The WIN s_ booste r_ expert. */
WINS_BOOSTER_EXPERT("2"),
/** The WIN s_ rankup. */
WINS_RANKUP ("DIFFICULTY_INDEX_REQD"), /** */
WINS_RANKUP_EASY ("3"), /** */
WINS_RANKUP_MEDIUM ("4"), /** */
WINS_RANKUP_HARD ("5"), /** */
WINS_RANKUP_EXPERT ("6"), /** */
WINS_RANKUP("DIFFICULTY_INDEX_REQD"), /** The WIN s_ ranku p_ easy. */
WINS_RANKUP_EASY("3"),
/** The WIN s_ ranku p_ medium. */
WINS_RANKUP_MEDIUM("4"),
/** The WIN s_ ranku p_ hard. */
WINS_RANKUP_HARD("5"),
/** The WIN s_ ranku p_ expert. */
WINS_RANKUP_EXPERT("6"),
/** The WIN s_ mediumai. */
WINS_MEDIUMAI ("DIFFICULTY_INDEX_REQD"), /** */
WINS_MEDIUMAI_EASY ("10"), /** */
WINS_MEDIUMAI_MEDIUM ("9"), /** */
WINS_MEDIUMAI_HARD ("8"), /** */
WINS_MEDIUMAI_EXPERT ("7"), /** */
WINS_MEDIUMAI("DIFFICULTY_INDEX_REQD"), /** The WIN s_ mediuma i_ easy. */
WINS_MEDIUMAI_EASY("10"),
/** The WIN s_ mediuma i_ medium. */
WINS_MEDIUMAI_MEDIUM("9"),
/** The WIN s_ mediuma i_ hard. */
WINS_MEDIUMAI_HARD("8"),
/** The WIN s_ mediuma i_ expert. */
WINS_MEDIUMAI_EXPERT("7"),
/** The WIN s_ hardai. */
WINS_HARDAI ("DIFFICULTY_INDEX_REQD"), /** */
WINS_HARDAI_EASY ("20"), /** */
WINS_HARDAI_MEDIUM ("18"), /** */
WINS_HARDAI_HARD ("16"), /** */
WINS_HARDAI_EXPERT ("14"), /** */
WINS_HARDAI("DIFFICULTY_INDEX_REQD"), /** The WIN s_ harda i_ easy. */
WINS_HARDAI_EASY("20"),
/** The WIN s_ harda i_ medium. */
WINS_HARDAI_MEDIUM("18"),
/** The WIN s_ harda i_ hard. */
WINS_HARDAI_HARD("16"),
/** The WIN s_ harda i_ expert. */
WINS_HARDAI_EXPERT("14"),
/** The WIN s_ expertai. */
WINS_EXPERTAI ("DIFFICULTY_INDEX_REQD"), /** */
WINS_EXPERTAI_EASY ("40"), /** */
WINS_EXPERTAI_MEDIUM ("36"), /** */
WINS_EXPERTAI_HARD ("32"), /** */
WINS_EXPERTAI_EXPERT ("28"), /** */
WINS_EXPERTAI("DIFFICULTY_INDEX_REQD"), /** The WIN s_ experta i_ easy. */
WINS_EXPERTAI_EASY("40"),
/** The WIN s_ experta i_ medium. */
WINS_EXPERTAI_MEDIUM("36"),
/** The WIN s_ experta i_ hard. */
WINS_EXPERTAI_HARD("32"),
/** The WIN s_ experta i_ expert. */
WINS_EXPERTAI_EXPERT("28"),
/** The SHO p_ ma x_ packs. */
SHOP_MAX_PACKS ("6"), /** */
SHOP_SINGLES_COMMON ("7"), /** */
SHOP_SINGLES_UNCOMMON ("3"), /** */
SHOP_SINGLES_RARE ("1"), /** */
SHOP_WINS_FOR_ADDITIONAL_PACK ("10"), /** */
SHOP_STARTING_PACKS ("4"); /** */
SHOP_MAX_PACKS("6"), /** The SHO p_ single s_ common. */
SHOP_SINGLES_COMMON("7"),
/** The SHO p_ single s_ uncommon. */
SHOP_SINGLES_UNCOMMON("3"),
/** The SHO p_ single s_ rare. */
SHOP_SINGLES_RARE("1"),
/** The SHO p_ win s_ fo r_ additiona l_ pack. */
SHOP_WINS_FOR_ADDITIONAL_PACK("10"),
/** The SHO p_ startin g_ packs. */
SHOP_STARTING_PACKS("4");
/** */
private final String strDefaultVal;
/** @param s0 &emsp; {@link java.lang.String} */
QPref(String s0) {
/**
* Instantiates a new q pref.
*
* @param s0 &emsp; {@link java.lang.String}
*/
QPref(final String s0) {
this.strDefaultVal = s0;
}
/** @return {@link java.lang.String} */
/**
* Gets the default.
*
* @return {@link java.lang.String}
*/
public String getDefault() {
return strDefaultVal;
return this.strDefaultVal;
}
}
/** Instantiates a QuestPreferences object. */
public QuestPreferences() {
preferenceValues = new HashMap<QPref, String>();
this.preferenceValues = new HashMap<QPref, String>();
try {
final BufferedReader input = new BufferedReader(new FileReader(ForgeProps.getFile(Quest.PREFS)));
String line = null;
@@ -164,10 +230,10 @@ public class QuestPreferences implements Serializable {
this.setPreference(split[0], split[1]);
}
}
} catch (FileNotFoundException ex) {
//ex.printStackTrace();
} catch (IOException ex) {
//ex.printStackTrace();
} catch (final FileNotFoundException ex) {
// ex.printStackTrace();
} catch (final IOException ex) {
// ex.printStackTrace();
}
}
@@ -177,60 +243,65 @@ public class QuestPreferences implements Serializable {
try {
writer = new BufferedWriter(new FileWriter(ForgeProps.getFile(Quest.PREFS)));
for (QPref key : QPref.values()) {
for (final QPref key : QPref.values()) {
if (key.getDefault().equals("DIFFICULTY_INDEX_REQD")) {
writer.newLine();
continue;
}
writer.write(key + "=" + getPreference(key));
writer.write(key + "=" + this.getPreference(key));
writer.newLine();
}
writer.flush();
writer.close();
} catch (FileNotFoundException ex) {
} catch (final FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
} catch (final IOException ex) {
ex.printStackTrace();
}
}
/** */
/**
* Reset.
*/
public void reset() {
this.preferenceValues.clear();
}
/**
* DUE TO BE DEPRECATED:
* Transition code between preference manager for v1.2.2 and v1.2.3.
* (string-based vs. enum-based)
* DUE TO BE DEPRECATED: Transition code between preference manager for
* v1.2.2 and v1.2.3. (string-based vs. enum-based)
*
* @param s0 &emsp; {@link java.lang.String} identifier of preference
* @param s1 &emsp; {@link java.lang.String} value
* @param s0
* &emsp; {@link java.lang.String} identifier of preference
* @param s1
* &emsp; {@link java.lang.String} value
*/
public void setPreference(String s0, String s1) {
public void setPreference(final String s0, final String s1) {
try {
preferenceValues.put(QPref.valueOf(s0), s1);
}
catch (Exception e) {
this.preferenceValues.put(QPref.valueOf(s0), s1);
} catch (final Exception e) {
}
}
/**
* Sets the preference.
*
* @param q0 &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* @param s0 &emsp; {@link java.lang.String} value
*/
public void setPreference(QPref q0, String s0) {
preferenceValues.put(q0, s0);
public void setPreference(final QPref q0, final String s0) {
this.preferenceValues.put(q0, s0);
}
/**
* Returns a non-difficulty-indexed preference value.
*
* @param qp0 &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* @param qp0
* &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* @return String
*/
public String getPreference(QPref qp0) {
public String getPreference(final QPref qp0) {
String val;
if (qp0.getDefault().equals("DIFFICULTY_INDEX_REQD")) {
@@ -239,12 +310,17 @@ public class QuestPreferences implements Serializable {
// A difficulty index must be passed to determine
// which value is appropriate for this setting.
// To do this, use getPreference(QPref, int).
try { throw new Exception(); }
catch (Exception e1) { e1.printStackTrace(); }
try {
throw new Exception();
} catch (final Exception e1) {
e1.printStackTrace();
}
}
val = preferenceValues.get(qp0);
if (val == null) { val = qp0.getDefault(); }
val = this.preferenceValues.get(qp0);
if (val == null) {
val = qp0.getDefault();
}
return val;
}
@@ -252,31 +328,44 @@ public class QuestPreferences implements Serializable {
/**
* Returns a preference value according to a difficulty index.
*
* @param qp0 &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* @param i0 &emsp; int difficulty index
* @param qp0
* &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* @param i0
* &emsp; int difficulty index
* @return String
*/
public String getPreference(QPref qp0, int i0) {
public String getPreference(final QPref qp0, final int i0) {
String val;
String newQPref = qp0.toString();
QPref q;
switch(i0) {
case 0: newQPref += "_EASY"; break;
case 1: newQPref += "_MEDIUM"; break;
case 2: newQPref += "_HARD"; break;
case 3: newQPref += "_EXPERT"; break;
default:
try { throw new Exception(); }
catch (Exception e1) {
System.err.println("Difficulty index (" + i0 + ") out of bounds! ");
e1.printStackTrace();
}
switch (i0) {
case 0:
newQPref += "_EASY";
break;
case 1:
newQPref += "_MEDIUM";
break;
case 2:
newQPref += "_HARD";
break;
case 3:
newQPref += "_EXPERT";
break;
default:
try {
throw new Exception();
} catch (final Exception e1) {
System.err.println("Difficulty index (" + i0 + ") out of bounds! ");
e1.printStackTrace();
}
}
q = QPref.valueOf(newQPref);
val = preferenceValues.get(q);
if (val == null) { val = q.getDefault(); }
val = this.preferenceValues.get(q);
if (val == null) {
val = q.getDefault();
}
return val;
}
@@ -284,36 +373,50 @@ public class QuestPreferences implements Serializable {
/**
* Returns a non-difficulty-indexed preference value, as an int.
*
* @param qp0 &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* @param qp0
* &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* @return int
*/
public int getPreferenceInt(QPref qp0) {
return Integer.parseInt(getPreference(qp0));
public int getPreferenceInt(final QPref qp0) {
return Integer.parseInt(this.getPreference(qp0));
}
/**
* Returns a difficulty-indexed preference value, as an int.
*
* @param qp0 &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* @param i0 &emsp; int difficulty index
* @param qp0
* &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* @param i0
* &emsp; int difficulty index
* @return int
*/
public int getPreferenceInt(QPref qp0, int i0) {
return Integer.parseInt(getPreference(qp0, i0));
public int getPreferenceInt(final QPref qp0, final int i0) {
return Integer.parseInt(this.getPreference(qp0, i0));
}
/**
* Gets the difficulty.
*
* @param i &emsp; int
* @return String
*/
public static String getDifficulty(int i) {
public static String getDifficulty(final int i) {
String s;
switch(i) {
case 1: s = "EASY"; break;
case 2: s = "MEDIUM"; break;
case 3: s = "HARD"; break;
case 4: s = "EXPERT"; break;
default: s = "UNKNOWN";
switch (i) {
case 1:
s = "EASY";
break;
case 2:
s = "MEDIUM";
break;
case 3:
s = "HARD";
break;
case 4:
s = "EXPERT";
break;
default:
s = "UNKNOWN";
}
return s;
}

View File

@@ -26,6 +26,7 @@ import net.slightlymagic.maxmtg.Predicate;
import forge.Singletons;
import forge.card.BoosterGenerator;
import forge.card.CardEdition;
import forge.card.CardRarity;
import forge.card.FormatUtils;
import forge.deck.Deck;
import forge.item.BoosterPack;
@@ -60,17 +61,14 @@ public final class QuestUtilCards {
/**
* Adds the basic lands.
*
* @param pool
* the pool
* @param nBasic
* the n basic
* @param nSnow
* the n snow
*
* @param nBasic the n basic
* @param nSnow the n snow
* @return the item pool view
*/
public static ItemPoolView<CardPrinted> generateBasicLands(final int nBasic, final int nSnow) {
final CardDb db = CardDb.instance();
ItemPool<CardPrinted> pool = new ItemPool<CardPrinted>(CardPrinted.class);
final ItemPool<CardPrinted> pool = new ItemPool<CardPrinted>(CardPrinted.class);
pool.add(db.getCard("Forest", "M10"), nBasic);
pool.add(db.getCard("Mountain", "M10"), nBasic);
pool.add(db.getCard("Swamp", "M10"), nBasic);
@@ -317,15 +315,17 @@ public final class QuestUtilCards {
* Generate cards in shop.
*/
private final FormatUtils formats = Singletons.getModel().getFormats();
private final Predicate<CardEdition> filterExt = CardEdition.Predicates.isLegalInFormat(formats.getExtended());
private final Predicate<CardEdition> filterExt = CardEdition.Predicates.isLegalInFormat(this.formats.getExtended());
/** The filter t2booster. */
private final Predicate<CardEdition> filterT2booster = Predicate.and(CardEdition.Predicates.CAN_MAKE_BOOSTER,
CardEdition.Predicates.isLegalInFormat(formats.getStandard()));
CardEdition.Predicates.isLegalInFormat(this.formats.getStandard()));
/** The filter ext but t2. */
private final Predicate<CardEdition> filterExtButT2 = Predicate.and(CardEdition.Predicates.CAN_MAKE_BOOSTER,
Predicate.and(this.filterExt, Predicate.not(CardEdition.Predicates.isLegalInFormat(formats.getStandard()))));
private final Predicate<CardEdition> filterExtButT2 = Predicate.and(
CardEdition.Predicates.CAN_MAKE_BOOSTER,
Predicate.and(this.filterExt,
Predicate.not(CardEdition.Predicates.isLegalInFormat(this.formats.getStandard()))));
/** The filter not ext. */
private final Predicate<CardEdition> filterNotExt = Predicate.and(CardEdition.Predicates.CAN_MAKE_BOOSTER,
@@ -342,7 +342,8 @@ public final class QuestUtilCards {
final int rollD100 = MyRandom.getRandom().nextInt(100);
final Predicate<CardEdition> filter = rollD100 < 40 ? this.filterT2booster
: (rollD100 < 75 ? this.filterExtButT2 : this.filterNotExt);
this.q.getShopList().addAllFlat(filter.random(Singletons.getModel().getEditions().getAllSets(), 1, BoosterPack.FN_FROM_SET));
this.q.getShopList().addAllFlat(
filter.random(Singletons.getModel().getEditions().getAllSets(), 1, BoosterPack.FN_FROM_SET));
}
}
@@ -355,7 +356,7 @@ public final class QuestUtilCards {
public void generatePreconsInShop(final int count) {
final List<PreconDeck> meetRequirements = new ArrayList<PreconDeck>();
for (final PreconDeck deck : QuestData.getPrecons()) {
if (deck.getRecommendedDeals().meetsRequiremnts(q)) {
if (deck.getRecommendedDeals().meetsRequiremnts(this.q)) {
meetRequirements.add(deck);
}
}
@@ -380,7 +381,6 @@ public final class QuestUtilCards {
final int winPacks = this.q.getWin() / winsForPack;
final int totalPacks = Math.min(levelPacks + winPacks, maxPacks);
this.q.getShopList().clear();
for (int i = 0; i < totalPacks; i++) {
this.q.getShopList().addAllFlat(pack.getBoosterPack(common, uncommon, rare, 0, 0, 0, 0, 0, 0));

View File

@@ -1,27 +1,62 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.util;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
/**
/**
* TODO: Write javadoc for this type.
*
*
*/
public class FileSection {
/** The lines. */
protected final Map<String, String> lines = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
/**
* Gets the lines.
*
* @return the lines
*/
protected final Map<String, String> getLines() {
return lines;
return this.lines;
}
protected FileSection() { }
/**
* Instantiates a new file section.
*/
protected FileSection() {
}
public static FileSection parse(String line, String kvSeparator, String pairSeparator) {
String[] pairs = line.split(Pattern.quote(pairSeparator));
Pattern splitter = Pattern.compile(Pattern.quote(kvSeparator));
FileSection result = new FileSection();
/**
* Parses the.
*
* @param line the line
* @param kvSeparator the kv separator
* @param pairSeparator the pair separator
* @return the file section
*/
public static FileSection parse(final String line, final String kvSeparator, final String pairSeparator) {
final String[] pairs = line.split(Pattern.quote(pairSeparator));
final Pattern splitter = Pattern.compile(Pattern.quote(kvSeparator));
final FileSection result = new FileSection();
for (final String dd : pairs) {
final String[] v = splitter.split(dd, 2);
@@ -31,9 +66,16 @@ public class FileSection {
return result;
}
public static FileSection parse(Iterable<String> lines, String kvSeparator) {
FileSection result = new FileSection();
Pattern splitter = Pattern.compile(Pattern.quote(kvSeparator));
/**
* Parses the.
*
* @param lines the lines
* @param kvSeparator the kv separator
* @return the file section
*/
public static FileSection parse(final Iterable<String> lines, final String kvSeparator) {
final FileSection result = new FileSection();
final Pattern splitter = Pattern.compile(Pattern.quote(kvSeparator));
for (final String dd : lines) {
final String[] v = splitter.split(dd, 2);
result.lines.put(v[0].trim(), v.length > 1 ? v[1].trim() : "");
@@ -42,27 +84,64 @@ public class FileSection {
return result;
}
public String get(String fieldName) {
return lines.get(fieldName);
/**
* Gets the.
*
* @param fieldName the field name
* @return the string
*/
public String get(final String fieldName) {
return this.lines.get(fieldName);
}
public int getInt(String fieldName) { return getInt(fieldName, 0); }
public int getInt(String fieldName, int defaultValue) {
/**
* Gets the int.
*
* @param fieldName the field name
* @return the int
*/
public int getInt(final String fieldName) {
return this.getInt(fieldName, 0);
}
/**
* Gets the int.
*
* @param fieldName the field name
* @param defaultValue the default value
* @return the int
*/
public int getInt(final String fieldName, final int defaultValue) {
try {
return Integer.parseInt(get(fieldName));
} catch (NumberFormatException ex) {
return Integer.parseInt(this.get(fieldName));
} catch (final NumberFormatException ex) {
return defaultValue;
}
}
public boolean getBoolean(String fieldName) { return getBoolean(fieldName, false); }
public boolean getBoolean(String fieldName, boolean defaultValue) {
String s = get(fieldName);
/**
* Gets the boolean.
*
* @param fieldName the field name
* @return the boolean
*/
public boolean getBoolean(final String fieldName) {
return this.getBoolean(fieldName, false);
}
/**
* Gets the boolean.
*
* @param fieldName the field name
* @param defaultValue the default value
* @return the boolean
*/
public boolean getBoolean(final String fieldName, final boolean defaultValue) {
final String s = this.get(fieldName);
if (s == null) {
return defaultValue;
}
return "true".equalsIgnoreCase(s);
}
}

View File

@@ -1,13 +1,36 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.util;
/**
/**
* TODO: Write javadoc for this type.
*
*
*/
public class FileSectionManual extends FileSection {
public void put(String key, String value) {
getLines().put(key, value);
/**
* Put.
*
* @param key the key
* @param value the value
*/
public void put(final String key, final String value) {
this.getLines().put(key, value);
}
}

View File

@@ -17,54 +17,56 @@
*/
package forge.util;
//reads and writeDeck Deck objects
/**
* <p>
* DeckManager class.
* </p>
*
*
* @param <T> the generic type
* @author Forge
* @version $Id$
*/
public class FolderMap<T extends IHasName> extends FolderMapView<T> implements IFolderMap<T> {
private IItemSerializer<T> serializer;
private final IItemSerializer<T> serializer;
/**
* <p>
* Constructor for DeckManager.
* </p>
*
* @param deckDir
* a {@link java.io.File} object.
*
* @param io the io
*/
public FolderMap(IItemSerializer<T> io) {
public FolderMap(final IItemSerializer<T> io) {
super(io);
serializer = io;
this.serializer = io;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.IFolderMap#add(T)
*/
@Override
public final void add(final T deck) {
this.getMap().put(deck.getName(), deck);
serializer.save(deck);
this.serializer.save(deck);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.IFolderMap#delete(java.lang.String)
*/
@Override
public final void delete(final String deckName) {
serializer.erase(this.getMap().remove(deckName));
this.serializer.erase(this.getMap().remove(deckName));
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.IFolderMapView#isUnique(java.lang.String)
*/
@Override
@@ -72,7 +74,4 @@ public class FolderMap<T extends IHasName> extends FolderMapView<T> implements I
return !this.getMap().containsKey(name);
}
}

View File

@@ -22,13 +22,13 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
//reads and writeDeck Deck objects
/**
* <p>
* DeckManager class.
* </p>
*
*
* @param <T> the generic type
* @author Forge
* @version $Id: DeckManager.java 13590 2012-01-27 20:46:27Z Max mtg $
*/
@@ -39,15 +39,16 @@ public class FolderMapView<T extends IHasName> implements Iterable<T>, IFolderMa
* <p>
* Constructor for DeckManager.
* </p>
*
* @param deckDir
* a {@link java.io.File} object.
*
* @param io the io
*/
public FolderMapView(IItemReader<T> io) {
public FolderMapView(final IItemReader<T> io) {
this.map = io.readAll();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.IFolderMapView#get(java.lang.String)
*/
@Override
@@ -55,22 +56,33 @@ public class FolderMapView<T extends IHasName> implements Iterable<T>, IFolderMa
return this.map.get(name);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.IFolderMapView#getNames()
*/
@Override
public final Collection<String> getNames() {
return new ArrayList<String>(map.keySet());
return new ArrayList<String>(this.map.keySet());
}
/**
* Gets the map.
*
* @return the map
*/
protected final Map<String, T> getMap() {
return map;
return this.map;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see java.lang.Iterable#iterator()
*/
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see forge.deck.IFolderMapView#iterator()
*/
@Override

View File

@@ -1,10 +1,26 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.util;
/**
/**
* TODO: Write javadoc for this type.
*
* @param <T>
* @param <T> the generic type
*/
public interface IFolderMap<T extends IHasName> extends IFolderMapView<T> {
@@ -32,9 +48,8 @@ public interface IFolderMap<T extends IHasName> extends IFolderMapView<T> {
* <p>
* isUnique.
* </p>
*
* @param deckName
* a {@link java.lang.String} object.
*
* @param name the name
* @return a boolean.
*/
public abstract boolean isUnique(final String name);

View File

@@ -1,12 +1,28 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.util;
import java.util.Collection;
/**
/**
* TODO: Write javadoc for this type.
*
* @param <T>
* @param <T> the generic type
*/
public interface IFolderMapView<T extends IHasName> extends Iterable<T> {
@@ -14,22 +30,17 @@ public interface IFolderMapView<T extends IHasName> extends Iterable<T> {
* <p>
* getDeck.
* </p>
*
* @param deckName
* a {@link java.lang.String} object.
*
* @param name the name
* @return a {@link forge.deck.Deck} object.
*/
public abstract T get(final String name);
/**
*
* Get names of decks.
*
* @param deckType
* a GameType
*
* @return a ArrayList<String>
*/
public abstract Collection<String> getNames();
}

View File

@@ -1,9 +1,32 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.util;
/**
/**
* TODO: Write javadoc for this type.
*
*
*/
public interface IHasName {
/**
* Gets the name.
*
* @return the name
*/
String getName();
}

View File

@@ -1,11 +1,36 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.util;
import java.util.Map;
/**
* The Interface IItemReader.
*
* @param <T> the generic type
*/
public interface IItemReader<T extends IHasName> {
/**
* Read all.
*
* @return the map
*/
Map<String, T> readAll();
//T read(File file);
// T read(File file);
}

View File

@@ -1,14 +1,40 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.util;
/**
/**
* TODO: Write javadoc for this type.
*
* @param <T> the generic type
*/
public interface IItemSerializer<T extends IHasName> extends IItemReader<T> {
/**
* Save.
*
* @param unit the unit
*/
void save(T unit);
/**
* Erase.
*
* @param unit the unit
*/
void erase(T unit);
}

View File

@@ -77,5 +77,5 @@ public class SectionUtil {
return result;
}
}

View File

@@ -28,42 +28,43 @@ import org.apache.commons.lang3.StringUtils;
/**
* This class treats every line of a given file as a source for a named object.
*
*
* @param <T> the generic type
*/
public abstract class StorageReaderFile<T extends IHasName> implements IItemReader<T> {
private final File file;
public StorageReaderFile(File file0) {
file = file0;
/**
* Instantiates a new storage reader file.
*
* @param file0 the file0
*/
public StorageReaderFile(final File file0) {
this.file = file0;
}
// only accepts numbers, letters or dashes up to 20 characters in length
/**
*
* Clean deck name.
*
* @param in
* a String
*
* @return a String
*/
@Override
public Map<String, T> readAll() {
final Map<String, T> result = new TreeMap<String, T>();
final ArrayList<String> fData = FileUtil.readFile(file);
final ArrayList<String> fData = FileUtil.readFile(this.file);
for (final String s : fData) {
if (!lineContainsObject(s)) {
if (!this.lineContainsObject(s)) {
continue;
}
T item = read(s);
final T item = this.read(s);
if (null == item) {
String msg = "An object stored in " + file.getPath() + " failed to load.\nPlease submit this as a bug with the mentioned file attached.";
final String msg = "An object stored in " + this.file.getPath()
+ " failed to load.\nPlease submit this as a bug with the mentioned file attached.";
JOptionPane.showMessageDialog(null, msg);
continue;
}
@@ -74,16 +75,21 @@ public abstract class StorageReaderFile<T extends IHasName> implements IItemRead
return result;
}
/**
* TODO: Write javadoc for this method.
* @param file
* @return
*
* @param line the line
* @return the t
*/
protected abstract T read(String line);
protected boolean lineContainsObject(String line) {
/**
* Line contains object.
*
* @param line the line
* @return true, if successful
*/
protected boolean lineContainsObject(final String line) {
return !StringUtils.isBlank(line) && !line.trim().startsWith("#");
}

View File

@@ -34,33 +34,43 @@ import forge.deck.io.OldDeckFileFormatException;
import forge.error.ErrorViewer;
/**
* This class treats every file in the given folder as a source for a named object.
* The descendant should implement read method to deserialize a single item.
* So that readAll will return a map of Name => Object as read from disk
*
* This class treats every file in the given folder as a source for a named
* object. The descendant should implement read method to deserialize a single
* item. So that readAll will return a map of Name => Object as read from disk
*
* @param <T> the generic type
*/
public abstract class StorageReaderFolder<T extends IHasName> implements IItemReader<T> {
private final File directory;
/**
* Gets the directory.
*
* @return the directory
*/
protected final File getDirectory() {
return directory;
return this.directory;
}
/**
* Instantiates a new storage reader folder.
*
* @param deckDir0 the deck dir0
*/
public StorageReaderFolder(final File deckDir0) {
public StorageReaderFolder(File deckDir0) {
this.directory = deckDir0;
directory = deckDir0;
if (directory == null) {
if (this.directory == null) {
throw new IllegalArgumentException("No deck directory specified");
}
try {
if (directory.isFile()) {
if (this.directory.isFile()) {
throw new IOException("Not a directory");
} else {
directory.mkdirs();
if (!directory.isDirectory()) {
this.directory.mkdirs();
if (!this.directory.isDirectory()) {
throw new IOException("Directory can't be created");
}
}
@@ -70,27 +80,35 @@ public abstract class StorageReaderFolder<T extends IHasName> implements IItemRe
}
}
/* (non-Javadoc)
* @see forge.util.IItemReader#readAll()
*/
@Override
public Map<String, T> readAll() {
final Map<String, T> result = new TreeMap<String, T>();
final List<String> decksThatFailedToLoad = new ArrayList<String>();
final File[] files = directory.listFiles(getFileFilter());
final File[] files = this.directory.listFiles(this.getFileFilter());
boolean hasWarnedOfOldFormat = false;
for (final File file : files) {
try {
final T newDeck = read(file);
final T newDeck = this.read(file);
if (null == newDeck) {
String msg = "An object stored in " + file.getPath() + " failed to load.\nPlease submit this as a bug with the mentioned file/directory attached.";
final String msg = "An object stored in "
+ file.getPath()
+ " failed to load.\nPlease submit this as a bug with the mentioned file/directory attached.";
JOptionPane.showMessageDialog(null, msg);
continue;
}
result.put(newDeck.getName(), newDeck);
} catch (final OldDeckFileFormatException ex ) {
if( !hasWarnedOfOldFormat ) {
JOptionPane.showMessageDialog(null, "Found a deck in old fileformat in the storage.\nMoving this file and all similiar ones to parent folder.\n\nForge will try to convert them in a second.");
} catch (final OldDeckFileFormatException ex) {
if (!hasWarnedOfOldFormat) {
JOptionPane
.showMessageDialog(
null,
"Found a deck in old fileformat in the storage.\nMoving this file and all similiar ones to parent folder.\n\nForge will try to convert them in a second.");
hasWarnedOfOldFormat = true;
}
file.renameTo(new File(directory.getParentFile(), file.getName()));
file.renameTo(new File(this.directory.getParentFile(), file.getName()));
} catch (final NoSuchElementException ex) {
final String message = String.format("%s failed to load because ---- %s", file.getName(),
ex.getMessage());
@@ -107,17 +125,17 @@ public abstract class StorageReaderFolder<T extends IHasName> implements IItemRe
return result;
}
/**
* Read the object from file.
* @param file
*
* @param file the file
* @return the object deserialized by inherited class
*/
protected abstract T read(File file);
/**
* TODO: Write javadoc for this method.
*
* @return FilenameFilter to pick only relevant objects for deserialization
*/
protected abstract FilenameFilter getFileFilter();

View File

@@ -1,3 +1,20 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Nate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.view.toolbox;
import java.awt.Color;
@@ -28,40 +45,45 @@ import forge.gui.deckeditor.DeckEditorConstructed;
import forge.gui.deckeditor.DeckEditorLimited;
import forge.gui.deckeditor.DeckEditorQuest;
/**
* Creates deck list for selected decks for quick deleting, editing, and basic info.
*
/**
* Creates deck list for selected decks for quick deleting, editing, and basic
* info.
*
*/
@SuppressWarnings("serial")
public class DeckLister extends JPanel {
private ImageIcon icoDelete;
private ImageIcon icoDeleteOver;
private ImageIcon icoEdit;
private ImageIcon icoEditOver;
private final ImageIcon icoDelete;
private final ImageIcon icoDeleteOver;
private final ImageIcon icoEdit;
private final ImageIcon icoEditOver;
private RowPanel previousSelect;
private RowPanel[] rows;
private GameType gametype;
private final GameType gametype;
private Command cmdEditorExit, cmdDelete, cmdRowSelect;
private final Color clrDefault, clrHover, clrActive, clrBorders;
/**
* Creates deck list for selected decks for quick deleting, editing, and basic info.
* "selectable" and "editable" assumed true.
* Creates deck list for selected decks for quick deleting, editing, and
* basic info. "selectable" and "editable" assumed true.
*
* @param gt0 {@link forge.game.GameType}
* @param gt0 the gt0
* {@link forge.game.GameType}
*/
public DeckLister(GameType gt0) {
public DeckLister(final GameType gt0) {
this(gt0, null);
}
/**
* Creates deck list for selected decks for quick deleting, editing, and basic info.
* Set "selectable" and "editable" to show those buttons, or not.
*
* @param gt0 {@link forge.game.GameType}
* @param cmd0 {@link forge.Command}, when exiting deck editor
* Creates deck list for selected decks for quick deleting, editing, and
* basic info. Set "selectable" and "editable" to show those buttons, or
* not.
*
* @param gt0 the gt0
* @param cmd0 the cmd0
* {@link forge.game.GameType}
* {@link forge.Command}, when exiting deck editor
*/
public DeckLister(GameType gt0, Command cmd0) {
public DeckLister(final GameType gt0, final Command cmd0) {
super();
this.gametype = gt0;
this.cmdEditorExit = cmd0;
@@ -74,21 +96,27 @@ public class DeckLister extends JPanel {
this.setOpaque(false);
this.setLayout(new MigLayout("insets 0, gap 0, wrap"));
icoDelete = FSkin.getIcon(FSkin.ForgeIcons.ICO_DELETE);
icoDeleteOver = FSkin.getIcon(FSkin.ForgeIcons.ICO_DELETE_OVER);
icoEdit = FSkin.getIcon(FSkin.ForgeIcons.ICO_EDIT);
icoEditOver = FSkin.getIcon(FSkin.ForgeIcons.ICO_EDIT_OVER);
this.icoDelete = FSkin.getIcon(FSkin.ForgeIcons.ICO_DELETE);
this.icoDeleteOver = FSkin.getIcon(FSkin.ForgeIcons.ICO_DELETE_OVER);
this.icoEdit = FSkin.getIcon(FSkin.ForgeIcons.ICO_EDIT);
this.icoEditOver = FSkin.getIcon(FSkin.ForgeIcons.ICO_EDIT_OVER);
}
/** @param decks0 {@link forge.deck.Deck}[] */
public void setDecks(Iterable<Deck> decks0) {
/**
* Sets the decks.
*
* @param decks0 the new decks
* {@link forge.deck.Deck}[]
*/
public void setDecks(final Iterable<Deck> decks0) {
this.removeAll();
List<RowPanel> tempRows = new ArrayList<RowPanel>();
final List<RowPanel> tempRows = new ArrayList<RowPanel>();
// Title row
// Note: careful with the widths of the rows here;
// scroll panes will have difficulty dynamically resizing if 100% width is set.
JPanel rowTitle = new TitlePanel();
// scroll panes will have difficulty dynamically resizing if 100% width
// is set.
final JPanel rowTitle = new TitlePanel();
rowTitle.setBackground(FSkin.getColor(FSkin.Colors.CLR_ZEBRA));
rowTitle.setLayout(new MigLayout("insets 0, gap 0"));
@@ -96,7 +124,8 @@ public class DeckLister extends JPanel {
"w 10%!, h 20px!, gaptop 5px");
rowTitle.add(new FLabel.Builder().text("Edit").fontAlign(SwingConstants.CENTER).build(),
"w 10%!, h 20px!, gaptop 5px");
rowTitle.add(new FLabel.Builder().text("Deck Name").fontAlign(SwingConstants.CENTER).build(), "w 60%!, h 20px!, gaptop 5px");
rowTitle.add(new FLabel.Builder().text("Deck Name").fontAlign(SwingConstants.CENTER).build(),
"w 60%!, h 20px!, gaptop 5px");
rowTitle.add(new FLabel.Builder().text("Main").fontAlign(SwingConstants.CENTER).build(),
"w 10%!, h 20px!, gaptop 5px");
rowTitle.add(new FLabel.Builder().text("Side").fontAlign(SwingConstants.CENTER).build(),
@@ -104,8 +133,10 @@ public class DeckLister extends JPanel {
this.add(rowTitle, "w 98%!, h 30px!, gapleft 1%");
RowPanel row;
for (Deck d : decks0) {
if (d.getName() == null) { continue; }
for (final Deck d : decks0) {
if (d.getName() == null) {
continue;
}
row = new RowPanel(d);
row.add(new DeleteButton(row), "w 10%!, h 20px!, gaptop 5px");
@@ -117,14 +148,18 @@ public class DeckLister extends JPanel {
tempRows.add(row);
}
rows = tempRows.toArray(new RowPanel[0]);
revalidate();
this.rows = tempRows.toArray(new RowPanel[0]);
this.revalidate();
}
/** @return {@link forge.deck.Deck} */
/**
* Gets the selected deck.
*
* @return {@link forge.deck.Deck}
*/
public Deck getSelectedDeck() {
Deck selectedDeck = null;
for (RowPanel r : rows) {
for (final RowPanel r : this.rows) {
if (r.isSelected()) {
selectedDeck = r.getDeck();
}
@@ -135,40 +170,42 @@ public class DeckLister extends JPanel {
/** Prevent panel from repainting the whole screen. */
public void repaintOnlyThisPanel() {
final Dimension d = DeckLister.this.getSize();
repaint(0, 0, d.width, d.height);
this.repaint(0, 0, d.width, d.height);
}
private class DeleteButton extends JButton {
public DeleteButton(final RowPanel r0) {
super();
setRolloverEnabled(true);
setPressedIcon(icoDeleteOver);
setRolloverIcon(icoDeleteOver);
setIcon(icoDelete);
setOpaque(false);
setContentAreaFilled(false);
setBorder(null);
setBorderPainted(false);
setToolTipText("Delete this deck");
this.setRolloverEnabled(true);
this.setPressedIcon(DeckLister.this.icoDeleteOver);
this.setRolloverIcon(DeckLister.this.icoDeleteOver);
this.setIcon(DeckLister.this.icoDelete);
this.setOpaque(false);
this.setContentAreaFilled(false);
this.setBorder(null);
this.setBorderPainted(false);
this.setToolTipText("Delete this deck");
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
public void mouseEntered(final MouseEvent e) {
if (!r0.selected) {
r0.setBackground(clrHover);
r0.setBackground(DeckLister.this.clrHover);
r0.setOpaque(true);
}
}
@Override
public void mouseExited(MouseEvent e) {
public void mouseExited(final MouseEvent e) {
if (!r0.selected) {
r0.setBackground(clrDefault);
r0.setBackground(DeckLister.this.clrDefault);
r0.setOpaque(false);
}
}
@Override
public void mouseClicked(MouseEvent e) {
deleteDeck(r0);
public void mouseClicked(final MouseEvent e) {
DeckLister.this.deleteDeck(r0);
}
});
}
@@ -177,217 +214,246 @@ public class DeckLister extends JPanel {
private class EditButton extends JButton {
public EditButton(final RowPanel r0) {
super();
setRolloverEnabled(true);
setPressedIcon(icoEditOver);
setRolloverIcon(icoEditOver);
setIcon(icoEdit);
setOpaque(false);
setContentAreaFilled(false);
setBorder(null);
setBorderPainted(false);
setToolTipText("Edit this deck");
this.setRolloverEnabled(true);
this.setPressedIcon(DeckLister.this.icoEditOver);
this.setRolloverIcon(DeckLister.this.icoEditOver);
this.setIcon(DeckLister.this.icoEdit);
this.setOpaque(false);
this.setContentAreaFilled(false);
this.setBorder(null);
this.setBorderPainted(false);
this.setToolTipText("Edit this deck");
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
public void mouseEntered(final MouseEvent e) {
if (!r0.selected) {
r0.setBackground(clrHover);
r0.setBackground(DeckLister.this.clrHover);
r0.setOpaque(true);
}
}
@Override
public void mouseExited(MouseEvent e) {
public void mouseExited(final MouseEvent e) {
if (!r0.selected) {
r0.setBackground(clrDefault);
r0.setBackground(DeckLister.this.clrDefault);
r0.setOpaque(false);
}
}
@Override
public void mouseClicked(MouseEvent e) {
editDeck(r0.getDeck());
public void mouseClicked(final MouseEvent e) {
DeckLister.this.editDeck(r0.getDeck());
}
});
}
}
// Here only to prevent visual artifact problems from translucent skin colors.
// Here only to prevent visual artifact problems from translucent skin
// colors.
private class TitlePanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.clearRect(0, 0, getWidth(), getHeight());
g.fillRect(0, 0, getWidth(), getHeight());
public void paintComponent(final Graphics g) {
g.setColor(this.getBackground());
g.clearRect(0, 0, this.getWidth(), this.getHeight());
g.fillRect(0, 0, this.getWidth(), this.getHeight());
super.paintComponent(g);
}
}
private class RowPanel extends JPanel {
private boolean selected = false;
private Deck deck;
private final Deck deck;
public RowPanel(Deck d0) {
public RowPanel(final Deck d0) {
super();
setOpaque(false);
setBackground(new Color(0, 0, 0, 0));
setLayout(new MigLayout("insets 0, gap 0"));
setBorder(new MatteBorder(0, 0, 1, 0, clrBorders));
deck = d0;
this.setOpaque(false);
this.setBackground(new Color(0, 0, 0, 0));
this.setLayout(new MigLayout("insets 0, gap 0"));
this.setBorder(new MatteBorder(0, 0, 1, 0, DeckLister.this.clrBorders));
this.deck = d0;
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
if (!selected) {
((RowPanel) e.getSource()).setBackground(clrHover);
public void mouseEntered(final MouseEvent e) {
if (!RowPanel.this.selected) {
((RowPanel) e.getSource()).setBackground(DeckLister.this.clrHover);
((RowPanel) e.getSource()).setOpaque(true);
}
}
@Override
public void mouseExited(MouseEvent e) {
if (!selected) {
((RowPanel) e.getSource()).setBackground(clrDefault);
public void mouseExited(final MouseEvent e) {
if (!RowPanel.this.selected) {
((RowPanel) e.getSource()).setBackground(DeckLister.this.clrDefault);
((RowPanel) e.getSource()).setOpaque(false);
}
}
@Override
public void mousePressed(MouseEvent e) {
selectHandler((RowPanel) e.getSource());
public void mousePressed(final MouseEvent e) {
DeckLister.this.selectHandler((RowPanel) e.getSource());
}
});
}
public void setSelected(boolean b0) {
selected = b0;
setOpaque(b0);
setBackground(b0 ? clrActive : clrHover);
public void setSelected(final boolean b0) {
this.selected = b0;
this.setOpaque(b0);
this.setBackground(b0 ? DeckLister.this.clrActive : DeckLister.this.clrHover);
}
public boolean isSelected() {
return selected;
return this.selected;
}
public Deck getDeck() {
return deck;
return this.deck;
}
}
private class MainLabel extends JLabel {
public MainLabel(String txt0) {
public MainLabel(final String txt0) {
super(txt0);
setOpaque(true);
this.setOpaque(true);
if (Integer.parseInt(txt0) < 40) {
setBackground(Color.RED.brighter());
this.setBackground(Color.RED.brighter());
} else {
this.setBackground(Color.GREEN);
}
else {
setBackground(Color.GREEN);
}
setHorizontalAlignment(SwingConstants.CENTER);
setFont(FSkin.getBoldFont(12));
setHorizontalAlignment(SwingConstants.CENTER);
this.setHorizontalAlignment(SwingConstants.CENTER);
this.setFont(FSkin.getBoldFont(12));
this.setHorizontalAlignment(SwingConstants.CENTER);
}
}
private class GenericLabel extends JLabel {
public GenericLabel(String txt0) {
public GenericLabel(final String txt0) {
super(txt0);
setHorizontalAlignment(SwingConstants.CENTER);
setForeground(FSkin.getColor(FSkin.Colors.CLR_TEXT));
setFont(FSkin.getBoldFont(12));
this.setHorizontalAlignment(SwingConstants.CENTER);
this.setForeground(FSkin.getColor(FSkin.Colors.CLR_TEXT));
this.setFont(FSkin.getBoldFont(12));
}
}
/** @return {@link java.lang.Integer} */
/**
* Gets the selected index.
*
* @return {@link java.lang.Integer}
*/
public int getSelectedIndex() {
for (int i = 0; i < rows.length; i++) {
if (rows[i].isSelected()) { return i; }
for (int i = 0; i < this.rows.length; i++) {
if (this.rows[i].isSelected()) {
return i;
}
}
return -1;
}
/** Selects a row programatically.
* @param i0 &emsp; int
/**
* Selects a row programatically.
*
* @param i0
* &emsp; int
* @return boolean Was able to select, or not.
*/
public boolean setSelectedIndex(int i0) {
if (i0 >= rows.length) { return false; }
selectHandler(rows[i0]);
public boolean setSelectedIndex(final int i0) {
if (i0 >= this.rows.length) {
return false;
}
this.selectHandler(this.rows[i0]);
return true;
}
/**
/**
* Sets the selected deck.
*
* @param d0 &emsp; Deck object to select (if exists in list)
* @return boolean Found deck, or didn't.
*/
public boolean setSelectedDeck(Deck d0) {
for (RowPanel r : rows) {
public boolean setSelectedDeck(final Deck d0) {
for (final RowPanel r : this.rows) {
if (r.getDeck() == d0) {
selectHandler(r);
this.selectHandler(r);
return true;
}
}
return false;
}
/** @param c0 &emsp; {@link forge.Command} command executed on delete. */
public void setDeleteCommand(Command c0) {
/**
* Sets the delete command.
*
* @param c0 &emsp; {@link forge.Command} command executed on delete.
*/
public void setDeleteCommand(final Command c0) {
this.cmdDelete = c0;
}
/** @param c0 &emsp; {@link forge.Command} command executed on row select. */
public void setSelectCommand(Command c0) {
/**
* Sets the select command.
*
* @param c0 &emsp; {@link forge.Command} command executed on row select.
*/
public void setSelectCommand(final Command c0) {
this.cmdRowSelect = c0;
}
/** @param c0 &emsp; {@link forge.Command} command executed on editor exit. */
public void setExitCommand(Command c0) {
/**
* Sets the exit command.
*
* @param c0 &emsp; {@link forge.Command} command executed on editor exit.
*/
public void setExitCommand(final Command c0) {
this.cmdEditorExit = c0;
}
private void selectHandler(RowPanel r0) {
if (previousSelect != null) {
previousSelect.setSelected(false);
private void selectHandler(final RowPanel r0) {
if (this.previousSelect != null) {
this.previousSelect.setSelected(false);
}
r0.setSelected(true);
previousSelect = r0;
this.previousSelect = r0;
if (cmdRowSelect != null) { cmdRowSelect.execute(); }
if (this.cmdRowSelect != null) {
this.cmdRowSelect.execute();
}
}
private void editDeck(Deck d0) {
switch(gametype) {
private void editDeck(final Deck d0) {
switch (this.gametype) {
case Quest:
Constant.Runtime.HUMAN_DECK[0] = d0;
final DeckEditorQuest editor = new DeckEditorQuest(AllZone.getQuestData());
editor.show(cmdEditorExit);
editor.show(this.cmdEditorExit);
editor.setVisible(true);
break;
case Constructed:
final DeckEditorConstructed cEditor = new DeckEditorConstructed();
cEditor.show(cmdEditorExit);
cEditor.show(this.cmdEditorExit);
cEditor.getController().load(d0.getName());
cEditor.setVisible(true);
break;
case Sealed:
final DeckEditorLimited sEditor = new DeckEditorLimited(Singletons.getModel().getDecks().getSealed());
sEditor.show(cmdEditorExit);
sEditor.show(this.cmdEditorExit);
sEditor.getController().load(d0.getName());
sEditor.setVisible(true);
break;
case Draft:
final DeckEditorLimited dEditor = new DeckEditorLimited(Singletons.getModel().getDecks().getDraft());
dEditor.show(cmdEditorExit);
dEditor.show(this.cmdEditorExit);
dEditor.getController().load(d0.getName());
dEditor.setVisible(true);
break;
}
}
private void deleteDeck(RowPanel r0) {
Deck d0 = r0.getDeck();
private void deleteDeck(final RowPanel r0) {
final Deck d0 = r0.getDeck();
final int n = JOptionPane.showConfirmDialog(null,
"Are you sure you want to delete \"" + d0.getName()
+ "\" ?", "Delete Deck", JOptionPane.YES_NO_OPTION);
final int n = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete \"" + d0.getName() + "\" ?",
"Delete Deck", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.NO_OPTION) {
return;
@@ -395,18 +461,15 @@ public class DeckLister extends JPanel {
final CardCollections deckManager = Singletons.getModel().getDecks();
if (gametype.equals(GameType.Draft)) {
if (this.gametype.equals(GameType.Draft)) {
deckManager.getDraft().delete(d0.getName());
}
else if (gametype.equals(GameType.Sealed)) {
} else if (this.gametype.equals(GameType.Sealed)) {
deckManager.getSealed().delete(d0.getName());
}
else if (gametype.equals(GameType.Quest)) {
} else if (this.gametype.equals(GameType.Quest)) {
AllZone.getQuestData().getMyDecks().delete(d0.getName());
AllZone.getQuestData().saveData();
Singletons.getView().getViewHome().getBtnQuest().grabFocus();
}
else {
} else {
deckManager.getConstructed().delete(d0.getName());
}
@@ -414,6 +477,8 @@ public class DeckLister extends JPanel {
this.repaintOnlyThisPanel();
this.revalidate();
if (cmdDelete != null) { cmdDelete.execute(); }
if (this.cmdDelete != null) {
this.cmdDelete.execute();
}
}
}