diff --git a/src/main/java/forge/ComputerUtil.java b/src/main/java/forge/ComputerUtil.java index 386a4d5bbf8..9b9a7c57ba7 100644 --- a/src/main/java/forge/ComputerUtil.java +++ b/src/main/java/forge/ComputerUtil.java @@ -1,5 +1,12 @@ package forge; +import static forge.error.ErrorViewer.showError; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; + import forge.Constant.Zone; import forge.card.abilityFactory.AbilityFactory; import forge.card.cardFactory.CardFactoryUtil; @@ -8,54 +15,57 @@ import forge.card.cost.CostUtil; import forge.card.cost.Cost_Payment; import forge.card.mana.ManaCost; import forge.card.mana.ManaPool; -import forge.card.spellability.*; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; - -import static forge.error.ErrorViewer.showError; - +import forge.card.spellability.Ability_Mana; +import forge.card.spellability.SpellAbility; +import forge.card.spellability.Target; /** - *

ComputerUtil class.

- * + *

+ * ComputerUtil class. + *

+ * * @author Forge * @version $Id$ */ public class ComputerUtil { - //if return true, go to next phase + // if return true, go to next phase /** - *

playCards.

- * + *

+ * playCards. + *

+ * * @return a boolean. */ - static public boolean playCards() { + public static boolean playCards() { return playCards(getSpellAbility()); } - //if return true, go to next phase + // if return true, go to next phase /** - *

playCards.

- * - * @param all an array of {@link forge.card.spellability.SpellAbility} objects. + *

+ * playCards. + *

+ * + * @param all + * an array of {@link forge.card.spellability.SpellAbility} + * objects. * @return a boolean. */ - static public boolean playCards(SpellAbility[] all) { - //not sure "playing biggest spell" matters? + public static boolean playCards(final SpellAbility[] all) { + // not sure "playing biggest spell" matters? sortSpellAbilityByCost(all); - // MyRandom.shuffle(all); + // MyRandom.shuffle(all); for (SpellAbility sa : all) { // Don't add Counterspells to the "normal" playcard lookupss AbilityFactory af = sa.getAbilityFactory(); - if (af != null && af.getAPI().equals("Counter")) + if (af != null && af.getAPI().equals("Counter")) { continue; + } sa.setActivatingPlayer(AllZone.getComputerPlayer()); - if (canBePlayedAndPayedByAI(sa)) //checks everything necessary + if (canBePlayedAndPayedByAI(sa)) // checks everything necessary { handlePlayingSpellAbility(sa); @@ -63,33 +73,40 @@ public class ComputerUtil { } } return true; - }//playCards() + }// playCards() /** - *

playCards.

- * - * @param all a {@link java.util.ArrayList} object. + *

+ * playCards. + *

+ * + * @param all + * a {@link java.util.ArrayList} object. * @return a boolean. */ - static public boolean playCards(ArrayList all) { + public static boolean playCards(final ArrayList all) { SpellAbility[] sas = new SpellAbility[all.size()]; for (int i = 0; i < sas.length; i++) { sas[i] = all.get(i); } return playCards(sas); - }//playCards() + } // playCards() /** - *

handlePlayingSpellAbility.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * handlePlayingSpellAbility. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. */ - static public void handlePlayingSpellAbility(SpellAbility sa) { + public static void handlePlayingSpellAbility(final SpellAbility sa) { AllZone.getStack().freezeStack(); Card source = sa.getSourceCard(); - if (sa.isSpell() && !source.isCopiedSpell()) + if (sa.isSpell() && !source.isCopiedSpell()) { AllZone.getGameAction().moveToStack(source); + } Cost cost = sa.getPayCosts(); Target tgt = sa.getTarget(); @@ -100,22 +117,27 @@ public class ComputerUtil { sa.getBeforePayManaAI().execute(); AllZone.getStack().addAndUnfreeze(sa); } else { - if (tgt != null && tgt.doesTarget()) + if (tgt != null && tgt.doesTarget()) { sa.chooseTargetAI(); + } Cost_Payment pay = new Cost_Payment(cost, sa); - if (pay.payComputerCosts()) + if (pay.payComputerCosts()) { AllZone.getStack().addAndUnfreeze(sa); + } } } /** - *

counterSpellRestriction.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * counterSpellRestriction. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. * @return a int. */ - static public int counterSpellRestriction(SpellAbility sa) { + public static int counterSpellRestriction(final SpellAbility sa) { // Move this to AF? // Restriction Level is Based off a handful of factors @@ -129,7 +151,7 @@ public class ComputerUtil { // Play higher costing spells first? Cost cost = sa.getPayCosts(); // Convert cost to CMC - //String totalMana = source.getSVar("PayX"); // + cost.getCMC() + // String totalMana = source.getSVar("PayX"); // + cost.getCMC() // Consider the costs here for relative "scoring" if (CostUtil.hasDiscardHandCost(cost)) { @@ -138,8 +160,9 @@ public class ComputerUtil { } // Abilities before Spells (card advantage) - if (af.isAbility()) + if (af.isAbility()) { restrict += 40; + } // TargetValidTargeting gets biggest bonus if (tgt.getSAValidTargeting() != null) { @@ -154,38 +177,44 @@ public class ComputerUtil { int usableManaSources = CardFactoryUtil.getUsableManaSources(AllZone.getHumanPlayer()); // If the Unless isn't enough, this should be less likely to be used - if (amount > usableManaSources) + if (amount > usableManaSources) { restrict += 20 - (2 * amount); - else + } else { restrict -= (10 - (2 * amount)); + } } // Then base on Targeting Restriction String[] validTgts = tgt.getValidTgts(); - if (validTgts.length != 1 || !validTgts[0].equals("Card")) + if (validTgts.length != 1 || !validTgts[0].equals("Card")) { restrict += 10; + } - // And lastly give some bonus points to least restrictive TargetType (Spell,Ability,Triggered) + // And lastly give some bonus points to least restrictive TargetType + // (Spell,Ability,Triggered) String tgtType = tgt.getTargetSpellAbilityType(); restrict -= (5 * tgtType.split(",").length); return restrict; } - //if return true, go to next phase + // if return true, go to next phase /** - *

playCounterSpell.

- * - * @param possibleCounters a {@link java.util.ArrayList} object. + *

+ * playCounterSpell. + *

+ * + * @param possibleCounters + * a {@link java.util.ArrayList} object. * @return a boolean. */ - static public boolean playCounterSpell(ArrayList possibleCounters) { + public static boolean playCounterSpell(final ArrayList possibleCounters) { SpellAbility bestSA = null; int bestRestriction = Integer.MIN_VALUE; for (SpellAbility sa : possibleCounters) { sa.setActivatingPlayer(AllZone.getComputerPlayer()); - if (canBePlayedAndPayedByAI(sa)) { //checks everything nescessary + if (canBePlayedAndPayedByAI(sa)) { // checks everything nescessary if (bestSA == null) { bestSA = sa; bestRestriction = counterSpellRestriction(sa); @@ -201,8 +230,9 @@ public class ComputerUtil { } } - if (bestSA == null) + if (bestSA == null) { return false; + } // TODO // "Look" at Targeted SA and "calculate" the threshold @@ -211,8 +241,9 @@ public class ComputerUtil { AllZone.getStack().freezeStack(); Card source = bestSA.getSourceCard(); - if (bestSA.isSpell() && !source.isCopiedSpell()) + if (bestSA.isSpell() && !source.isCopiedSpell()) { AllZone.getGameAction().moveToStack(source); + } Cost cost = bestSA.getPayCosts(); @@ -224,25 +255,29 @@ public class ComputerUtil { AllZone.getStack().addAndUnfreeze(bestSA); } else { Cost_Payment pay = new Cost_Payment(cost, bestSA); - if (pay.payComputerCosts()) + if (pay.payComputerCosts()) { AllZone.getStack().addAndUnfreeze(bestSA); + } } return true; - }//playCounterSpell() + }// playCounterSpell() - - //this is used for AI's counterspells + // this is used for AI's counterspells /** - *

playStack.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * playStack. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. */ - final static public void playStack(SpellAbility sa) { + public static final void playStack(final SpellAbility sa) { if (canPayCost(sa)) { Card source = sa.getSourceCard(); - if (sa.isSpell() && !source.isCopiedSpell()) + if (sa.isSpell() && !source.isCopiedSpell()) { AllZone.getGameAction().moveToStack(source); + } sa.setActivatingPlayer(AllZone.getComputerPlayer()); @@ -253,60 +288,69 @@ public class ComputerUtil { } /** - *

playStackFree.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * playStackFree. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. */ - final static public void playStackFree(SpellAbility sa) { + public static final void playStackFree(final SpellAbility sa) { sa.setActivatingPlayer(AllZone.getComputerPlayer()); Card source = sa.getSourceCard(); - if (sa.isSpell() && !source.isCopiedSpell()) + if (sa.isSpell() && !source.isCopiedSpell()) { AllZone.getGameAction().moveToStack(source); + } AllZone.getStack().add(sa); } /** - *

playNoStack.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * playNoStack. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. */ - final static public void playNoStack(SpellAbility sa) { + public static final void playNoStack(final SpellAbility sa) { // TODO: We should really restrict what doesn't use the Stack if (canPayCost(sa)) { Card source = sa.getSourceCard(); - if (sa.isSpell() && !source.isCopiedSpell()) + if (sa.isSpell() && !source.isCopiedSpell()) { AllZone.getGameAction().moveToStack(source); + } sa.setActivatingPlayer(AllZone.getComputerPlayer()); - + Cost cost = sa.getPayCosts(); - if (cost == null) + if (cost == null) { payManaCost(sa); - else { - Cost_Payment pay = new Cost_Payment(cost, sa); - pay.payComputerCosts(); + } else { + Cost_Payment pay = new Cost_Payment(cost, sa); + pay.payComputerCosts(); } AbilityFactory.resolve(sa, false); - //destroys creatures if they have lethal damage, etc.. + // destroys creatures if they have lethal damage, etc.. AllZone.getGameAction().checkStateEffects(); } - }//play() + }// play() - - //gets Spells of cards in hand and Abilities of cards in play - //checks to see - //1. if canPlay() returns true, 2. can pay for mana + // gets Spells of cards in hand and Abilities of cards in play + // checks to see + // 1. if canPlay() returns true, 2. can pay for mana /** - *

getSpellAbility.

- * + *

+ * getSpellAbility. + *

+ * * @return an array of {@link forge.card.spellability.SpellAbility} objects. */ - static public SpellAbility[] getSpellAbility() { + public static SpellAbility[] getSpellAbility() { CardList all = new CardList(); all.addAll(AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield)); all.addAll(AllZone.getComputerPlayer().getCardsIn(Zone.Hand)); @@ -315,7 +359,7 @@ public class ComputerUtil { CardList humanPlayable = new CardList(); humanPlayable.addAll(AllZone.getHumanPlayer().getCardsIn(Zone.Battlefield)); humanPlayable = humanPlayable.filter(new CardListFilter() { - public boolean addCard(Card c) { + public boolean addCard(final Card c) { return (c.canAnyPlayerActivate()); } }); @@ -326,7 +370,10 @@ public class ComputerUtil { for (int outer = 0; outer < all.size(); outer++) { SpellAbility[] sa = all.get(outer).getSpellAbility(); for (int i = 0; i < sa.length; i++) - spellAbility.add(sa[i]);//this seems like it needs to be copied, not sure though + { + spellAbility.add(sa[i]);// this seems like it needs to be + // copied, not sure though + } } SpellAbility[] sa = new SpellAbility[spellAbility.size()]; @@ -334,121 +381,154 @@ public class ComputerUtil { return sa; } - //This is for playing spells regularly (no Cascade/Ripple etc.) + // This is for playing spells regularly (no Cascade/Ripple etc.) /** - *

canBePlayedAndPayedByAI.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * canBePlayedAndPayedByAI. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. * @return a boolean. * @since 1.0.15 */ - static public boolean canBePlayedAndPayedByAI(SpellAbility sa) { + public static boolean canBePlayedAndPayedByAI(final SpellAbility sa) { return sa.canPlay() && sa.canPlayAI() && canPayCost(sa); } /** - *

canPayCost.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * canPayCost. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. * @return a boolean. */ - static public boolean canPayCost(SpellAbility sa) { + public static boolean canPayCost(final SpellAbility sa) { return canPayCost(sa, AllZone.getComputerPlayer()); - }//canPayCost() - + }// canPayCost() /** - *

canPayCost.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. - * @param player a {@link forge.Player} object. + *

+ * canPayCost. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. + * @param player + * a {@link forge.Player} object. * @return a boolean. */ - static public boolean canPayCost(SpellAbility sa, Player player) { - if (!payManaCost(sa, player, true, 0)) + public static boolean canPayCost(final SpellAbility sa, final Player player) { + if (!payManaCost(sa, player, true, 0)) { return false; + } return canPayAdditionalCosts(sa, player); - }//canPayCost() - + }// canPayCost() /** - *

determineLeftoverMana.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * determineLeftoverMana. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. * @return a int. */ - static public int determineLeftoverMana(SpellAbility sa) { + public static int determineLeftoverMana(final SpellAbility sa) { return determineLeftoverMana(sa, AllZone.getComputerPlayer()); } /** - *

determineLeftoverMana.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. - * @param player a {@link forge.Player} object. + *

+ * determineLeftoverMana. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. + * @param player + * a {@link forge.Player} object. * @return a int. * @since 1.0.15 */ - static public int determineLeftoverMana(SpellAbility sa, Player player) { + public static int determineLeftoverMana(final SpellAbility sa, final Player player) { int xMana = 0; for (int i = 1; i < 99; i++) { - if (!payManaCost(sa, player, true, xMana)) + if (!payManaCost(sa, player, true, xMana)) { break; + } xMana = i; } return xMana; } - /** - *

canPayAdditionalCosts.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * canPayAdditionalCosts. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. * @return a boolean. */ - static public boolean canPayAdditionalCosts(SpellAbility sa) { + public static boolean canPayAdditionalCosts(final SpellAbility sa) { return canPayAdditionalCosts(sa, AllZone.getComputerPlayer()); } /** - *

canPayAdditionalCosts.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. - * @param player a {@link forge.Player} object. + *

+ * canPayAdditionalCosts. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. + * @param player + * a {@link forge.Player} object. * @return a boolean. */ - static public boolean canPayAdditionalCosts(SpellAbility sa, Player player) { - if (sa.getActivatingPlayer() == null){ - System.out.println(sa.getSourceCard() + " in ComputerUtil.canPayAdditionalCosts() without an activating player"); + public static boolean canPayAdditionalCosts(final SpellAbility sa, final Player player) { + if (sa.getActivatingPlayer() == null) { + System.out.println(sa.getSourceCard() + + " in ComputerUtil.canPayAdditionalCosts() without an activating player"); sa.setActivatingPlayer(player); } return Cost_Payment.canPayAdditionalCosts(sa.getPayCosts(), sa); } /** - *

payManaCost.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * payManaCost. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. */ - static public void payManaCost(SpellAbility sa) { + public static void payManaCost(final SpellAbility sa) { payManaCost(sa, AllZone.getComputerPlayer(), false, 0); } /** - *

payManaCost.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. - * @param player a {@link forge.Player} object. - * @param test (is for canPayCost, if true does not change the game state) - * @param extraMana a int. + *

+ * payManaCost. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. + * @param player + * a {@link forge.Player} object. + * @param test + * (is for canPayCost, if true does not change the game state) + * @param extraMana + * a int. * @return a boolean. * @since 1.0.15 */ - static public boolean payManaCost(SpellAbility sa, Player player, boolean test, int extraMana) { + public static boolean payManaCost(final SpellAbility sa, final Player player, final boolean test, final int extraMana) { String mana = sa.getPayCosts() != null ? sa.getPayCosts().getTotalMana() : sa.getManaCost(); ManaCost cost = new ManaCost(mana); @@ -462,108 +542,140 @@ public class ComputerUtil { if (sa.getPayCosts() != null && cost.getXcounter() > 0) { int manaToAdd = 0; - if (test && extraMana > 0) + if (test && extraMana > 0) { manaToAdd = extraMana * cost.getXcounter(); - else { + } else { // For Count$xPaid set PayX in the AFs then use that here // Else calculate it as appropriate. String xSvar = card.getSVar("X").equals("Count$xPaid") ? "PayX" : "X"; if (!card.getSVar(xSvar).equals("")) { - if (xSvar.equals("PayX")) - manaToAdd = Integer.parseInt(card.getSVar(xSvar)) * cost.getXcounter(); // X has already been decided - else { + if (xSvar.equals("PayX")) { + manaToAdd = Integer.parseInt(card.getSVar(xSvar)) * cost.getXcounter(); // X + } else { manaToAdd = AbilityFactory.calculateAmount(card, xSvar, sa) * cost.getXcounter(); } } } cost.increaseColorlessMana(manaToAdd); - if (!test) + if (!test) { card.setXManaCostPaid(manaToAdd); + } } - if (cost.isPaid()) + if (cost.isPaid()) { return true; + } ArrayList colors; cost = ((ManaPool) manapool).subtractMana(sa, cost); - if(card.getSVar("ManaNeededToAvoidNegativeEffect") != "") { + if (card.getSVar("ManaNeededToAvoidNegativeEffect") != "") { cost.setManaNeededToAvoidNegativeEffect(card.getSVar("ManaNeededToAvoidNegativeEffect").split(",")); } CardList manaSources = getAvailableMana(); - //this is to prevent errors for mana sources that have abilities that cost mana. + // this is to prevent errors for mana sources that have abilities that + // cost mana. manaSources.remove(sa.getSourceCard()); for (int i = 0; i < manaSources.size(); i++) { Card sourceCard = manaSources.get(i); ArrayList manaAbilities = sourceCard.getAIPlayableMana(); - boolean used = false; //this is for testing paying mana only + boolean used = false; // this is for testing paying mana only manaAbilities = sortForNeeded(cost, manaAbilities, player); for (Ability_Mana m : manaAbilities) { - if (used) break; //mana source already used in the test + if (used) + { + break; // mana source already used in the test + } m.setActivatingPlayer(player); - //if the AI can't pay the additional costs skip the mana ability + // if the AI can't pay the additional costs skip the mana + // ability if (m.getPayCosts() != null) { - if (!canPayAdditionalCosts(m, player)) + if (!canPayAdditionalCosts(m, player)) { continue; - } else if (sourceCard.isTapped()) + } + } else if (sourceCard.isTapped()) { continue; + } - //don't use abilities with dangerous drawbacks - if (m.getSubAbility() != null) - if (!m.getSubAbility().chkAI_Drawback()) + // don't use abilities with dangerous drawbacks + if (m.getSubAbility() != null) { + if (!m.getSubAbility().chkAI_Drawback()) { continue; + } + } colors = getProduceableColors(m, player); for (int j = 0; j < colors.size(); j++) { - if (used) break; //mana source already used in the test + if (used) + { + break; // mana source already used in the test + } if (cost.isNeeded(colors.get(j))) { if (!test) { - //Pay additional costs + // Pay additional costs if (m.getPayCosts() != null) { Cost_Payment pay = new Cost_Payment(m.getPayCosts(), m); - if (!pay.payComputerCosts()) continue; - } else + if (!pay.payComputerCosts()) { + continue; + } + } else { sourceCard.tap(); - } else used = true; // mana source is now used in the test + } + } + else { + used = true; // mana source is now used in the test + } cost.payMana(colors.get(j)); if (!test) { - //resolve subabilities + // resolve subabilities AbilityFactory af = m.getAbilityFactory(); - if (af != null) + if (af != null) { AbilityFactory.resolveSubAbilities(m); + } if (sourceCard.getName().equals("Undiscovered Paradise")) { sourceCard.setBounceAtUntap(true); } if (sourceCard.getName().equals("Rainbow Vale")) { - sourceCard.addExtrinsicKeyword("An opponent gains control of CARDNAME at the beginning of the next end step."); + sourceCard + .addExtrinsicKeyword("An opponent gains control of CARDNAME at the beginning of the next end step."); } - //System.out.println("just subtracted " + colors.get(j) + ", cost is now: " + cost.toString()); - //Run triggers + // System.out.println("just subtracted " + + // colors.get(j) + ", cost is now: " + + // cost.toString()); + // Run triggers HashMap runParams = new HashMap(); runParams.put("Card", sourceCard); runParams.put("Player", player); - runParams.put("Produced", colors.get(j)); //can't tell what mana the computer just paid? + runParams.put("Produced", colors.get(j)); // can't + // tell + // what + // mana + // the + // computer + // just + // paid? AllZone.getTriggerHandler().runTrigger("TapsForMana", runParams); - }//not a test + }// not a test } if (cost.isPaid()) { - //if (sa instanceof Spell_Permanent) // should probably add this - sa.getSourceCard().setColorsPaid(cost.getColorsPaid()); + // if (sa instanceof Spell_Permanent) // should probably + // add this + sa.getSourceCard().setColorsPaid(cost.getColorsPaid()); sa.getSourceCard().setSunburstValue(cost.getSunburst()); manapool.clearPay(sa, test); return true; @@ -573,81 +685,105 @@ public class ComputerUtil { } - if (!test) // real payment should not arrive here - throw new RuntimeException("ComputerUtil : payManaCost() cost was not paid for " + sa.getSourceCard().getName()); + if (!test) { + throw new RuntimeException("ComputerUtil : payManaCost() cost was not paid for " + + sa.getSourceCard().getName()); + } return false; - }//payManaCost() - + }// payManaCost() /** - *

getProduceableColors.

- * - * @param m a {@link forge.card.spellability.Ability_Mana} object. - * @param player a {@link forge.Player} object. + *

+ * getProduceableColors. + *

+ * + * @param m + * a {@link forge.card.spellability.Ability_Mana} object. + * @param player + * a {@link forge.Player} object. * @return a {@link java.util.ArrayList} object. * @since 1.0.15 */ - public static ArrayList getProduceableColors(Ability_Mana m, Player player) { + public static ArrayList getProduceableColors(final Ability_Mana m, final Player player) { ArrayList colors = new ArrayList(); - //if the mana ability is not avaiable move to the next one + // if the mana ability is not avaiable move to the next one m.setActivatingPlayer(player); - if (!m.canPlay()) return colors; + if (!m.canPlay()) { + return colors; + } - if (!colors.contains(Constant.Color.Black) && m.isBasic() && m.mana().equals("B")) + 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")) + } + 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")) + } + 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")) + } + 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")) + } + 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")) + } + if (!colors.contains(Constant.Color.Colorless) && m.isBasic() && m.mana().equals("1")) { colors.add(Constant.Color.Colorless); + } return colors; } /** - *

getAvailableMana.

- * + *

+ * getAvailableMana. + *

+ * * @return a {@link forge.CardList} object. */ - static public CardList getAvailableMana() { + public static CardList getAvailableMana() { return getAvailableMana(AllZone.getComputerPlayer()); - }//getAvailableMana() + }// getAvailableMana() - //gets available mana sources and sorts them + // gets available mana sources and sorts them /** - *

getAvailableMana.

- * - * @param player a {@link forge.Player} object. + *

+ * getAvailableMana. + *

+ * + * @param player + * a {@link forge.Player} object. * @return a {@link forge.CardList} object. */ - static public CardList getAvailableMana(final Player player) { + public static CardList getAvailableMana(final Player player) { CardList list = player.getCardsIn(Zone.Battlefield); CardList manaSources = list.filter(new CardListFilter() { - public boolean addCard(Card c) { + public boolean addCard(final Card c) { for (Ability_Mana am : c.getAIPlayableMana()) { am.setActivatingPlayer(player); - if (am.canPlay()) return true; + if (am.canPlay()) { + return true; + } } return false; } - });//CardListFilter + });// CardListFilter CardList sortedManaSources = new CardList(); - - // 1. Use lands that can only produce colorless mana without drawback/cost first + + // 1. Use lands that can only produce colorless mana without + // drawback/cost first for (int i = 0; i < manaSources.size(); i++) { Card card = manaSources.get(i); - if (card.isCreature() || card.isEnchanted()) continue; //don't use creatures before other permanents + if (card.isCreature() || card.isEnchanted()) + { + continue; // don't use creatures before other permanents + } int usableManaAbilities = 0; boolean needsLimitedResources = false; @@ -658,33 +794,42 @@ public class ComputerUtil { Cost cost = m.getPayCosts(); needsLimitedResources |= !cost.isReusuableResource(); - //if the AI can't pay the additional costs skip the mana ability + // if the AI can't pay the additional costs skip the mana + // ability m.setActivatingPlayer(AllZone.getComputerPlayer()); if (cost != null) { - if (!canPayAdditionalCosts(m, player)) + if (!canPayAdditionalCosts(m, player)) { continue; + } } - //don't use abilities with dangerous drawbacks + // don't use abilities with dangerous drawbacks if (m.getSubAbility() != null) { - if (!m.getSubAbility().chkAI_Drawback()) + if (!m.getSubAbility().chkAI_Drawback()) { continue; - needsLimitedResources = true; //TODO: check for good drawbacks (gainLife) + } + needsLimitedResources = true; // TODO: check for good + // drawbacks (gainLife) } usableManaAbilities++; } - - //use lands that can only produce colorless mana first - if (usableManaAbilities == 1 && !needsLimitedResources && manaAbilities.get(0).mana().equals("1")) - sortedManaSources.add(card); + + // use lands that can only produce colorless mana first + if (usableManaAbilities == 1 && !needsLimitedResources && manaAbilities.get(0).mana().equals("1")) { + sortedManaSources.add(card); + } } - // 2. Search for mana sources that have a certain number of mana abilities (start with 1 and go up to 5) and no drawback/costs - for (int number = 1; number < 6; number++) + // 2. Search for mana sources that have a certain number of mana + // abilities (start with 1 and go up to 5) and no drawback/costs + for (int number = 1; number < 6; number++) { for (int i = 0; i < manaSources.size(); i++) { Card card = manaSources.get(i); - if (card.isCreature() || card.isEnchanted()) continue; //don't use creatures before other permanents + if (card.isCreature() || card.isEnchanted()) + { + continue; // don't use creatures before other permanents + } int usableManaAbilities = 0; boolean needsLimitedResources = false; @@ -694,48 +839,61 @@ public class ComputerUtil { Cost cost = m.getPayCosts(); needsLimitedResources |= !cost.isReusuableResource(); - //if the AI can't pay the additional costs skip the mana ability + // if the AI can't pay the additional costs skip the mana + // ability if (cost != null) { - if (!canPayAdditionalCosts(m, player)) + if (!canPayAdditionalCosts(m, player)) { continue; + } } - //don't use abilities with dangerous drawbacks + // don't use abilities with dangerous drawbacks if (m.getSubAbility() != null) { - if (!m.getSubAbility().chkAI_Drawback()) + if (!m.getSubAbility().chkAI_Drawback()) { continue; - needsLimitedResources = true; //TODO: check for good drawbacks (gainLife) + } + needsLimitedResources = true; // TODO: check for good + // drawbacks (gainLife) } usableManaAbilities++; } - if (usableManaAbilities == number && !needsLimitedResources && !sortedManaSources.contains(card)) + if (usableManaAbilities == number && !needsLimitedResources && !sortedManaSources.contains(card)) { sortedManaSources.add(card); + } } + } - //Add the rest + // Add the rest for (int j = 0; j < manaSources.size(); j++) { - if (!sortedManaSources.contains(manaSources.get(j))) + if (!sortedManaSources.contains(manaSources.get(j))) { sortedManaSources.add(manaSources.get(j)); + } } return sortedManaSources; - }//getAvailableMana() + }// getAvailableMana() // sorts the most needed mana abilities to come first /** - *

sortForNeeded.

- * - * @param cost a {@link forge.card.mana.ManaCost} object. - * @param manaAbilities a {@link java.util.ArrayList} object. - * @param player a {@link forge.Player} object. + *

+ * sortForNeeded. + *

+ * + * @param cost + * a {@link forge.card.mana.ManaCost} object. + * @param manaAbilities + * a {@link java.util.ArrayList} object. + * @param player + * a {@link forge.Player} object. * @return a {@link java.util.ArrayList} object. * @since 1.0.15 */ - static public ArrayList sortForNeeded(ManaCost cost, ArrayList manaAbilities, Player player) { + public static ArrayList sortForNeeded(final ManaCost cost, final ArrayList manaAbilities, + final Player player) { ArrayList colors; - + ArrayList colorsNeededToAvoidNegativeEffect = cost.getManaNeededToAvoidNegativeEffect(); ArrayList res = new ArrayList(); @@ -751,8 +909,8 @@ public class ComputerUtil { res.add(am); break; } - for(String col : colorsNeededToAvoidNegativeEffect) { - if(col.equalsIgnoreCase(colors.get(j)) + for (String col : colorsNeededToAvoidNegativeEffect) { + if (col.equalsIgnoreCase(colors.get(j)) || CardUtil.getShortColor(col).equalsIgnoreCase(colors.get(j))) { res.add(am); } @@ -762,7 +920,9 @@ public class ComputerUtil { for (Ability_Mana am : manaAbilities) { - if (res.contains(am)) break; + if (res.contains(am)) { + break; + } colors = getProduceableColors(am, player); for (int j = 0; j < colors.size(); j++) { @@ -770,8 +930,8 @@ public class ComputerUtil { res.add(am); break; } - for(String col : colorsNeededToAvoidNegativeEffect) { - if(col.equalsIgnoreCase(colors.get(j)) + for (String col : colorsNeededToAvoidNegativeEffect) { + if (col.equalsIgnoreCase(colors.get(j)) || CardUtil.getShortColor(col).equalsIgnoreCase(colors.get(j))) { res.add(am); } @@ -782,55 +942,59 @@ public class ComputerUtil { return res; } - - //plays a land if one is available + // plays a land if one is available /** - *

chooseLandsToPlay.

- * + *

+ * chooseLandsToPlay. + *

+ * * @return a boolean. */ - static public boolean chooseLandsToPlay() { + public static boolean chooseLandsToPlay() { Player computer = AllZone.getComputerPlayer(); CardList landList = computer.getCardsIn(Zone.Hand); landList = landList.filter(CardListFilter.lands); - CardList lands = computer.getCardsIn(Zone.Graveyard).getType("Land"); - for (Card crd : lands){ - if (crd.isLand() && crd.hasStartOfKeyword("May be played")) - landList.add(crd); + for (Card crd : lands) { + if (crd.isLand() && crd.hasStartOfKeyword("May be played")) { + landList.add(crd); + } } landList = landList.filter(new CardListFilter() { - public boolean addCard(Card c) { + public boolean addCard(final Card c) { if (c.getSVar("NeedsToPlay").length() > 0) { String needsToPlay = c.getSVar("NeedsToPlay"); CardList list = AllZoneUtil.getCardsIn(Zone.Battlefield); list = list.getValidCards(needsToPlay.split(","), c.getController(), c); - if (list.isEmpty()) return false; - } - if (c.isType("Legendary") - && !c.getName().equals("Flagstones of Trokair")) { - CardList list = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield); - if (list.containsName(c.getName())) + if (list.isEmpty()) { return false; + } } - - //don't play the land if it has cycling and enough lands are available + if (c.isType("Legendary") && !c.getName().equals("Flagstones of Trokair")) { + CardList list = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield); + if (list.containsName(c.getName())) { + return false; + } + } + + // don't play the land if it has cycling and enough lands are + // available ArrayList spellAbilities = c.getSpellAbilities(); - for (SpellAbility sa : spellAbilities) - if (sa.isCycling()) { - CardList hand = AllZone.getComputerPlayer().getCardsIn(Zone.Hand); + for (SpellAbility sa : spellAbilities) + if (sa.isCycling()) { + CardList hand = AllZone.getComputerPlayer().getCardsIn(Zone.Hand); CardList lands = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield); lands.addAll(hand); lands = lands.getType("Land"); - if (lands.size() >= Math.max(hand.getHighestConvertedManaCost(), 6)) + if (lands.size() >= Math.max(hand.getHighestConvertedManaCost(), 6)) { return false; - } - - + } + } + return true; } }); @@ -839,30 +1003,37 @@ public class ComputerUtil { // play as many lands as you can int ix = 0; while (landList.get(ix).isReflectedLand() && (ix + 1 < landList.size())) { - // Skip through reflected lands. Choose last if they are all reflected. + // Skip through reflected lands. Choose last if they are all + // reflected. ix++; } Card land = landList.get(ix); landList.remove(ix); computer.playLand(land); - - if (AllZone.getStack().size() != 0) - return true; + + if (AllZone.getStack().size() != 0) { + return true; + } } return false; } /** - *

getCardPreference.

- * - * @param activate a {@link forge.Card} object. - * @param pref a {@link java.lang.String} object. - * @param typeList a {@link forge.CardList} object. + *

+ * getCardPreference. + *

+ * + * @param activate + * a {@link forge.Card} object. + * @param pref + * a {@link java.lang.String} object. + * @param typeList + * a {@link forge.CardList} object. * @return a {@link forge.Card} object. */ - static public Card getCardPreference(Card activate, String pref, CardList typeList) { - + public static Card getCardPreference(final Card activate, final String pref, final CardList typeList) { + if (activate != null) { String[] prefValid = activate.getSVar("AIPreference").split("\\$"); if (prefValid[0].equals(pref)) { @@ -874,10 +1045,11 @@ public class ComputerUtil { } } if (pref.contains("SacCost")) { // search for permanents with SacMe - for (int ip = 0; ip < 9; ip++) { // priority 0 is the lowest, priority 5 the highest + for (int ip = 0; ip < 9; ip++) { // priority 0 is the lowest, + // priority 5 the highest final int priority = 9 - ip; CardList SacMeList = typeList.filter(new CardListFilter() { - public boolean addCard(Card c) { + public boolean addCard(final Card c) { return (!c.getSVar("SacMe").equals("") && Integer.parseInt(c.getSVar("SacMe")) == priority); } }); @@ -887,12 +1059,14 @@ public class ComputerUtil { } } } - - if (pref.contains("DiscardCost")) { // search for permanents with DiscardMe - for (int ip = 0; ip < 9; ip++) { // priority 0 is the lowest, priority 5 the highest + + if (pref.contains("DiscardCost")) { // search for permanents with + // DiscardMe + for (int ip = 0; ip < 9; ip++) { // priority 0 is the lowest, + // priority 5 the highest final int priority = 9 - ip; CardList SacMeList = typeList.filter(new CardListFilter() { - public boolean addCard(Card c) { + public boolean addCard(final Card c) { return (!c.getSVar("DiscardMe").equals("") && Integer.parseInt(c.getSVar("DiscardMe")) == priority); } }); @@ -902,27 +1076,36 @@ public class ComputerUtil { } } } - + return null; } /** - *

chooseSacrificeType.

- * - * @param type a {@link java.lang.String} object. - * @param activate a {@link forge.Card} object. - * @param target a {@link forge.Card} object. - * @param amount a int. + *

+ * chooseSacrificeType. + *

+ * + * @param type + * a {@link java.lang.String} object. + * @param activate + * a {@link forge.Card} object. + * @param target + * a {@link forge.Card} object. + * @param amount + * a int. * @return a {@link forge.CardList} object. */ - static public CardList chooseSacrificeType(String type, Card activate, Card target, int amount) { + public static CardList chooseSacrificeType(final String type, final Card activate, final Card target, final int amount) { CardList typeList = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield); typeList = typeList.getValidCards(type.split(","), activate.getController(), activate); if (target != null && target.getController().isComputer() && typeList.contains(target)) - typeList.remove(target); // don't sacrifice the card we're pumping + { + typeList.remove(target); // don't sacrifice the card we're pumping + } - if (typeList.size() < amount) + if (typeList.size() < amount) { return null; + } CardList sacList = new CardList(); int count = 0; @@ -933,30 +1116,37 @@ public class ComputerUtil { sacList.add(prefCard); typeList.remove(prefCard); count++; - } else + } else { break; + } } CardListUtil.sortAttackLowFirst(typeList); - for (int i = count; i < amount; i++) sacList.add(typeList.get(i)); + for (int i = count; i < amount; i++) { + sacList.add(typeList.get(i)); + } return sacList; } - - /** - *

AI_discardNumType.

- * - * @param numDiscard a int. - * @param uTypes an array of {@link java.lang.String} objects. May be null for no restrictions. - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * AI_discardNumType. + *

+ * + * @param numDiscard + * a int. + * @param uTypes + * an array of {@link java.lang.String} objects. May be null for + * no restrictions. + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. * @return a CardList of discarded cards. */ - static public CardList AI_discardNumType(int numDiscard, String[] uTypes, SpellAbility sa) { + public static CardList AI_discardNumType(final int numDiscard, final String[] uTypes, final SpellAbility sa) { CardList hand = AllZone.getComputerPlayer().getCardsIn(Zone.Hand); Card sourceCard = null; - + if (uTypes != null && sa != null) { hand = hand.getValidCards(uTypes, sa.getActivatingPlayer(), sa.getSourceCard()); } @@ -964,13 +1154,13 @@ public class ComputerUtil { sourceCard = sa.getSourceCard(); } - if (hand.size() < numDiscard){ + if (hand.size() < numDiscard) { return null; } - + CardList discardList = new CardList(); int count = 0; - + // look for good discards while (count < numDiscard) { Card prefCard = getCardPreference(sourceCard, "DiscardCost", hand); @@ -978,13 +1168,14 @@ public class ComputerUtil { discardList.add(prefCard); hand.remove(prefCard); count++; - } else + } else { break; + } } - + int discardsLeft = numDiscard - count; - - // chose rest + + // chose rest for (int i = 0; i < discardsLeft; i++) { if (hand.size() <= 0) { continue; @@ -992,154 +1183,211 @@ public class ComputerUtil { CardList landsInPlay = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield).getType("Land"); if (landsInPlay.size() > 5) { CardList landsInHand = hand.getType("Land"); - if (landsInHand.size() > 0) { //discard lands + if (landsInHand.size() > 0) { // discard lands discardList.add(landsInHand.get(0)); hand.remove(landsInHand.get(0)); - } else { //discard low costed stuff - CardListUtil.sortCMC(hand); + } else { // discard low costed stuff + CardListUtil.sortCMC(hand); hand.reverse(); discardList.add(hand.get(0)); hand.remove(hand.get(0)); } - } else { //discard high costed stuff + } else { // discard high costed stuff CardListUtil.sortCMC(hand); discardList.add(hand.get(0)); hand.remove(hand.get(0)); } } - + return discardList; } /** - *

chooseExileType.

- * - * @param type a {@link java.lang.String} object. - * @param activate a {@link forge.Card} object. - * @param target a {@link forge.Card} object. - * @param amount a int. + *

+ * chooseExileType. + *

+ * + * @param type + * a {@link java.lang.String} object. + * @param activate + * a {@link forge.Card} object. + * @param target + * a {@link forge.Card} object. + * @param amount + * a int. * @return a {@link forge.CardList} object. */ - static public CardList chooseExileType(String type, Card activate, Card target, int amount) { + public static CardList chooseExileType(final String type, final Card activate, final Card target, final int amount) { return chooseExileFrom(Constant.Zone.Battlefield, type, activate, target, amount); } /** - *

chooseExileFromHandType.

- * - * @param type a {@link java.lang.String} object. - * @param activate a {@link forge.Card} object. - * @param target a {@link forge.Card} object. - * @param amount a int. + *

+ * chooseExileFromHandType. + *

+ * + * @param type + * a {@link java.lang.String} object. + * @param activate + * a {@link forge.Card} object. + * @param target + * a {@link forge.Card} object. + * @param amount + * a int. * @return a {@link forge.CardList} object. */ - static public CardList chooseExileFromHandType(String type, Card activate, Card target, int amount) { + public static CardList chooseExileFromHandType(final String type, final Card activate, final Card target, final int amount) { return chooseExileFrom(Constant.Zone.Hand, type, activate, target, amount); } /** - *

chooseExileFromGraveType.

- * - * @param type a {@link java.lang.String} object. - * @param activate a {@link forge.Card} object. - * @param target a {@link forge.Card} object. - * @param amount a int. + *

+ * chooseExileFromGraveType. + *

+ * + * @param type + * a {@link java.lang.String} object. + * @param activate + * a {@link forge.Card} object. + * @param target + * a {@link forge.Card} object. + * @param amount + * a int. * @return a {@link forge.CardList} object. */ - static public CardList chooseExileFromGraveType(String type, Card activate, Card target, int amount) { + public static CardList chooseExileFromGraveType(final String type, final Card activate, final Card target, final int amount) { return chooseExileFrom(Constant.Zone.Graveyard, type, activate, target, amount); } /** - *

chooseExileFrom.

- * - * @param zone a {@link java.lang.String} object. - * @param type a {@link java.lang.String} object. - * @param activate a {@link forge.Card} object. - * @param target a {@link forge.Card} object. - * @param amount a int. + *

+ * chooseExileFrom. + *

+ * + * @param zone + * a {@link java.lang.String} object. + * @param type + * a {@link java.lang.String} object. + * @param activate + * a {@link forge.Card} object. + * @param target + * a {@link forge.Card} object. + * @param amount + * a int. * @return a {@link forge.CardList} object. */ - static public CardList chooseExileFrom(Constant.Zone zone, String type, Card activate, Card target, int amount) { + public static CardList chooseExileFrom(final Constant.Zone zone, final String type, final Card activate, final Card target, final int amount) { CardList typeList = AllZone.getComputerPlayer().getCardsIn(zone); typeList = typeList.getValidCards(type.split(","), activate.getController(), activate); if (target != null && target.getController().isComputer() && typeList.contains(target)) - typeList.remove(target); // don't exile the card we're pumping + { + typeList.remove(target); // don't exile the card we're pumping + } - if (typeList.size() < amount) + if (typeList.size() < amount) { return null; + } CardListUtil.sortAttackLowFirst(typeList); CardList exileList = new CardList(); - for (int i = 0; i < amount; i++) exileList.add(typeList.get(i)); + for (int i = 0; i < amount; i++) { + exileList.add(typeList.get(i)); + } return exileList; } /** - *

chooseTapType.

- * - * @param type a {@link java.lang.String} object. - * @param activate a {@link forge.Card} object. - * @param tap a boolean. - * @param amount a int. + *

+ * chooseTapType. + *

+ * + * @param type + * a {@link java.lang.String} object. + * @param activate + * a {@link forge.Card} object. + * @param tap + * a boolean. + * @param amount + * a int. * @return a {@link forge.CardList} object. */ - static public CardList chooseTapType(String type, Card activate, boolean tap, int amount) { + public static CardList chooseTapType(final String type, final Card activate, final boolean tap, final int amount) { CardList typeList = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield); typeList = typeList.getValidCards(type.split(","), activate.getController(), activate); - //is this needed? + // is this needed? typeList = typeList.filter(CardListFilter.untapped); - if (tap) + if (tap) { typeList.remove(activate); + } - if (typeList.size() < amount) + if (typeList.size() < amount) { return null; + } CardListUtil.sortAttackLowFirst(typeList); CardList tapList = new CardList(); - for (int i = 0; i < amount; i++) tapList.add(typeList.get(i)); + for (int i = 0; i < amount; i++) { + tapList.add(typeList.get(i)); + } return tapList; } /** - *

chooseReturnType.

- * - * @param type a {@link java.lang.String} object. - * @param activate a {@link forge.Card} object. - * @param target a {@link forge.Card} object. - * @param amount a int. + *

+ * chooseReturnType. + *

+ * + * @param type + * a {@link java.lang.String} object. + * @param activate + * a {@link forge.Card} object. + * @param target + * a {@link forge.Card} object. + * @param amount + * a int. * @return a {@link forge.CardList} object. */ - static public CardList chooseReturnType(String type, Card activate, Card target, int amount) { + public static CardList chooseReturnType(final String type, final Card activate, final Card target, final int amount) { CardList typeList = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield); typeList = typeList.getValidCards(type.split(","), activate.getController(), activate); - if (target != null && target.getController().isComputer() && typeList.contains(target)) // don't bounce the card we're pumping + if (target != null && target.getController().isComputer() && typeList.contains(target)) { + // bounce + // the + // card + // we're + // pumping typeList.remove(target); + } - if (typeList.size() < amount) + if (typeList.size() < amount) { return null; + } CardListUtil.sortAttackLowFirst(typeList); CardList returnList = new CardList(); - for (int i = 0; i < amount; i++) returnList.add(typeList.get(i)); + for (int i = 0; i < amount; i++) { + returnList.add(typeList.get(i)); + } return returnList; } /** - *

getPossibleAttackers.

- * + *

+ * getPossibleAttackers. + *

+ * * @return a {@link forge.CardList} object. */ - static public CardList getPossibleAttackers() { + public static CardList getPossibleAttackers() { CardList list = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield); list = list.filter(new CardListFilter() { - public boolean addCard(Card c) { + public boolean addCard(final Card c) { return CombatUtil.canAttack(c); } }); @@ -1147,11 +1395,13 @@ public class ComputerUtil { } /** - *

getAttackers.

- * + *

+ * getAttackers. + *

+ * * @return a {@link forge.Combat} object. */ - static public Combat getAttackers() { + public static Combat getAttackers() { ComputerUtil_Attack2 att = new ComputerUtil_Attack2(AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield), AllZone.getHumanPlayer().getCardsIn(Zone.Battlefield), AllZone.getHumanPlayer().getLife()); @@ -1159,64 +1409,77 @@ public class ComputerUtil { } /** - *

getBlockers.

- * + *

+ * getBlockers. + *

+ * * @return a {@link forge.Combat} object. */ - static public Combat getBlockers() { + public static Combat getBlockers() { CardList blockers = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield); return ComputerUtil_Block2.getBlockers(AllZone.getCombat(), blockers); } /** - *

sortSpellAbilityByCost.

- * - * @param sa an array of {@link forge.card.spellability.SpellAbility} objects. + *

+ * sortSpellAbilityByCost. + *

+ * + * @param sa + * an array of {@link forge.card.spellability.SpellAbility} + * objects. */ - static void sortSpellAbilityByCost(SpellAbility sa[]) { - //sort from highest cost to lowest - //we want the highest costs first + static void sortSpellAbilityByCost(final SpellAbility[] sa) { + // sort from highest cost to lowest + // we want the highest costs first Comparator c = new Comparator() { - public int compare(SpellAbility a, SpellAbility b) { + public int compare(final SpellAbility a, final SpellAbility b) { int a1 = CardUtil.getConvertedManaCost(a); int b1 = CardUtil.getConvertedManaCost(b); - //puts creatures in front of spells - if (a.getSourceCard().isCreature()) + // puts creatures in front of spells + if (a.getSourceCard().isCreature()) { a1 += 1; + } - if (b.getSourceCard().isCreature()) + if (b.getSourceCard().isCreature()) { b1 += 1; + } - //sort planeswalker abilities for ultimate - if(a.getRestrictions().getPlaneswalker() && b.getRestrictions().getPlaneswalker()) { - if(a.getAbilityFactory() != null && a.getAbilityFactory().getMapParams().containsKey("Ultimate")) { + // sort planeswalker abilities for ultimate + if (a.getRestrictions().getPlaneswalker() && b.getRestrictions().getPlaneswalker()) { + if (a.getAbilityFactory() != null && a.getAbilityFactory().getMapParams().containsKey("Ultimate")) { a1 += 1; - } - else if(b.getAbilityFactory() != null && b.getAbilityFactory().getMapParams().containsKey("Ultimate")) { + } else if (b.getAbilityFactory() != null + && b.getAbilityFactory().getMapParams().containsKey("Ultimate")) { b1 += 1; } } return b1 - a1; } - };//Comparator + };// Comparator Arrays.sort(sa, c); - }//sortSpellAbilityByCost() + }// sortSpellAbilityByCost() /** - *

sacrificePermanents.

- * - * @param amount a int. - * @param list a {@link forge.CardList} object. + *

+ * sacrificePermanents. + *

+ * + * @param amount + * a int. + * @param list + * a {@link forge.CardList} object. */ - static public CardList sacrificePermanents(int amount, CardList list) { + public static CardList sacrificePermanents(final int amount, final CardList list) { CardList sacList = new CardList(); // used in Annihilator and AF_Sacrifice int max = list.size(); - if (max > amount) + if (max > amount) { max = amount; + } CardListUtil.sortCMC(list); list.reverse(); @@ -1254,42 +1517,53 @@ public class ComputerUtil { } /** - *

canRegenerate.

- * - * @param card a {@link forge.Card} object. + *

+ * canRegenerate. + *

+ * + * @param card + * a {@link forge.Card} object. * @return a boolean. */ - public static boolean canRegenerate(Card card) { + public static boolean canRegenerate(final Card card) { - if (card.hasKeyword("CARDNAME can't be regenerated.")) return false; + if (card.hasKeyword("CARDNAME can't be regenerated.")) { + return false; + } Player controller = card.getController(); CardList l = controller.getCardsIn(Zone.Battlefield); for (Card c : l) - for (SpellAbility sa : c.getSpellAbility()){ - //This try/catch should fix the "computer is thinking" bug + for (SpellAbility sa : c.getSpellAbility()) { + // This try/catch should fix the "computer is thinking" bug try { - AbilityFactory af = sa.getAbilityFactory(); - - if (!sa.isAbility() || af == null || !af.getAPI().equals("Regenerate")) - continue; // Not a Regenerate ability - - //sa.setActivatingPlayer(controller); - if (!(sa.canPlay() && ComputerUtil.canPayCost(sa, controller))) - continue; // Can't play ability - - HashMap mapParams = af.getMapParams(); - - Target tgt = sa.getTarget(); - if (tgt != null){ - if (AllZoneUtil.getCardsIn(Zone.Battlefield).getValidCards(tgt.getValidTgts(), controller, sa.getSourceCard()).contains(card)) - return true; + AbilityFactory af = sa.getAbilityFactory(); + + if (!sa.isAbility() || af == null || !af.getAPI().equals("Regenerate")) + { + continue; // Not a Regenerate ability } - else if (AbilityFactory.getDefinedCards(sa.getSourceCard(), mapParams.get("Defined"), sa).contains(card)) + + // sa.setActivatingPlayer(controller); + if (!(sa.canPlay() && ComputerUtil.canPayCost(sa, controller))) + { + continue; // Can't play ability + } + + HashMap mapParams = af.getMapParams(); + + Target tgt = sa.getTarget(); + if (tgt != null) { + if (AllZoneUtil.getCardsIn(Zone.Battlefield) + .getValidCards(tgt.getValidTgts(), controller, sa.getSourceCard()).contains(card)) { + return true; + } + } else if (AbilityFactory.getDefinedCards(sa.getSourceCard(), mapParams.get("Defined"), sa) + .contains(card)) { return true; - - } - catch (Exception ex) { + } + + } catch (Exception ex) { showError(ex, "There is an error in the card code for %s:%n", c.getName(), ex.getMessage()); } } @@ -1298,12 +1572,15 @@ public class ComputerUtil { } /** - *

possibleDamagePrevention.

- * - * @param card a {@link forge.Card} object. + *

+ * possibleDamagePrevention. + *

+ * + * @param card + * a {@link forge.Card} object. * @return a int. */ - public static int possibleDamagePrevention(Card card) { + public static int possibleDamagePrevention(final Card card) { int prevented = 0; @@ -1312,19 +1589,25 @@ public class ComputerUtil { for (Card c : l) for (SpellAbility sa : c.getSpellAbility()) // if SA is from AF_Counter don't add to getPlayable - //This try/catch should fix the "computer is thinking" bug + // This try/catch should fix the "computer is thinking" bug try { if (sa.getAbilityFactory() != null && sa.isAbility()) { AbilityFactory af = sa.getAbilityFactory(); HashMap mapParams = af.getMapParams(); - if (mapParams.get("AB").equals("PreventDamage") && sa.canPlay() && ComputerUtil.canPayCost(sa, controller)) { - if (AbilityFactory.getDefinedCards(sa.getSourceCard(), mapParams.get("Defined"), sa).contains(card)) - prevented += AbilityFactory.calculateAmount(af.getHostCard(), mapParams.get("Amount"), sa); + if (mapParams.get("AB").equals("PreventDamage") && sa.canPlay() + && ComputerUtil.canPayCost(sa, controller)) { + if (AbilityFactory.getDefinedCards(sa.getSourceCard(), mapParams.get("Defined"), sa) + .contains(card)) { + prevented += AbilityFactory.calculateAmount(af.getHostCard(), mapParams.get("Amount"), + sa); + } Target tgt = sa.getTarget(); if (tgt != null) { - if (AllZoneUtil.getCardsIn(Zone.Battlefield).getValidCards(tgt.getValidTgts(), controller, af.getHostCard()) - .contains(card)) - prevented += AbilityFactory.calculateAmount(af.getHostCard(), mapParams.get("Amount"), sa); + if (AllZoneUtil.getCardsIn(Zone.Battlefield) + .getValidCards(tgt.getValidTgts(), controller, af.getHostCard()).contains(card)) { + prevented += AbilityFactory.calculateAmount(af.getHostCard(), + mapParams.get("Amount"), sa); + } } } diff --git a/src/main/java/forge/ComputerUtil_Attack2.java b/src/main/java/forge/ComputerUtil_Attack2.java index 0da0e98272d..12a2516b596 100644 --- a/src/main/java/forge/ComputerUtil_Attack2.java +++ b/src/main/java/forge/ComputerUtil_Attack2.java @@ -1,23 +1,25 @@ package forge; -import forge.Constant.Zone; -import forge.card.cardFactory.CardFactoryUtil; -import forge.card.trigger.Trigger; - import java.util.ArrayList; import java.util.HashMap; import java.util.Random; +import forge.Constant.Zone; +import forge.card.cardFactory.CardFactoryUtil; +import forge.card.trigger.Trigger; + //doesHumanAttackAndWin() uses the global variable AllZone.getComputerPlayer() /** - *

ComputerUtil_Attack2 class.

- * + *

+ * ComputerUtil_Attack2 class. + *

+ * * @author Forge * @version $Id$ */ public class ComputerUtil_Attack2 { - //possible attackers and blockers + // possible attackers and blockers private CardList attackers; private CardList blockers; private CardList playerCreatures; @@ -26,30 +28,42 @@ public class ComputerUtil_Attack2 { private Random random = MyRandom.random; private final int randomInt = random.nextInt(); - private CardList humanList; //holds human player creatures - private CardList computerList; //holds computer creatures + private CardList humanList; // holds human player creatures + private CardList computerList; // holds computer creatures - private int aiAggression = 0; // added by Masher, how aggressive the ai attack will be depending on circumstances + private int aiAggression = 0; // added by Masher, how aggressive the ai + // attack will be depending on circumstances /** - *

Constructor for ComputerUtil_Attack2.

- * - * @param possibleAttackers an array of {@link forge.Card} objects. - * @param possibleBlockers an array of {@link forge.Card} objects. - * @param blockerLife a int. + *

+ * Constructor for ComputerUtil_Attack2. + *

+ * + * @param possibleAttackers + * an array of {@link forge.Card} objects. + * @param possibleBlockers + * an array of {@link forge.Card} objects. + * @param blockerLife + * a int. */ - public ComputerUtil_Attack2(Card[] possibleAttackers, Card[] possibleBlockers, int blockerLife) { + public ComputerUtil_Attack2(final Card[] possibleAttackers, final Card[] possibleBlockers, final int blockerLife) { this(new CardList(possibleAttackers), new CardList(possibleBlockers), blockerLife); } /** - *

Constructor for ComputerUtil_Attack2.

- * - * @param possibleAttackers a {@link forge.CardList} object. - * @param possibleBlockers a {@link forge.CardList} object. - * @param blockerLife a int. + *

+ * Constructor for ComputerUtil_Attack2. + *

+ * + * @param possibleAttackers + * a {@link forge.CardList} object. + * @param possibleBlockers + * a {@link forge.CardList} object. + * @param blockerLife + * a int. */ - public ComputerUtil_Attack2(final CardList possibleAttackers, CardList possibleBlockers, int blockerLife) { + public ComputerUtil_Attack2(final CardList possibleAttackers, + final CardList possibleBlockers, final int blockerLife) { humanList = new CardList(possibleBlockers.toArray()); humanList = humanList.getType("Creature"); @@ -61,18 +75,21 @@ public class ComputerUtil_Attack2 { attackers = getPossibleAttackers(possibleAttackers); blockers = getPossibleBlockers(possibleBlockers, attackers); this.blockerLife = blockerLife; - } //constructor + } // constructor /** - *

sortAttackers.

- * - * @param in a {@link forge.CardList} object. + *

+ * sortAttackers. + *

+ * + * @param in + * a {@link forge.CardList} object. * @return a {@link forge.CardList} object. */ public final CardList sortAttackers(final CardList in) { CardList list = new CardList(); - //Cards with triggers should come first (for Battle Cry) + // Cards with triggers should come first (for Battle Cry) for (Card attacker : in) { ArrayList registeredTriggers = attacker.getTriggers(); for (Trigger trigger : registeredTriggers) { @@ -90,19 +107,23 @@ public class ComputerUtil_Attack2 { } return list; - } //sortAttackers() + } // sortAttackers() - //Is there any reward for attacking? (for 0/1 creatures there is not) + // Is there any reward for attacking? (for 0/1 creatures there is not) /** - *

isEffectiveAttacker.

- * - * @param attacker a {@link forge.Card} object. - * @param combat a {@link forge.Combat} object. + *

+ * isEffectiveAttacker. + *

+ * + * @param attacker + * a {@link forge.Card} object. + * @param combat + * a {@link forge.Combat} object. * @return a boolean. */ - public final boolean isEffectiveAttacker(final Card attacker, Combat combat) { + public final boolean isEffectiveAttacker(final Card attacker, final Combat combat) { - //if the attacker will die when attacking don't attack + // if the attacker will die when attacking don't attack if (attacker.getNetDefense() + CombatUtil.predictToughnessBonusOfAttacker(attacker, null, combat) <= 0) { return false; } @@ -113,10 +134,10 @@ public class ComputerUtil_Attack2 { if (CombatUtil.poisonIfUnblocked(attacker, AllZone.getHumanPlayer(), combat) > 0) { return true; } - + CardList controlledByCompy = AllZone.getComputerPlayer().getAllCards(); - for(Card c : controlledByCompy) { + for (Card c : controlledByCompy) { for (Trigger trigger : c.getTriggers()) { if (CombatUtil.combatTriggerWillTrigger(attacker, null, trigger, combat)) { return true; @@ -128,12 +149,15 @@ public class ComputerUtil_Attack2 { } /** - *

getPossibleAttackers.

- * - * @param in a {@link forge.CardList} object. + *

+ * getPossibleAttackers. + *

+ * + * @param in + * a {@link forge.CardList} object. * @return a {@link forge.CardList} object. */ - public CardList getPossibleAttackers(CardList in) { + public final CardList getPossibleAttackers(final CardList in) { CardList list = new CardList(in.toArray()); list = list.filter(new CardListFilter() { public boolean addCard(final Card c) { @@ -141,16 +165,20 @@ public class ComputerUtil_Attack2 { } }); return list; - } //getPossibleAttackers() + } // getPossibleAttackers() /** - *

getPossibleBlockers.

- * - * @param blockers a {@link forge.CardList} object. - * @param attackers a {@link forge.CardList} object. + *

+ * getPossibleBlockers. + *

+ * + * @param blockers + * a {@link forge.CardList} object. + * @param attackers + * a {@link forge.CardList} object. * @return a {@link forge.CardList} object. */ - public final CardList getPossibleBlockers(CardList blockers, CardList attackers) { + public final CardList getPossibleBlockers(final CardList blockers, CardList attackers) { CardList possibleBlockers = new CardList(blockers.toArray()); final CardList attackerList = new CardList(attackers.toArray()); possibleBlockers = possibleBlockers.filter(new CardListFilter() { @@ -167,24 +195,28 @@ public class ComputerUtil_Attack2 { } }); return possibleBlockers; - }//getPossibleBlockers() + } // getPossibleBlockers() - //this checks to make sure that the computer player - //doesn't lose when the human player attacks - //this method is used by getAttackers() + // this checks to make sure that the computer player + // doesn't lose when the human player attacks + // this method is used by getAttackers() /** - *

notNeededAsBlockers.

- * - * @param attackers a {@link forge.CardList} object. - * @param combat a {@link forge.Combat} object. + *

+ * notNeededAsBlockers. + *

+ * + * @param attackers + * a {@link forge.CardList} object. + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.CardList} object. */ - public final CardList notNeededAsBlockers(CardList attackers, Combat combat) { + public final CardList notNeededAsBlockers(final CardList attackers, Combat combat) { CardList notNeededAsBlockers = new CardList(attackers.toArray()); CardListUtil.sortAttackLowFirst(attackers); int blockersNeeded = attackers.size(); - //don't hold back creatures that can't block any of the human creatures + // don't hold back creatures that can't block any of the human creatures CardList list = getPossibleBlockers(attackers, humanList); for (int i = 0; i < list.size(); i++) { @@ -201,9 +233,11 @@ public class ComputerUtil_Attack2 { return notNeededAsBlockers; } - // Increase the total number of blockers needed by 1 if Finest Hour in play + // Increase the total number of blockers needed by 1 if Finest Hour in + // play // (human will get an extra first attack with a creature that untaps) - // In addition, if the computer guesses it needs no blockers, make sure that + // In addition, if the computer guesses it needs no blockers, make sure + // that // it won't be surprised by Exalted int humanExaltedBonus = countExaltedBonus(AllZone.getHumanPlayer()); @@ -212,134 +246,153 @@ public class ComputerUtil_Attack2 { if ((blockersNeeded == 0 || nFinestHours > 0) && humanList.size() > 0) { // - // total attack = biggest creature + exalted, *2 if Rafiq is in play + // total attack = biggest creature + exalted, *2 if Rafiq is in + // play int humanBaseAttack = getAttack(humanList.get(0)) + humanExaltedBonus; if (nFinestHours > 0) { - // For Finest Hour, one creature could attack and get the bonus TWICE + // For Finest Hour, one creature could attack and get the + // bonus TWICE humanBaseAttack = humanBaseAttack + humanExaltedBonus; } - int totalExaltedAttack = AllZoneUtil.isCardInPlay("Rafiq of the Many", AllZone.getHumanPlayer()) ? - 2 * humanBaseAttack : humanBaseAttack; + int totalExaltedAttack = AllZoneUtil.isCardInPlay("Rafiq of the Many", + AllZone.getHumanPlayer()) ? 2 * humanBaseAttack : humanBaseAttack; if ((AllZone.getComputerPlayer().getLife() - 3) <= totalExaltedAttack) { - // We will lose if there is an Exalted attack -- keep one blocker - if (blockersNeeded == 0 && notNeededAsBlockers.size() > 0) + // We will lose if there is an Exalted attack -- keep one + // blocker + if (blockersNeeded == 0 && notNeededAsBlockers.size() > 0) { notNeededAsBlockers.remove(0); + } - // Finest Hour allows a second Exalted attack: keep a blocker for that too - if (nFinestHours > 0 && notNeededAsBlockers.size() > 0) + // Finest Hour allows a second Exalted attack: keep a + // blocker for that too + if (nFinestHours > 0 && notNeededAsBlockers.size() > 0) { notNeededAsBlockers.remove(0); + } } } } - //re-add creatures with vigilance + // re-add creatures with vigilance for (Card c : attackers) { - if (c.hasKeyword("Vigilance")) + if (c.hasKeyword("Vigilance")) { notNeededAsBlockers.add(c); + } } return notNeededAsBlockers; } - //this uses a global variable, which isn't perfect + // this uses a global variable, which isn't perfect /** - *

doesHumanAttackAndWin.

- * - * @param nBlockingCreatures a int. + *

+ * doesHumanAttackAndWin. + *

+ * + * @param nBlockingCreatures + * a int. * @return a boolean. */ - public boolean doesHumanAttackAndWin(int nBlockingCreatures) { + public final boolean doesHumanAttackAndWin(final int nBlockingCreatures) { int totalAttack = 0; int stop = humanList.size() - nBlockingCreatures; - for (int i = 0; i < stop; i++) + for (int i = 0; i < stop; i++) { totalAttack += getAttack(humanList.get(i)); + } - //originally -3 so the computer will try to stay at 3 life - //0 now to prevent the AI from not attacking when it's got low life - //(seems to happen too often) + // originally -3 so the computer will try to stay at 3 life + // 0 now to prevent the AI from not attacking when it's got low life + // (seems to happen too often) return AllZone.getComputerPlayer().getLife() <= totalAttack; } /** - *

doAssault.

- * + *

+ * doAssault. + *

+ * * @return a boolean. */ private boolean doAssault() { - //Beastmaster Ascension + // Beastmaster Ascension if (AllZoneUtil.isCardInPlay("Beastmaster Ascension", AllZone.getComputerPlayer()) && attackers.size() > 1) { - CardList beastions = AllZone.getComputerPlayer().getCardsIn(Constant.Zone.Battlefield). - getName("Beastmaster Ascension"); + CardList beastions = AllZone.getComputerPlayer().getCardsIn(Constant.Zone.Battlefield) + .getName("Beastmaster Ascension"); int minCreatures = 7; for (Card beastion : beastions) { int counters = beastion.getCounters(Counters.QUEST); minCreatures = Math.min(minCreatures, 7 - counters); } - if (attackers.size() >= minCreatures) + if (attackers.size() >= minCreatures) { return true; + } } - //I think this is right but the assault code may still be a little off + // I think this is right but the assault code may still be a little off CardListUtil.sortAttackLowFirst(attackers); int totalAttack = 0; - //presumes the Human will block - for (int i = 0; i < (attackers.size() - blockers.size()); i++) + // presumes the Human will block + for (int i = 0; i < (attackers.size() - blockers.size()); i++) { totalAttack += getAttack(attackers.get(i)); + } return blockerLife <= totalAttack; - }//doAssault() + } // doAssault() /** - *

chooseDefender.

- * - * @param c a {@link forge.Combat} object. - * @param bAssault a boolean. + *

+ * chooseDefender. + *

+ * + * @param c + * a {@link forge.Combat} object. + * @param bAssault + * a boolean. */ - public void chooseDefender(Combat c, boolean bAssault) { - // TODO: split attackers to different planeswalker/human + public final void chooseDefender(final Combat c, final boolean bAssault) { + // TODO split attackers to different planeswalker/human // AI will only attack one Defender per combat for now ArrayList defs = c.getDefenders(); - + // Randomly determine who EVERYONE is attacking // would be better to determine more individually int n = MyRandom.random.nextInt(defs.size()); - + Object entity = AllZone.getComputerPlayer().getMustAttackEntity(); - if(null != entity) { - ArrayList defenders = AllZone.getCombat().getDefenders(); - n = defenders.indexOf(entity); - if(-1 == n) { - System.out.println("getMustAttackEntity() returned something not in defenders."); - c.setCurrentDefender(0); - } - else { - c.setCurrentDefender(n); - } - } - else { + if (null != entity) { + ArrayList defenders = AllZone.getCombat().getDefenders(); + n = defenders.indexOf(entity); + if (-1 == n) { + System.out.println("getMustAttackEntity() returned something not in defenders."); + c.setCurrentDefender(0); + } else { + c.setCurrentDefender(n); + } + } else { if (defs.size() == 1 || bAssault) { c.setCurrentDefender(0); + } else { + c.setCurrentDefender(n); } - else c.setCurrentDefender(n); } - + return; } - /** - *

Getter for the field attackers.

- * + *

+ * Getter for the field attackers. + *

+ * * @return a {@link forge.Combat} object. */ public Combat getAttackers() { - //if this method is called multiple times during a turn, - //it will always return the same value - //randomInt is used so that the computer doesn't always - //do the same thing on turn 3 if he had the same creatures in play - //I know this is a little confusing + // if this method is called multiple times during a turn, + // it will always return the same value + // randomInt is used so that the computer doesn't always + // do the same thing on turn 3 if he had the same creatures in play + // I know this is a little confusing random.setSeed(AllZone.getPhase().getTurn() + randomInt); Combat combat = new Combat(); @@ -354,16 +407,15 @@ public class ComputerUtil_Attack2 { CardList attackersLeft = new CardList(attackers.toArray()); - //Attackers that don't really have a choice + // Attackers that don't really have a choice for (Card attacker : attackers) { if ((attacker.hasKeyword("CARDNAME attacks each turn if able.") || attacker.hasKeyword("At the beginning of the end step, destroy CARDNAME.") || attacker.hasKeyword("At the beginning of the end step, exile CARDNAME.") || attacker.hasKeyword("At the beginning of the end step, sacrifice CARDNAME.") - || attacker.getSacrificeAtEOT() - || attacker.getSirenAttackOrDestroy() - || (attacker.getController().getMustAttackEntity() != null)) - && CombatUtil.canAttack(attacker, combat)) { + || attacker.getSacrificeAtEOT() || attacker.getSirenAttackOrDestroy() || (attacker.getController() + .getMustAttackEntity() != null)) && CombatUtil.canAttack(attacker, combat)) + { combat.addAttacker(attacker); attackersLeft.remove(attacker); } @@ -380,19 +432,21 @@ public class ComputerUtil_Attack2 { // examine the potential forces CardList nextTurnAttackers = new CardList(); int candidateCounterAttackDamage = 0; - //int candidateTotalBlockDamage = 0; + // int candidateTotalBlockDamage = 0; for (Card pCard : playerCreatures) { - // if the creature can attack next turn add it to counter attackers list + // if the creature can attack next turn add it to counter attackers + // list if (CombatUtil.canAttackNextTurn(pCard)) { nextTurnAttackers.add(pCard); if (pCard.getNetCombatDamage() > 0) { candidateCounterAttackDamage += pCard.getNetCombatDamage(); - //candidateTotalBlockDamage += pCard.getNetCombatDamage(); + // candidateTotalBlockDamage += pCard.getNetCombatDamage(); playerForces += 1; // player forces they might use to attack } } - // increment player forces that are relevant to an attritional attack - includes walls + // increment player forces that are relevant to an attritional + // attack - includes walls if (CombatUtil.canBlock(pCard)) { playerForcesForAttritionalAttack += 1; } @@ -408,7 +462,8 @@ public class ComputerUtil_Attack2 { CardList candidateAttackers = new CardList(); int candidateUnblockedDamage = 0; for (Card pCard : computerList) { - // if the creature can attack then it's a potential attacker this turn, assume summoning sickness creatures will be able to + // if the creature can attack then it's a potential attacker this + // turn, assume summoning sickness creatures will be able to if (CombatUtil.canAttackNextTurn(pCard)) { candidateAttackers.add(pCard); @@ -422,24 +477,36 @@ public class ComputerUtil_Attack2 { // find the potential damage ratio the AI can cause double playerLifeToDamageRatio = 1000000; - if (candidateUnblockedDamage > 0) + if (candidateUnblockedDamage > 0) { playerLifeToDamageRatio = (double) AllZone.getHumanPlayer().life / candidateUnblockedDamage; + } - /*System.out.println(String.valueOf(aiLifeToPlayerDamageRatio) + " = ai life to player damage ratio"); - System.out.println(String.valueOf(playerLifeToDamageRatio) + " = player life ai player damage ratio");*/ + /* + * System.out.println(String.valueOf(aiLifeToPlayerDamageRatio) + + * " = ai life to player damage ratio"); + * System.out.println(String.valueOf(playerLifeToDamageRatio) + + * " = player life ai player damage ratio"); + */ // determine if the ai outnumbers the player int outNumber = computerForces - playerForces; // compare the ratios, higher = better for ai double ratioDiff = aiLifeToPlayerDamageRatio - playerLifeToDamageRatio; - /* System.out.println(String.valueOf(ratioDiff) + " = ratio difference, higher = better for ai"); - System.out.println(String.valueOf(outNumber) + " = outNumber, higher = better for ai"); */ + /* + * System.out.println(String.valueOf(ratioDiff) + + * " = ratio difference, higher = better for ai"); + * System.out.println(String.valueOf(outNumber) + + * " = outNumber, higher = better for ai"); + */ // ********************* - // if outnumber and superior ratio work out whether attritional all out attacking will work - // attritional attack will expect some creatures to die but to achieve victory by sheer weight - // of numbers attacking turn after turn. It's not calculate very carefully, the accuracy + // if outnumber and superior ratio work out whether attritional all out + // attacking will work + // attritional attack will expect some creatures to die but to achieve + // victory by sheer weight + // of numbers attacking turn after turn. It's not calculate very + // carefully, the accuracy // can probably be improved // ********************* boolean doAttritionalAttack = false; @@ -455,14 +522,15 @@ public class ComputerUtil_Attack2 { // until the attackers are used up or the player would run out of life int attackRounds = 1; while (attritionalAttackers.size() > 0 && playerLife > 0 && attackRounds < 99) { - // sum attacker damage + // sum attacker damage int damageThisRound = 0; for (int y = 0; y < attritionalAttackers.size(); y++) { damageThisRound += attritionalAttackers.getCard(y).getNetCombatDamage(); } - // remove from player life + // remove from player life playerLife -= damageThisRound; - // shorten attacker list by the length of the blockers - assuming all blocked are killed for convenience + // shorten attacker list by the length of the blockers - assuming + // all blocked are killed for convenience for (int z = 0; z < playerForcesForAttritionalAttack; z++) { if (attritionalAttackers.size() > 0) { attritionalAttackers.remove(attritionalAttackers.size() - 1); @@ -473,7 +541,7 @@ public class ComputerUtil_Attack2 { doAttritionalAttack = true; } } - //System.out.println(doAttritionalAttack + " = do attritional attack"); + // System.out.println(doAttritionalAttack + " = do attritional attack"); // ********************* // end attritional attack calculation // ********************* @@ -486,7 +554,8 @@ public class ComputerUtil_Attack2 { boolean doUnblockableAttack = false; for (Card attacker : attackers) { boolean isUnblockableCreature = true; - // check blockers individually, as the bulk canBeBlocked doesn't check all circumstances + // check blockers individually, as the bulk canBeBlocked doesn't + // check all circumstances for (Card blocker : blockers) { if (CombatUtil.canBlock(attacker, blocker)) { isUnblockableCreature = false; @@ -506,22 +575,33 @@ public class ComputerUtil_Attack2 { // end see how long until unblockable attackers will be fatal // ***************** - // decide on attack aggression based on a comparison of forces, life totals and other considerations - // some bad "magic numbers" here, TODO replace with nice descriptive variable names - if ((ratioDiff > 0 && doAttritionalAttack)) { // (playerLifeToDamageRatio <= 1 && ratioDiff >= 1 && outNumber > 0) || + // decide on attack aggression based on a comparison of forces, life + // totals and other considerations + // some bad "magic numbers" here, TODO replace with nice descriptive + // variable names + if ((ratioDiff > 0 && doAttritionalAttack)) { // (playerLifeToDamageRatio + // <= 1 && ratioDiff >= 1 + // && outNumber > 0) || aiAggression = 5; // attack at all costs - } else if ((playerLifeToDamageRatio < 2 && ratioDiff >= 0) || ratioDiff > 3 || (ratioDiff > 0 && outNumber > 0)) { - aiAggression = 3; // attack expecting to kill creatures or damage player. + } else if ((playerLifeToDamageRatio < 2 && ratioDiff >= 0) + || ratioDiff > 3 || (ratioDiff > 0 && outNumber > 0)) { + aiAggression = 3; // attack expecting to kill creatures or damage + // player. } else if (ratioDiff >= 0 || ratioDiff + outNumber >= -1) { - // at 0 ratio expect to potentially gain an advantage by attacking first + // at 0 ratio expect to potentially gain an advantage by attacking + // first // if the ai has a slight advantage - // or the ai has a significant advantage numerically but only a slight disadvantage damage/life - aiAggression = 2; // attack expecting to destroy creatures/be unblockable + // or the ai has a significant advantage numerically but only a + // slight disadvantage damage/life + aiAggression = 2; // attack expecting to destroy creatures/be + // unblockable } else if (ratioDiff < 0 && aiLifeToPlayerDamageRatio > 1) { // the player is overmatched but there are a few turns before death - aiAggression = 2; // attack expecting to destroy creatures/be unblockable + aiAggression = 2; // attack expecting to destroy creatures/be + // unblockable } else if (doUnblockableAttack || ((ratioDiff * -1) < turnsUntilDeathByUnblockable)) { - aiAggression = 1; // look for unblockable creatures that might be able to attack for a bit of + aiAggression = 1; // look for unblockable creatures that might be + // able to attack for a bit of // fatal damage even if the player is significantly better } else if (ratioDiff < 0) { aiAggression = 0; @@ -532,13 +612,15 @@ public class ComputerUtil_Attack2 { // End of edits // **************** - //Exalted - if (combat.getAttackers().length == 0 && (countExaltedBonus(AllZone.getComputerPlayer()) >= 3 || - AllZoneUtil.isCardInPlay("Rafiq of the Many", AllZone.getComputerPlayer()) || - AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield, "Battlegrace Angel").size() >= 2 || - (AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield, "Finest Hour").size() >= 1) && - AllZone.getPhase().isFirstCombat()) - && !bAssault) { + // Exalted + if (combat.getAttackers().length == 0 + && (countExaltedBonus(AllZone.getComputerPlayer()) >= 3 + || AllZoneUtil.isCardInPlay("Rafiq of the Many", AllZone.getComputerPlayer()) + || AllZone.getComputerPlayer() + .getCardsIn(Zone.Battlefield, "Battlegrace Angel").size() >= 2 || (AllZone + .getComputerPlayer().getCardsIn(Zone.Battlefield, "Finest Hour").size() >= 1) + && AllZone.getPhase().isFirstCombat()) && !bAssault) + { int biggest = 0; Card att = null; for (int i = 0; i < attackersLeft.size(); i++) { @@ -547,19 +629,23 @@ public class ComputerUtil_Attack2 { att = attackersLeft.get(i); } } - if (att != null && CombatUtil.canAttack(att, combat)) + if (att != null && CombatUtil.canAttack(att, combat)) { combat.addAttacker(att); + } System.out.println("Exalted"); } - //do assault (all creatures attack) if the computer would win the game - //or if the computer has 4 creatures and the player has 1 + // do assault (all creatures attack) if the computer would win the game + // or if the computer has 4 creatures and the player has 1 else if (bAssault) { System.out.println("Assault"); CardListUtil.sortAttack(attackersLeft); - for (int i = 0; i < attackersLeft.size(); i++) - if (CombatUtil.canAttack(attackersLeft.get(i), combat)) combat.addAttacker(attackersLeft.get(i)); + for (int i = 0; i < attackersLeft.size(); i++) { + if (CombatUtil.canAttack(attackersLeft.get(i), combat)) { + combat.addAttacker(attackersLeft.get(i)); + } + } } else { System.out.println("Normal attack"); @@ -571,28 +657,36 @@ public class ComputerUtil_Attack2 { for (int i = 0; i < attackersLeft.size(); i++) { Card attacker = attackersLeft.get(i); int totalFirstStrikeBlockPower = 0; - if (!attacker.hasFirstStrike() && !attacker.hasDoubleStrike()) - totalFirstStrikeBlockPower = CombatUtil.getTotalFirstStrikeBlockPower(attacker, AllZone.getHumanPlayer()); + if (!attacker.hasFirstStrike() && !attacker.hasDoubleStrike()) { + totalFirstStrikeBlockPower = CombatUtil.getTotalFirstStrikeBlockPower(attacker, + AllZone.getHumanPlayer()); + } - if (shouldAttack(attacker, blockers, combat) && (totalFirstStrikeBlockPower < attacker.getKillDamage() || aiAggression == 5) + if (shouldAttack(attacker, blockers, combat) + && (totalFirstStrikeBlockPower < attacker.getKillDamage() || aiAggression == 5) && CombatUtil.canAttack(attacker, combat)) + { combat.addAttacker(attacker); + } } - }//getAttackers() + } // getAttackers() return combat; - }//getAttackers() + } // getAttackers() /** - *

countExaltedBonus.

- * - * @param player a {@link forge.Player} object. + *

+ * countExaltedBonus. + *

+ * + * @param player + * a {@link forge.Player} object. * @return a int. */ - public int countExaltedBonus(Player player) { + public final int countExaltedBonus(final Player player) { CardList list = player.getCardsIn(Zone.Battlefield); list = list.filter(new CardListFilter() { - public boolean addCard(Card c) { + public boolean addCard(final Card c) { return c.hasKeyword("Exalted"); } }); @@ -601,92 +695,125 @@ public class ComputerUtil_Attack2 { } /** - *

getAttack.

- * - * @param c a {@link forge.Card} object. + *

+ * getAttack. + *

+ * + * @param c + * a {@link forge.Card} object. * @return a int. */ - public int getAttack(Card c) { + public final int getAttack(final Card c) { int n = c.getNetCombatDamage(); - if (c.hasKeyword("Double Strike")) + if (c.hasKeyword("Double Strike")) { n *= 2; + } return n; } /** - *

shouldAttack.

- * - * @param attacker a {@link forge.Card} object. - * @param defenders a {@link forge.CardList} object. - * @param combat a {@link forge.Combat} object. + *

+ * shouldAttack. + *

+ * + * @param attacker + * a {@link forge.Card} object. + * @param defenders + * a {@link forge.CardList} object. + * @param combat + * a {@link forge.Combat} object. * @return a boolean. */ - public boolean shouldAttack(Card attacker, CardList defenders, Combat combat) { - boolean canBeKilledByOne = false; // indicates if the attacker can be killed by a single blockers - boolean canKillAll = true; // indicates if the attacker can kill all single blockers - boolean canKillAllDangerous = true; // indicates if the attacker can kill all single blockers with wither or infect + public final boolean shouldAttack(final Card attacker, final CardList defenders, final Combat combat) { + boolean canBeKilledByOne = false; // indicates if the attacker can be + // killed by a single blockers + boolean canKillAll = true; // indicates if the attacker can kill all + // single blockers + boolean canKillAllDangerous = true; // indicates if the attacker can + // kill all single blockers with + // wither or infect boolean isWorthLessThanAllKillers = true; boolean canBeBlocked = false; - if (!isEffectiveAttacker(attacker, combat)) return false; + if (!isEffectiveAttacker(attacker, combat)) { + return false; + } - // look at the attacker in relation to the blockers to establish a number of factors about the attacking - // context that will be relevant to the attackers decision according to the selected strategy + // look at the attacker in relation to the blockers to establish a + // number of factors about the attacking + // context that will be relevant to the attackers decision according to + // the selected strategy for (Card defender : defenders) { - if (CombatUtil.canBlock(attacker, defender)) { //, combat )) { + if (CombatUtil.canBlock(attacker, defender)) { // , combat )) { canBeBlocked = true; if (CombatUtil.canDestroyAttacker(attacker, defender, combat, false)) { - canBeKilledByOne = true; // there is a single creature on the battlefield that can kill the creature - // see if the defending creature is of higher or lower value. We don't want to attack only to lose value + canBeKilledByOne = true; // there is a single creature on + // the battlefield that can kill + // the creature + // see if the defending creature is of higher or lower + // value. We don't want to attack only to lose value if (CardFactoryUtil.evaluateCreature(defender) <= CardFactoryUtil.evaluateCreature(attacker)) { isWorthLessThanAllKillers = false; } } - // see if this attacking creature can destroy this defender, if not record that it can't kill everything + // see if this attacking creature can destroy this defender, if + // not record that it can't kill everything if (!CombatUtil.canDestroyBlocker(defender, attacker, combat, false)) { canKillAll = false; if (defender.hasKeyword("Wither") || defender.hasKeyword("Infect")) { - canKillAllDangerous = false; // there is a dangerous creature that can survive an attack from this creature + canKillAllDangerous = false; // there is a dangerous + // creature that can + // survive an attack from + // this creature } } } } - // if the creature cannot block and can kill all opponents they might as well attack, they do nothing staying back + // if the creature cannot block and can kill all opponents they might as + // well attack, they do nothing staying back if (canKillAll && !CombatUtil.canBlock(attacker) && isWorthLessThanAllKillers) { - System.out.println(attacker.getName() + " = attacking because they can't block, expecting to kill or damage player"); + System.out.println(attacker.getName() + + " = attacking because they can't block, expecting to kill or damage player"); return true; } - // decide if the creature should attack based on the prevailing strategy choice in aiAggression + // decide if the creature should attack based on the prevailing strategy + // choice in aiAggression switch (aiAggression) { - case 5: // all out attacking - System.out.println(attacker.getName() + " = all out attacking"); + case 5: // all out attacking + System.out.println(attacker.getName() + " = all out attacking"); + return true; + case 4: // expecting to at least trade with something + if (canKillAll || (canKillAllDangerous && !canBeKilledByOne) || !canBeBlocked) { + System.out.println(attacker.getName() + " = attacking expecting to at least trade with something"); return true; - case 4: // expecting to at least trade with something - if (canKillAll || (canKillAllDangerous && !canBeKilledByOne) || !canBeBlocked) { - System.out.println(attacker.getName() + " = attacking expecting to at least trade with something"); - return true; - } - case 3: // expecting to at least kill a creature of equal value, not be blocked - if ((canKillAll && isWorthLessThanAllKillers) || (canKillAllDangerous && !canBeKilledByOne) || !canBeBlocked) { - System.out.println(attacker.getName() + " = attacking expecting to kill creature or cause damage, or is unblockable"); - return true; - } - case 2: // attack expecting to attract a group block or destroying a single blocker and surviving - if ((canKillAll && !canBeKilledByOne) || !canBeBlocked) { - System.out.println(attacker.getName() + " = attacking expecting to survive or attract group block"); - return true; - } - case 1: // unblockable creatures only - if (!canBeBlocked) { - System.out.println(attacker.getName() + " = attacking expecting not to be blocked"); - return true; - } + } + case 3: // expecting to at least kill a creature of equal value, not be + // blocked + if ((canKillAll && isWorthLessThanAllKillers) || (canKillAllDangerous && !canBeKilledByOne) + || !canBeBlocked) { + System.out.println(attacker.getName() + + " = attacking expecting to kill creature or cause damage, or is unblockable"); + return true; + } + case 2: // attack expecting to attract a group block or destroying a + // single blocker and surviving + if ((canKillAll && !canBeKilledByOne) || !canBeBlocked) { + System.out.println(attacker.getName() + " = attacking expecting to survive or attract group block"); + return true; + } + case 1: // unblockable creatures only + if (!canBeBlocked) { + System.out.println(attacker.getName() + " = attacking expecting not to be blocked"); + return true; + } + default: + break; } return false; // don't attack } -}//end class ComputerUtil_Attack2 +} // end class ComputerUtil_Attack2 diff --git a/src/main/java/forge/ComputerUtil_Block2.java b/src/main/java/forge/ComputerUtil_Block2.java index 06cbbf240c6..83d722b7ce3 100644 --- a/src/main/java/forge/ComputerUtil_Block2.java +++ b/src/main/java/forge/ComputerUtil_Block2.java @@ -1,32 +1,44 @@ package forge; -import forge.card.cardFactory.CardFactoryUtil; - import java.util.ArrayList; +import forge.card.cardFactory.CardFactoryUtil; /** - *

ComputerUtil_Block2 class.

- * + *

+ * ComputerUtil_Block2 class. + *

+ * * @author Forge * @version $Id$ */ public class ComputerUtil_Block2 { - /** Constant attackers */ - private static CardList attackers = new CardList(); //all attackers - /** Constant attackersLeft */ - private static CardList attackersLeft = new CardList(); //keeps track of all currently unblocked attackers - /** Constant blockedButUnkilled */ - private static CardList blockedButUnkilled = new CardList(); //blocked attackers that currently wouldn't be destroyed - /** Constant blockersLeft */ - private static CardList blockersLeft = new CardList(); //keeps track of all unassigned blockers - /** Constant diff=0 */ + /** Constant attackers. */ + private static CardList attackers = new CardList(); // all attackers + /** Constant attackersLeft. */ + private static CardList attackersLeft = new CardList(); // keeps track of + // all currently + // unblocked + // attackers + /** Constant blockedButUnkilled. */ + private static CardList blockedButUnkilled = new CardList(); // blocked + // attackers + // that + // currently + // wouldn't be + // destroyed + /** Constant blockersLeft. */ + private static CardList blockersLeft = new CardList(); // keeps track of all + // unassigned + // blockers + /** Constant diff=0. */ private static int diff = 0; - /** - *

Getter for the field attackers.

- * + *

+ * Getter for the field attackers. + *

+ * * @return a {@link forge.CardList} object. */ private static CardList getAttackers() { @@ -34,17 +46,22 @@ public class ComputerUtil_Block2 { } /** - *

Setter for the field attackers.

- * - * @param cardList a {@link forge.CardList} object. + *

+ * Setter for the field attackers. + *

+ * + * @param cardList + * a {@link forge.CardList} object. */ - private static void setAttackers(CardList cardList) { + private static void setAttackers(final CardList cardList) { attackers = (cardList); } /** - *

Getter for the field attackersLeft.

- * + *

+ * Getter for the field attackersLeft. + *

+ * * @return a {@link forge.CardList} object. */ private static CardList getAttackersLeft() { @@ -52,17 +69,22 @@ public class ComputerUtil_Block2 { } /** - *

Setter for the field attackersLeft.

- * - * @param cardList a {@link forge.CardList} object. + *

+ * Setter for the field attackersLeft. + *

+ * + * @param cardList + * a {@link forge.CardList} object. */ - private static void setAttackersLeft(CardList cardList) { + private static void setAttackersLeft(final CardList cardList) { attackersLeft = (cardList); } /** - *

Getter for the field blockedButUnkilled.

- * + *

+ * Getter for the field blockedButUnkilled. + *

+ * * @return a {@link forge.CardList} object. */ private static CardList getBlockedButUnkilled() { @@ -71,17 +93,22 @@ public class ComputerUtil_Block2 { } /** - *

Setter for the field blockedButUnkilled.

- * - * @param cardList a {@link forge.CardList} object. + *

+ * Setter for the field blockedButUnkilled. + *

+ * + * @param cardList + * a {@link forge.CardList} object. */ - private static void setBlockedButUnkilled(CardList cardList) { + private static void setBlockedButUnkilled(final CardList cardList) { blockedButUnkilled = (cardList); } /** - *

Getter for the field blockersLeft.

- * + *

+ * Getter for the field blockersLeft. + *

+ * * @return a {@link forge.CardList} object. */ private static CardList getBlockersLeft() { @@ -89,17 +116,22 @@ public class ComputerUtil_Block2 { } /** - *

Setter for the field blockersLeft.

- * - * @param cardList a {@link forge.CardList} object. + *

+ * Setter for the field blockersLeft. + *

+ * + * @param cardList + * a {@link forge.CardList} object. */ - private static void setBlockersLeft(CardList cardList) { + private static void setBlockersLeft(final CardList cardList) { blockersLeft = (cardList); } /** - *

Getter for the field diff.

- * + *

+ * Getter for the field diff. + *

+ * * @return a int. */ private static int getDiff() { @@ -107,129 +139,166 @@ public class ComputerUtil_Block2 { } /** - *

Setter for the field diff.

- * - * @param diff a int. + *

+ * Setter for the field diff. + *

+ * + * @param diff + * a int. */ - private static void setDiff(int diff) { + private static void setDiff(final int diff) { ComputerUtil_Block2.diff = (diff); } - - //finds the creatures able to block the attacker + // finds the creatures able to block the attacker /** - *

getPossibleBlockers.

- * - * @param attacker a {@link forge.Card} object. - * @param blockersLeft a {@link forge.CardList} object. - * @param combat a {@link forge.Combat} object. + *

+ * getPossibleBlockers. + *

+ * + * @param attacker + * a {@link forge.Card} object. + * @param blockersLeft + * a {@link forge.CardList} object. + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.CardList} object. */ - private static CardList getPossibleBlockers(Card attacker, CardList blockersLeft, Combat combat) { + private static CardList getPossibleBlockers(final Card attacker, final CardList blockersLeft, Combat combat) { CardList blockers = new CardList(); for (Card blocker : blockersLeft) { - //if the blocker can block a creature with lure it can't block a creature without - if (CombatUtil.canBlock(attacker, blocker, combat)) blockers.add(blocker); + // if the blocker can block a creature with lure it can't block a + // creature without + if (CombatUtil.canBlock(attacker, blocker, combat)) { + blockers.add(blocker); + } } return blockers; } - //finds blockers that won't be destroyed + // finds blockers that won't be destroyed /** - *

getSafeBlockers.

- * - * @param attacker a {@link forge.Card} object. - * @param blockersLeft a {@link forge.CardList} object. - * @param combat a {@link forge.Combat} object. + *

+ * getSafeBlockers. + *

+ * + * @param attacker + * a {@link forge.Card} object. + * @param blockersLeft + * a {@link forge.CardList} object. + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.CardList} object. */ - private static CardList getSafeBlockers(Card attacker, CardList blockersLeft, Combat combat) { + private static CardList getSafeBlockers(final Card attacker, final CardList blockersLeft, Combat combat) { CardList blockers = new CardList(); for (Card b : blockersLeft) { - if (!CombatUtil.canDestroyBlocker(b, attacker, combat, false)) blockers.add(b); + if (!CombatUtil.canDestroyBlocker(b, attacker, combat, false)) { + blockers.add(b); + } } return blockers; } - //finds blockers that destroy the attacker + // finds blockers that destroy the attacker /** - *

getKillingBlockers.

- * - * @param attacker a {@link forge.Card} object. - * @param blockersLeft a {@link forge.CardList} object. - * @param combat a {@link forge.Combat} object. + *

+ * getKillingBlockers. + *

+ * + * @param attacker + * a {@link forge.Card} object. + * @param blockersLeft + * a {@link forge.CardList} object. + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.CardList} object. */ - private static CardList getKillingBlockers(Card attacker, CardList blockersLeft, Combat combat) { + private static CardList getKillingBlockers(final Card attacker, final CardList blockersLeft, Combat combat) { CardList blockers = new CardList(); for (Card b : blockersLeft) { - if (CombatUtil.canDestroyAttacker(attacker, b, combat, false)) blockers.add(b); + if (CombatUtil.canDestroyAttacker(attacker, b, combat, false)) { + blockers.add(b); + } } return blockers; } /** - *

sortPotentialAttackers.

- * - * @param combat a {@link forge.Combat} object. + *

+ * sortPotentialAttackers. + *

+ * + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.CardList} object. */ - public static CardList sortPotentialAttackers(Combat combat) { + public static CardList sortPotentialAttackers(final Combat combat) { CardList[] attackerLists = combat.sortAttackerByDefender(); CardList sortedAttackers = new CardList(); ArrayList defenders = combat.getDefenders(); - //Begin with the attackers that pose the biggest threat + // Begin with the attackers that pose the biggest threat CardListUtil.sortByEvaluateCreature(attackerLists[0]); CardListUtil.sortAttack(attackerLists[0]); // If I don't have any planeswalkers than sorting doesn't really matter - if (defenders.size() == 1) + if (defenders.size() == 1) { return attackerLists[0]; + } boolean bLifeInDanger = CombatUtil.lifeInDanger(combat); - // TODO: Add creatures attacking Planeswalkers in order of which we want to protect - // defend planeswalkers with more loyalty before planeswalkers with less loyalty + // TODO Add creatures attacking Planeswalkers in order of which we want + // to protect + // defend planeswalkers with more loyalty before planeswalkers with less + // loyalty // if planeswalker will be too difficult to defend don't even bother for (int i = 1; i < attackerLists.length; i++) { - //Begin with the attackers that pose the biggest threat + // Begin with the attackers that pose the biggest threat CardListUtil.sortAttack(attackerLists[i]); - for (Card c : attackerLists[i]) + for (Card c : attackerLists[i]) { sortedAttackers.add(c); + } } if (bLifeInDanger) { // add creatures attacking the Player to the front of the list - for (Card c : attackerLists[0]) + for (Card c : attackerLists[0]) { sortedAttackers.add(0, c); + } } else { // add creatures attacking the Player to the back of the list - for (Card c : attackerLists[0]) + for (Card c : attackerLists[0]) { sortedAttackers.add(c); + } } return sortedAttackers; } - // ======================= block assignment functions ================================ + // ======================= block assignment functions + // ================================ // Good Blocks means a good trade or no trade /** - *

makeGoodBlocks.

- * - * @param combat a {@link forge.Combat} object. + *

+ * makeGoodBlocks. + *

+ * + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.Combat} object. */ - private static Combat makeGoodBlocks(Combat combat) { + private static Combat makeGoodBlocks(final Combat combat) { CardList currentAttackers = new CardList(getAttackersLeft().toArray()); @@ -243,12 +312,12 @@ public class ComputerUtil_Block2 { CardList killingBlockers; if (safeBlockers.size() > 0) { - // 1.Blockers that can destroy the attacker but won't get destroyed + // 1.Blockers that can destroy the attacker but won't get + // destroyed killingBlockers = getKillingBlockers(attacker, safeBlockers, combat); - if (killingBlockers.size() > 0) blocker = CardFactoryUtil.AI_getWorstCreature(killingBlockers); - - // 2.Blockers that won't get destroyed - else { + if (killingBlockers.size() > 0) { + blocker = CardFactoryUtil.AI_getWorstCreature(killingBlockers); + } else { blocker = CardFactoryUtil.AI_getWorstCreature(safeBlockers); getBlockedButUnkilled().add(attacker); } @@ -256,10 +325,13 @@ public class ComputerUtil_Block2 { else { killingBlockers = getKillingBlockers(attacker, blockers, combat); if (killingBlockers.size() > 0) { - // 3.Blockers that can destroy the attacker and are worth less + // 3.Blockers that can destroy the attacker and are worth + // less Card worst = CardFactoryUtil.AI_getWorstCreature(killingBlockers); - if (CardFactoryUtil.evaluateCreature(worst) + getDiff() < CardFactoryUtil.evaluateCreature(attacker)) { + if (CardFactoryUtil.evaluateCreature(worst) + getDiff() < CardFactoryUtil + .evaluateCreature(attacker)) + { blocker = worst; } } @@ -276,34 +348,43 @@ public class ComputerUtil_Block2 { // Good Gang Blocks means a good trade or no trade /** - *

makeGangBlocks.

- * - * @param combat a {@link forge.Combat} object. + *

+ * makeGangBlocks. + *

+ * + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.Combat} object. */ - private static Combat makeGangBlocks(Combat combat) { + private static Combat makeGangBlocks(final Combat combat) { CardList currentAttackers = new CardList(getAttackersLeft().toArray()); currentAttackers = currentAttackers.getKeywordsDontContain("Rampage"); - currentAttackers = currentAttackers.getKeywordsDontContain("CARDNAME can't be blocked by more than one creature."); + currentAttackers = currentAttackers + .getKeywordsDontContain("CARDNAME can't be blocked by more than one creature."); CardList blockers; - //Try to block an attacker without first strike with a gang of first strikers + // Try to block an attacker without first strike with a gang of first + // strikers for (Card attacker : getAttackersLeft()) { - if (!attacker.hasKeyword("First Strike") - && !attacker.hasKeyword("Double Strike")) { + if (!attacker.hasKeyword("First Strike") && !attacker.hasKeyword("Double Strike")) { blockers = getPossibleBlockers(attacker, getBlockersLeft(), combat); CardList firstStrikeBlockers = new CardList(); CardList blockGang = new CardList(); - for (int i = 0; i < blockers.size(); i++) - if (blockers.get(i).hasFirstStrike() || blockers.get(i).hasDoubleStrike()) + for (int i = 0; i < blockers.size(); i++) { + if (blockers.get(i).hasFirstStrike() || blockers.get(i).hasDoubleStrike()) { firstStrikeBlockers.add(blockers.get(i)); + } + } if (firstStrikeBlockers.size() > 1) { CardListUtil.sortAttack(firstStrikeBlockers); for (Card blocker : firstStrikeBlockers) { - int damageNeeded = attacker.getKillDamage() + CombatUtil.predictToughnessBonusOfAttacker(attacker, blocker, combat); - //if the total damage of the blockgang was not enough without but is enough with this blocker finish the blockgang + int damageNeeded = attacker.getKillDamage() + + CombatUtil.predictToughnessBonusOfAttacker(attacker, blocker, combat); + // if the total damage of the blockgang was not enough + // without but is enough with this blocker finish the + // blockgang if (CombatUtil.totalDamageOfBlockers(attacker, blockGang) < damageNeeded) { blockGang.add(blocker); if (CombatUtil.totalDamageOfBlockers(attacker, blockGang) >= damageNeeded) { @@ -322,26 +403,32 @@ public class ComputerUtil_Block2 { setAttackersLeft(new CardList(currentAttackers.toArray())); currentAttackers = new CardList(getAttackersLeft().toArray()); - //Try to block an attacker with two blockers of which only one will die + // Try to block an attacker with two blockers of which only one will die for (final Card attacker : getAttackersLeft()) { blockers = getPossibleBlockers(attacker, getBlockersLeft(), combat); CardList usableBlockers; CardList blockGang = new CardList(); - int absorbedDamage = 0; //The amount of damage needed to kill the first blocker - int currentValue = 0; //The value of the creatures in the blockgang + int absorbedDamage = 0; // The amount of damage needed to kill the + // first blocker + int currentValue = 0; // The value of the creatures in the blockgang - //Try to add blockers that could be destroyed, but are worth less than the attacker - //Don't use blockers without First Strike or Double Strike if attacker has it + // Try to add blockers that could be destroyed, but are worth less + // than the attacker + // Don't use blockers without First Strike or Double Strike if + // attacker has it usableBlockers = blockers.filter(new CardListFilter() { - public boolean addCard(Card c) { + public boolean addCard(final Card c) { if ((attacker.hasKeyword("First Strike") || attacker.hasKeyword("Double Strike")) && !(c.hasKeyword("First Strike") || c.hasKeyword("Double Strike"))) + { return false; + } return CardFactoryUtil.evaluateCreature(c) + getDiff() < CardFactoryUtil.evaluateCreature(attacker); } }); - if (usableBlockers.size() < 2) + if (usableBlockers.size() < 2) { return combat; + } Card leader = CardFactoryUtil.AI_getBestCreature(usableBlockers); blockGang.add(leader); @@ -350,17 +437,23 @@ public class ComputerUtil_Block2 { currentValue = CardFactoryUtil.evaluateCreature(leader); for (Card blocker : usableBlockers) { - //Add an additional blocker if the current blockers are not enough and the new one would deal the remaining damage + // Add an additional blocker if the current blockers are not + // enough and the new one would deal the remaining damage int currentDamage = CombatUtil.totalDamageOfBlockers(attacker, blockGang); int additionalDamage = CombatUtil.dealsDamageAsBlocker(attacker, blocker); int absorbedDamage2 = blocker.getEnoughDamageToKill(attacker.getNetCombatDamage(), attacker, true); int addedValue = CardFactoryUtil.evaluateCreature(blocker); - int damageNeeded = attacker.getKillDamage() + CombatUtil.predictToughnessBonusOfAttacker(attacker, blocker, combat); - if (damageNeeded > currentDamage - && !(damageNeeded > currentDamage + additionalDamage) //The attacker will be killed - && (absorbedDamage2 + absorbedDamage > attacker.getNetCombatDamage() //only one blocker can be killed - || currentValue + addedValue - 50 <= CardFactoryUtil.evaluateCreature(attacker)) //attacker is worth more - && CombatUtil.canBlock(attacker, blocker, combat)) {//this is needed for attackers that can't be blocked by more than 1 + int damageNeeded = attacker.getKillDamage() + + CombatUtil.predictToughnessBonusOfAttacker(attacker, blocker, combat); + if (damageNeeded > currentDamage && !(damageNeeded > currentDamage + additionalDamage) + // The attacker will be killed + && (absorbedDamage2 + absorbedDamage > attacker.getNetCombatDamage() + // only one blocker can be killed + || currentValue + addedValue - 50 <= CardFactoryUtil.evaluateCreature(attacker)) + // attacker is worth more + && CombatUtil.canBlock(attacker, blocker, combat)) + { + // this is needed for attackers that can't be blocked by more than 1 currentAttackers.remove(attacker); combat.addBlocker(attacker, blocker); combat.addBlocker(attacker, leader); @@ -377,19 +470,22 @@ public class ComputerUtil_Block2 { // Bad Trade Blocks (should only be made if life is in danger) /** - *

makeTradeBlocks.

- * - * @param combat a {@link forge.Combat} object. + *

+ * makeTradeBlocks. + *

+ * + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.Combat} object. */ - private static Combat makeTradeBlocks(Combat combat) { + private static Combat makeTradeBlocks(final Combat combat) { CardList currentAttackers = new CardList(getAttackersLeft().toArray()); CardList killingBlockers; for (Card attacker : getAttackersLeft()) { - killingBlockers = - getKillingBlockers(attacker, getPossibleBlockers(attacker, getBlockersLeft(), combat), combat); + killingBlockers = getKillingBlockers(attacker, getPossibleBlockers(attacker, getBlockersLeft(), combat), + combat); if (killingBlockers.size() > 0 && CombatUtil.lifeInDanger(combat)) { Card blocker = CardFactoryUtil.AI_getWorstCreature(killingBlockers); combat.addBlocker(attacker, blocker); @@ -403,12 +499,15 @@ public class ComputerUtil_Block2 { // Chump Blocks (should only be made if life is in danger) /** - *

makeChumpBlocks.

- * - * @param combat a {@link forge.Combat} object. + *

+ * makeChumpBlocks. + *

+ * + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.Combat} object. */ - private static Combat makeChumpBlocks(Combat combat) { + private static Combat makeChumpBlocks(final Combat combat) { CardList currentAttackers = new CardList(getAttackersLeft().toArray()); CardList chumpBlockers; @@ -427,30 +526,42 @@ public class ComputerUtil_Block2 { return combat; } - //Reinforce blockers blocking attackers with trample (should only be made if life is in danger) + // Reinforce blockers blocking attackers with trample (should only be made + // if life is in danger) /** - *

reinforceBlockersAgainstTrample.

- * - * @param combat a {@link forge.Combat} object. + *

+ * reinforceBlockersAgainstTrample. + *

+ * + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.Combat} object. */ - private static Combat reinforceBlockersAgainstTrample(Combat combat) { + private static Combat reinforceBlockersAgainstTrample(final Combat combat) { CardList chumpBlockers; CardList tramplingAttackers = getAttackers().getKeyword("Trample"); - tramplingAttackers = tramplingAttackers.getKeywordsDontContain("Rampage"); //Don't make it worse - tramplingAttackers = tramplingAttackers.getKeywordsDontContain("CARDNAME can't be blocked by more than one creature."); - //TODO - should check here for a "rampage-like" trigger that replaced the keyword: + tramplingAttackers = tramplingAttackers.getKeywordsDontContain("Rampage"); // Don't + // make + // it + // worse + tramplingAttackers = tramplingAttackers + .getKeywordsDontContain("CARDNAME can't be blocked by more than one creature."); + // TODO - should check here for a "rampage-like" trigger that replaced + // the keyword: // "Whenever CARDNAME becomes blocked, it gets +1/+1 until end of turn for each creature blocking it." for (Card attacker : tramplingAttackers) { chumpBlockers = getPossibleBlockers(attacker, getBlockersLeft(), combat); for (Card blocker : chumpBlockers) { - //Add an additional blocker if the current blockers are not enough and the new one would suck some of the damage - if (CombatUtil.getAttack(attacker) > CombatUtil.totalShieldDamage(attacker, combat.getBlockers(attacker)) - && CombatUtil.shieldDamage(attacker, blocker) > 0 && CombatUtil.canBlock(attacker, blocker, combat) - && CombatUtil.lifeInDanger(combat)) { + // Add an additional blocker if the current blockers are not + // enough and the new one would suck some of the damage + if (CombatUtil.getAttack(attacker) > CombatUtil.totalShieldDamage(attacker, + combat.getBlockers(attacker)) + && CombatUtil.shieldDamage(attacker, blocker) > 0 + && CombatUtil.canBlock(attacker, blocker, combat) && CombatUtil.lifeInDanger(combat)) + { combat.addBlocker(attacker, blocker); getBlockersLeft().remove(blocker); } @@ -460,54 +571,74 @@ public class ComputerUtil_Block2 { return combat; } - //Support blockers not destroying the attacker with more blockers to try to kill the attacker + // Support blockers not destroying the attacker with more blockers to try to + // kill the attacker /** - *

reinforceBlockersToKill.

- * - * @param combat a {@link forge.Combat} object. + *

+ * reinforceBlockersToKill. + *

+ * + * @param combat + * a {@link forge.Combat} object. * @return a {@link forge.Combat} object. */ - private static Combat reinforceBlockersToKill(Combat combat) { + private static Combat reinforceBlockersToKill(final Combat combat) { CardList safeBlockers; CardList blockers; - CardList targetAttackers = getBlockedButUnkilled().getKeywordsDontContain("Rampage"); //Don't make it worse - targetAttackers = targetAttackers.getKeywordsDontContain("CARDNAME can't be blocked by more than one creature."); - //TODO - should check here for a "rampage-like" trigger that replaced the keyword: + CardList targetAttackers = getBlockedButUnkilled().getKeywordsDontContain("Rampage"); // Don't + // make + // it + // worse + targetAttackers = targetAttackers + .getKeywordsDontContain("CARDNAME can't be blocked by more than one creature."); + // TODO - should check here for a "rampage-like" trigger that replaced + // the keyword: // "Whenever CARDNAME becomes blocked, it gets +1/+1 until end of turn for each creature blocking it." for (Card attacker : targetAttackers) { blockers = getPossibleBlockers(attacker, getBlockersLeft(), combat); - //Try to use safe blockers first + // Try to use safe blockers first safeBlockers = getSafeBlockers(attacker, blockers, combat); for (Card blocker : safeBlockers) { - int damageNeeded = attacker.getKillDamage() + CombatUtil.predictToughnessBonusOfAttacker(attacker, blocker, combat); - //Add an additional blocker if the current blockers are not enough and the new one would deal additional damage + int damageNeeded = attacker.getKillDamage() + + CombatUtil.predictToughnessBonusOfAttacker(attacker, blocker, combat); + // Add an additional blocker if the current blockers are not + // enough and the new one would deal additional damage if (damageNeeded > CombatUtil.totalDamageOfBlockers(attacker, combat.getBlockers(attacker)) - && CombatUtil.dealsDamageAsBlocker(attacker, blocker) > 0 && CombatUtil.canBlock(attacker, blocker, combat)) { + && CombatUtil.dealsDamageAsBlocker(attacker, blocker) > 0 + && CombatUtil.canBlock(attacker, blocker, combat)) + { combat.addBlocker(attacker, blocker); getBlockersLeft().remove(blocker); } - blockers.remove(blocker); //Don't check them again next + blockers.remove(blocker); // Don't check them again next } - //Try to add blockers that could be destroyed, but are worth less than the attacker - //Don't use blockers without First Strike or Double Strike if attacker has it + // Try to add blockers that could be destroyed, but are worth less + // than the attacker + // Don't use blockers without First Strike or Double Strike if + // attacker has it if (attacker.hasKeyword("First Strike") || attacker.hasKeyword("Double Strike")) { safeBlockers = blockers.getKeyword("First Strike"); safeBlockers.addAll(blockers.getKeyword("Double Strike")); - } else safeBlockers = new CardList(blockers.toArray()); + } else { + safeBlockers = new CardList(blockers.toArray()); + } for (Card blocker : safeBlockers) { - int damageNeeded = attacker.getKillDamage() + CombatUtil.predictToughnessBonusOfAttacker(attacker, blocker, combat); - //Add an additional blocker if the current blockers are not enough and the new one would deal the remaining damage + int damageNeeded = attacker.getKillDamage() + + CombatUtil.predictToughnessBonusOfAttacker(attacker, blocker, combat); + // Add an additional blocker if the current blockers are not + // enough and the new one would deal the remaining damage int currentDamage = CombatUtil.totalDamageOfBlockers(attacker, combat.getBlockers(attacker)); int additionalDamage = CombatUtil.dealsDamageAsBlocker(attacker, blocker); if (damageNeeded > currentDamage && !(damageNeeded > currentDamage + additionalDamage) - && CardFactoryUtil.evaluateCreature(blocker) + getDiff() < CardFactoryUtil.evaluateCreature(attacker) - && CombatUtil.canBlock(attacker, blocker, combat)) { + && CardFactoryUtil.evaluateCreature(blocker) + getDiff() < CardFactoryUtil + .evaluateCreature(attacker) && CombatUtil.canBlock(attacker, blocker, combat)) + { combat.addBlocker(attacker, blocker); getBlockersLeft().removeAll(blocker); } @@ -518,50 +649,83 @@ public class ComputerUtil_Block2 { } /** - *

resetBlockers.

- * - * @param combat a {@link forge.Combat} object. - * @param possibleBlockers a {@link forge.CardList} object. + *

+ * resetBlockers. + *

+ * + * @param combat + * a {@link forge.Combat} object. + * @param possibleBlockers + * a {@link forge.CardList} object. * @return a {@link forge.Combat} object. */ - private static Combat resetBlockers(Combat combat, CardList possibleBlockers) { + private static Combat resetBlockers(final Combat combat, final CardList possibleBlockers) { CardList oldBlockers = combat.getAllBlockers(); for (Card blocker : oldBlockers) { combat.removeFromCombat(blocker); } - setAttackersLeft(new CardList(getAttackers().toArray())); //keeps track of all currently unblocked attackers - setBlockersLeft(new CardList(possibleBlockers.toArray())); //keeps track of all unassigned blockers - setBlockedButUnkilled(new CardList()); //keeps track of all blocked attackers that currently wouldn't be destroyed + setAttackersLeft(new CardList(getAttackers().toArray())); // keeps track + // of all + // currently + // unblocked + // attackers + setBlockersLeft(new CardList(possibleBlockers.toArray())); // keeps + // track of + // all + // unassigned + // blockers + setBlockedButUnkilled(new CardList()); // keeps track of all blocked + // attackers that currently + // wouldn't be destroyed return combat; } - //Main function + // Main function /** - *

getBlockers.

- * - * @param originalCombat a {@link forge.Combat} object. - * @param possibleBlockers a {@link forge.CardList} object. + *

+ * getBlockers. + *

+ * + * @param originalCombat + * a {@link forge.Combat} object. + * @param possibleBlockers + * a {@link forge.CardList} object. * @return a {@link forge.Combat} object. */ - static public Combat getBlockers(Combat originalCombat, CardList possibleBlockers) { + public static Combat getBlockers(final Combat originalCombat, final CardList possibleBlockers) { Combat combat = originalCombat; setAttackers(sortPotentialAttackers(combat)); - if (getAttackers().size() == 0) + if (getAttackers().size() == 0) { return combat; + } - setAttackersLeft(new CardList(getAttackers().toArray())); //keeps track of all currently unblocked attackers - setBlockersLeft(new CardList(possibleBlockers.toArray())); //keeps track of all unassigned blockers - setBlockedButUnkilled(new CardList()); //keeps track of all blocked attackers that currently wouldn't be destroyed + setAttackersLeft(new CardList(getAttackers().toArray())); // keeps track + // of all + // currently + // unblocked + // attackers + setBlockersLeft(new CardList(possibleBlockers.toArray())); // keeps + // track of + // all + // unassigned + // blockers + setBlockedButUnkilled(new CardList()); // keeps track of all blocked + // attackers that currently + // wouldn't be destroyed CardList blockers; CardList chumpBlockers; - setDiff(AllZone.getComputerPlayer().getLife() * 2 - 5); //This is the minimal gain for an unnecessary trade + setDiff(AllZone.getComputerPlayer().getLife() * 2 - 5); // This is the + // minimal gain + // for an + // unnecessary + // trade // remove all attackers that can't be blocked anyway for (Card a : getAttackers()) { @@ -572,52 +736,85 @@ public class ComputerUtil_Block2 { // remove all blockers that can't block anyway for (Card b : possibleBlockers) { - if (!CombatUtil.canBlock(b, combat)) getBlockersLeft().remove(b); + if (!CombatUtil.canBlock(b, combat)) { + getBlockersLeft().remove(b); + } } - if (getAttackersLeft().size() == 0) + if (getAttackersLeft().size() == 0) { return combat; + } - //Begin with the weakest blockers + // Begin with the weakest blockers CardListUtil.sortAttackLowFirst(getBlockersLeft()); - //== 1. choose best blocks first == + // == 1. choose best blocks first == combat = makeGoodBlocks(combat); combat = makeGangBlocks(combat); - if (CombatUtil.lifeInDanger(combat)) - combat = makeTradeBlocks(combat); //choose necessary trade blocks if life is in danger - if (CombatUtil.lifeInDanger(combat)) - combat = makeChumpBlocks(combat); //choose necessary chump blocks if life is still in danger - //Reinforce blockers blocking attackers with trample if life is still in danger - if (CombatUtil.lifeInDanger(combat)) combat = reinforceBlockersAgainstTrample(combat); - //Support blockers not destroying the attacker with more blockers to try to kill the attacker - if (!CombatUtil.lifeInDanger(combat)) combat = reinforceBlockersToKill(combat); - - - //== 2. If the AI life would still be in danger make a safer approach == if (CombatUtil.lifeInDanger(combat)) { - combat = resetBlockers(combat, possibleBlockers); // reset every block assignment - combat = makeTradeBlocks(combat); //choose necessary trade blocks if life is in danger + combat = makeTradeBlocks(combat); // choose necessary trade blocks + } + // if life is in danger + if (CombatUtil.lifeInDanger(combat)) { + combat = makeChumpBlocks(combat); // choose necessary chump blocks + } + // if life is still in danger + // Reinforce blockers blocking attackers with trample if life is still + // in danger + if (CombatUtil.lifeInDanger(combat)) { + combat = reinforceBlockersAgainstTrample(combat); + } + // Support blockers not destroying the attacker with more blockers to + // try to kill the attacker + if (!CombatUtil.lifeInDanger(combat)) { + combat = reinforceBlockersToKill(combat); + } + + // == 2. If the AI life would still be in danger make a safer approach + // == + if (CombatUtil.lifeInDanger(combat)) { + combat = resetBlockers(combat, possibleBlockers); // reset every + // block + // assignment + combat = makeTradeBlocks(combat); // choose necessary trade blocks + // if life is in danger combat = makeGoodBlocks(combat); - if (CombatUtil.lifeInDanger(combat)) - combat = makeChumpBlocks(combat); //choose necessary chump blocks if life is still in danger - //Reinforce blockers blocking attackers with trample if life is still in danger - if (CombatUtil.lifeInDanger(combat)) combat = reinforceBlockersAgainstTrample(combat); + if (CombatUtil.lifeInDanger(combat)) { + combat = makeChumpBlocks(combat); // choose necessary chump + } + // blocks if life is still in + // danger + // Reinforce blockers blocking attackers with trample if life is + // still in danger + if (CombatUtil.lifeInDanger(combat)) { + combat = reinforceBlockersAgainstTrample(combat); + } combat = makeGangBlocks(combat); combat = reinforceBlockersToKill(combat); } - //== 3. If the AI life would be in serious danger make an even safer approach == + // == 3. If the AI life would be in serious danger make an even safer + // approach == if (CombatUtil.lifeInSeriousDanger(combat)) { - combat = resetBlockers(combat, possibleBlockers); // reset every block assignment - combat = makeChumpBlocks(combat); //choose chump blocks - if (CombatUtil.lifeInDanger(combat)) - combat = makeTradeBlocks(combat); //choose necessary trade blocks if life is in danger - if (!CombatUtil.lifeInDanger(combat)) combat = makeGoodBlocks(combat); - //Reinforce blockers blocking attackers with trample if life is still in danger - if (CombatUtil.lifeInDanger(combat)) combat = reinforceBlockersAgainstTrample(combat); + combat = resetBlockers(combat, possibleBlockers); // reset every + // block + // assignment + combat = makeChumpBlocks(combat); // choose chump blocks + if (CombatUtil.lifeInDanger(combat)) { + combat = makeTradeBlocks(combat); // choose necessary trade + } + // blocks if life is in danger + if (!CombatUtil.lifeInDanger(combat)) { + combat = makeGoodBlocks(combat); + } + // Reinforce blockers blocking attackers with trample if life is + // still in danger + if (CombatUtil.lifeInDanger(combat)) { + combat = reinforceBlockersAgainstTrample(combat); + } combat = makeGangBlocks(combat); - //Support blockers not destroying the attacker with more blockers to try to kill the attacker + // Support blockers not destroying the attacker with more blockers + // to try to kill the attacker combat = reinforceBlockersToKill(combat); } @@ -625,7 +822,9 @@ public class ComputerUtil_Block2 { chumpBlockers = getBlockersLeft().getKeyword("CARDNAME blocks each turn if able."); // if an attacker with lure attacks - all that can block for (Card blocker : getBlockersLeft()) { - if (CombatUtil.mustBlockAnAttacker(blocker, combat)) chumpBlockers.add(blocker); + if (CombatUtil.mustBlockAnAttacker(blocker, combat)) { + chumpBlockers.add(blocker); + } } if (!chumpBlockers.isEmpty()) { getAttackers().shuffle(); diff --git a/src/main/java/forge/Constant.java b/src/main/java/forge/Constant.java index 38ba1679fa3..2b13fc5ae68 100644 --- a/src/main/java/forge/Constant.java +++ b/src/main/java/forge/Constant.java @@ -1,163 +1,333 @@ package forge; - import java.util.ArrayList; import java.util.List; import forge.deck.Deck; import forge.game.GameType; - /** - *

Constant interface.

- * + *

+ * Constant interface. + *

+ * * @author Forge * @version $Id$ */ public interface Constant { /** Constant ProgramName="Forge - http://cardforge.org" */ - public static final String ProgramName = "Forge - http://cardforge.org"; + String ProgramName = "Forge - http://cardforge.org"; - //used to pass information between the GUI screens + // used to pass information between the GUI screens + /** + * The Class Runtime. + */ public abstract class Runtime { + + /** The Constant HumanDeck. */ public static final Deck[] HumanDeck = new Deck[1]; + + /** The Constant ComputerDeck. */ public static final Deck[] ComputerDeck = new Deck[1]; + + /** The game type. */ public static GameType gameType = GameType.Constructed; + /** The Constant Smooth. */ public static final boolean[] Smooth = new boolean[1]; + + /** The Constant Mill. */ public static final boolean[] Mill = new boolean[1]; - public static final boolean[] DevMode = new boolean[1]; // one for normal mode one for quest mode - + + /** The Constant DevMode. */ + public static final boolean[] DevMode = new boolean[1]; // one for + // normal mode + // one for quest + // mode + + /** The Constant NetConn. */ public static final boolean[] NetConn = new boolean[1]; + + /** The Constant UpldDrft. */ public static final boolean[] UpldDrft = new boolean[1]; - + + /** The Constant RndCFoil. */ public static final boolean[] RndCFoil = new boolean[1]; - public static final int[] width = {300}; + /** The Constant width. */ + public static final int[] width = { 300 }; + + /** The Constant height. */ public static final int[] height = new int[1]; + /** The Constant stackSize. */ public static final int[] stackSize = new int[1]; + + /** The Constant stackOffset. */ public static final int[] stackOffset = new int[1]; } - //public interface IO { - // probably should read this from a file, or set from GUI + // public interface IO { + // probably should read this from a file, or set from GUI - //public static final String deckFile = "all-decks2"; - //public static final String boosterDeckFile = "booster-decks"; + // public static final String deckFile = "all-decks2"; + // public static final String boosterDeckFile = "booster-decks"; - //public static final String imageBaseDir = "pics"; + // public static final String imageBaseDir = "pics"; - //public static final ImageIcon upIcon = new ImageIcon("up.gif"); - //public static final ImageIcon downIcon = new ImageIcon("down.gif"); - //public static final ImageIcon leftIcon = new ImageIcon("left.gif"); - //public static final ImageIcon rightIcon = new ImageIcon("right.gif"); - //} + // public static final ImageIcon upIcon = new ImageIcon("up.gif"); + // public static final ImageIcon downIcon = new ImageIcon("down.gif"); + // public static final ImageIcon leftIcon = new ImageIcon("left.gif"); + // public static final ImageIcon rightIcon = new ImageIcon("right.gif"); + // } + /** + * The Interface Ability. + */ public interface Ability { + + /** The Triggered. */ String Triggered = "Triggered"; + + /** The Activated. */ String Activated = "Activated"; } + /** + * The Interface Phase. + */ public interface Phase { - public static final String Untap = "Untap"; - public static final String Upkeep = "Upkeep"; - public static final String Draw = "Draw"; - public static final String Main1 = "Main1"; + /** The Constant Untap. */ + String Untap = "Untap"; - public static final String Combat_Begin = "BeginCombat"; - public static final String Combat_Declare_Attackers = "Declare Attackers"; - public static final String Combat_Declare_Attackers_InstantAbility = "Declare Attackers - Play Instants and Abilities"; - public static final String Combat_Declare_Blockers = "Declare Blockers"; - public static final String Combat_Declare_Blockers_InstantAbility = "Declare Blockers - Play Instants and Abilities"; - public static final String Combat_Damage = "Combat Damage"; - public static final String Combat_FirstStrikeDamage = "First Strike Damage"; - public static final String Combat_End = "EndCombat"; + /** The Constant Upkeep. */ + String Upkeep = "Upkeep"; - public static final String Main2 = "Main2"; + /** The Constant Draw. */ + String Draw = "Draw"; - public static final String End_Of_Turn = "End of Turn"; - public static final String Cleanup = "Cleanup"; + /** The Constant Main1. */ + String Main1 = "Main1"; + + /** The Constant Combat_Begin. */ + String Combat_Begin = "BeginCombat"; + + /** The Constant Combat_Declare_Attackers. */ + String Combat_Declare_Attackers = "Declare Attackers"; + + /** The Constant Combat_Declare_Attackers_InstantAbility. */ + String Combat_Declare_Attackers_InstantAbility = "Declare Attackers - Play Instants and Abilities"; + + /** The Constant Combat_Declare_Blockers. */ + String Combat_Declare_Blockers = "Declare Blockers"; + + /** The Constant Combat_Declare_Blockers_InstantAbility. */ + String Combat_Declare_Blockers_InstantAbility = "Declare Blockers - Play Instants and Abilities"; + + /** The Constant Combat_Damage. */ + String Combat_Damage = "Combat Damage"; + + /** The Constant Combat_FirstStrikeDamage. */ + String Combat_FirstStrikeDamage = "First Strike Damage"; + + /** The Constant Combat_End. */ + String Combat_End = "EndCombat"; + + /** The Constant Main2. */ + String Main2 = "Main2"; + + /** The Constant End_Of_Turn. */ + String End_Of_Turn = "End of Turn"; + + /** The Constant Cleanup. */ + String Cleanup = "Cleanup"; } + /** + * The Enum Zone. + */ public enum Zone { + + /** The Hand. */ Hand, + + /** The Library. */ Library, + + /** The Graveyard. */ Graveyard, + + /** The Battlefield. */ Battlefield, + + /** The Exile. */ Exile, + + /** The Command. */ Command, + + /** The Stack. */ Stack; - + + /** + * Smart value of. + * + * @param value + * the value + * @return the zone + */ public static Zone smartValueOf(final String value) { - if (value == null) { return null; } - if ("All".equals(value)) { return null; } + if (value == null) { + return null; + } + if ("All".equals(value)) { + return null; + } String valToCompate = value.trim(); - for (Zone v : Zone.values()) { if (v.name().compareToIgnoreCase(valToCompate) == 0) { return v; } } + for (Zone v : Zone.values()) { + if (v.name().compareToIgnoreCase(valToCompate) == 0) { + return v; + } + } throw new IllegalArgumentException("No element named " + value + " in enum Zone"); } - + + /** + * List value of. + * + * @param values + * the values + * @return the list + */ public static List listValueOf(final String values) { List result = new ArrayList(); - for (String s : values.split("[, ]+")) { result.add(smartValueOf(s)); } + for (String s : values.split("[, ]+")) { + result.add(smartValueOf(s)); + } return result; } } + /** + * The Interface Color. + */ public interface Color { + + /** The Black. */ String Black = "black"; + + /** The Blue. */ String Blue = "blue"; + + /** The Green. */ String Green = "green"; + + /** The Red. */ String Red = "red"; + + /** The White. */ String White = "white"; + /** The Colorless. */ String Colorless = "colorless"; - //color order "wubrg" - String[] Colors = {White, Blue, Black, Red, Green, Colorless}; - String[] onlyColors = {White, Blue, Black, Red, Green}; + // color order "wubrg" + /** The Colors. */ + String[] Colors = { White, Blue, Black, Red, Green, Colorless }; + /** The only colors. */ + String[] onlyColors = { White, Blue, Black, Red, Green }; + + /** The Snow. */ String Snow = "snow"; - String[] ManaColors = {White, Blue, Black, Red, Green, Colorless, Snow}; - - boolean[] loaded = {false}; - //public static final Constant_StringHashMap[] LandColor = new Constant_StringHashMap[1]; - String[] BasicLands = {"Plains", "Island", "Swamp", "Mountain", "Forest"}; + /** The Mana colors. */ + String[] ManaColors = { White, Blue, Black, Red, Green, Colorless, Snow }; + + /** The loaded. */ + boolean[] loaded = { false }; + // public static final Constant_StringHashMap[] LandColor = new + // Constant_StringHashMap[1]; + + /** The Basic lands. */ + String[] BasicLands = { "Plains", "Island", "Swamp", "Mountain", "Forest" }; } + /** + * The Interface Quest. + */ public interface Quest { + + /** The fantasy quest. */ boolean[] fantasyQuest = new boolean[1]; - //public static final Quest_Assignment[] qa = new Quest_Assignment[1]; + // public static final Quest_Assignment[] qa = new Quest_Assignment[1]; + /** The human list. */ CardList[] humanList = new CardList[1]; + + /** The computer list. */ CardList[] computerList = new CardList[1]; + /** The human life. */ int[] humanLife = new int[1]; + + /** The computer life. */ int[] computerLife = new int[1]; + /** The opp icon name. */ String[] oppIconName = new String[1]; } + /** + * The Interface CardTypes. + */ public interface CardTypes { - boolean[] loaded = {false}; + + /** The loaded. */ + boolean[] loaded = { false }; + + /** The card types. */ Constant_StringArrayList[] cardTypes = new Constant_StringArrayList[1]; + + /** The super types. */ Constant_StringArrayList[] superTypes = new Constant_StringArrayList[1]; + + /** The basic types. */ Constant_StringArrayList[] basicTypes = new Constant_StringArrayList[1]; + + /** The land types. */ Constant_StringArrayList[] landTypes = new Constant_StringArrayList[1]; + + /** The creature types. */ Constant_StringArrayList[] creatureTypes = new Constant_StringArrayList[1]; + + /** The instant types. */ Constant_StringArrayList[] instantTypes = new Constant_StringArrayList[1]; + + /** The sorcery types. */ Constant_StringArrayList[] sorceryTypes = new Constant_StringArrayList[1]; + + /** The enchantment types. */ Constant_StringArrayList[] enchantmentTypes = new Constant_StringArrayList[1]; + + /** The artifact types. */ Constant_StringArrayList[] artifactTypes = new Constant_StringArrayList[1]; + + /** The walker types. */ Constant_StringArrayList[] walkerTypes = new Constant_StringArrayList[1]; } + /** + * The Interface Keywords. + */ public interface Keywords { - boolean[] loaded = {false}; + + /** The loaded. */ + boolean[] loaded = { false }; + + /** The Non stacking list. */ Constant_StringArrayList[] NonStackingList = new Constant_StringArrayList[1]; } - -} //Constant +} // Constant diff --git a/src/main/java/forge/Constant_StringArrayList.java b/src/main/java/forge/Constant_StringArrayList.java index 0383d97ffe2..b0646bb17a4 100644 --- a/src/main/java/forge/Constant_StringArrayList.java +++ b/src/main/java/forge/Constant_StringArrayList.java @@ -2,7 +2,12 @@ package forge; import java.util.ArrayList; +/** + * The Class Constant_StringArrayList. + */ public class Constant_StringArrayList { - public ArrayList list = new ArrayList(); - + + /** The list. */ + public ArrayList list = new ArrayList(); + } diff --git a/src/main/java/forge/Constant_StringHashMap.java b/src/main/java/forge/Constant_StringHashMap.java index ac98fd3b734..8033ecdbbeb 100644 --- a/src/main/java/forge/Constant_StringHashMap.java +++ b/src/main/java/forge/Constant_StringHashMap.java @@ -3,7 +3,12 @@ package forge; import java.util.HashMap; import java.util.Map; +/** + * The Class Constant_StringHashMap. + */ public class Constant_StringHashMap { - public Map map = new HashMap(); - + + /** The map. */ + public Map map = new HashMap(); + } diff --git a/src/main/java/forge/CopyFiles.java b/src/main/java/forge/CopyFiles.java index ea7ef8eeb78..060a2d954ec 100644 --- a/src/main/java/forge/CopyFiles.java +++ b/src/main/java/forge/CopyFiles.java @@ -1,41 +1,65 @@ package forge; - -import forge.properties.ForgeProps; -import forge.properties.NewConstants; -import javax.swing.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JProgressBar; +import javax.swing.SwingWorker; + +import forge.properties.ForgeProps; +import forge.properties.NewConstants; /** - *

CopyFiles class.

- * + *

+ * CopyFiles class. + *

+ * * @author Forge * @version $Id$ */ public class CopyFiles extends SwingWorker implements NewConstants { private List FileList; + + /** The j lb. */ JLabel jLb; + + /** The j b. */ JProgressBar jB; + + /** The j check. */ JCheckBox jCheck; + + /** The j source. */ JButton jSource; + + /** The count. */ int count; /** - *

Constructor for CopyFiles.

- * - * @param FileList a {@link java.util.List} object. - * @param jLabelTotalFiles a {@link javax.swing.JLabel} object. - * @param Jbar a {@link javax.swing.JProgressBar} object. - * @param jCheckBox a {@link javax.swing.JCheckBox} object. - * @param jButtonSource a {@link javax.swing.JButton} object. + *

+ * Constructor for CopyFiles. + *

+ * + * @param FileList + * a {@link java.util.List} object. + * @param jLabelTotalFiles + * a {@link javax.swing.JLabel} object. + * @param Jbar + * a {@link javax.swing.JProgressBar} object. + * @param jCheckBox + * a {@link javax.swing.JCheckBox} object. + * @param jButtonSource + * a {@link javax.swing.JButton} object. */ - public CopyFiles(List FileList, JLabel jLabelTotalFiles, JProgressBar Jbar, JCheckBox jCheckBox, JButton jButtonSource) { + public CopyFiles(final List FileList, JLabel jLabelTotalFiles, JProgressBar Jbar, JCheckBox jCheckBox, + JButton jButtonSource) { this.FileList = FileList; jLb = jLabelTotalFiles; jB = Jbar; @@ -45,7 +69,7 @@ public class CopyFiles extends SwingWorker implements NewConstant /** {@inheritDoc} */ @Override - protected Void doInBackground() { + protected final Void doInBackground() { for (int i = 0; i < this.FileList.size(); i++) { publish(); String cName, name, source; @@ -66,7 +90,9 @@ public class CopyFiles extends SwingWorker implements NewConstant int length; while (fis.available() > 0) { length = fis.read(buff); - if (length > 0) fos.write(buff, 0, length); + if (length > 0) { + fos.write(buff, 0, length); + } } fos.flush(); fis.close(); @@ -85,7 +111,7 @@ public class CopyFiles extends SwingWorker implements NewConstant /** {@inheritDoc} */ @Override - protected void done() { + protected final void done() { jLb.setText("All files were copied successfully."); jB.setIndeterminate(false); jCheck.setEnabled(true); diff --git a/src/main/java/forge/Counters.java b/src/main/java/forge/Counters.java index 40923fc57b0..9112e00f821 100644 --- a/src/main/java/forge/Counters.java +++ b/src/main/java/forge/Counters.java @@ -6,129 +6,321 @@ package forge; - /** * The class Counters. - * + * * @author Clemens Koza * @version V0.0 17.02.2010 */ public enum Counters { + + /** The AGE. */ AGE(), + + /** The ARROW. */ ARROW(), + + /** The ARROWHEAD. */ ARROWHEAD(), + + /** The AWAKENING. */ AWAKENING(), + + /** The BLAZE. */ BLAZE(), + + /** The BLOOD. */ BLOOD(), + + /** The BOUNTY. */ BOUNTY(), + + /** The BRIBERY. */ BRIBERY(), + + /** The CARRION. */ CARRION(), + + /** The CHARGE. */ CHARGE(), + + /** The CORPSE. */ CORPSE(), + + /** The CREDIT. */ CREDIT(), + + /** The CURRENCY. */ CURRENCY(), + + /** The DEATH. */ DEATH(), + + /** The DELAY. */ DELAY(), + + /** The DEPLETION. */ DEPLETION(), + + /** The DEVOTION. */ DEVOTION(), + + /** The DIVINITY. */ DIVINITY(), + + /** The DOOM. */ DOOM(), + + /** The ENERGY. */ ENERGY(), + + /** The EON. */ EON(), + + /** The FADE. */ FADE(), + + /** The FATE. */ FATE(), + + /** The FEATHER. */ FEATHER(), + + /** The FLOOD. */ FLOOD(), + + /** The FUNGUS. */ FUNGUS(), + + /** The FUSE. */ FUSE(), + + /** The GLYPH. */ GLYPH(), + + /** The GOLD. */ GOLD(), + + /** The GROWTH. */ GROWTH(), + + /** The HATCHLING. */ HATCHLING(), + + /** The HEALING. */ HEALING(), + + /** The HOOFPRINT. */ HOOFPRINT(), + + /** The HOURGLASS. */ HOURGLASS(), + + /** The ICE. */ ICE(), + + /** The INFECTION. */ INFECTION(), + + /** The INTERVENTION. */ INTERVENTION(), + + /** The JAVELIN. */ JAVELIN(), + + /** The KI. */ KI(), + + /** The LEVEL. */ LEVEL("Level"), + + /** The LORE. */ LORE(), + + /** The LOYALTY. */ LOYALTY(), + + /** The LUCK. */ LUCK(), + + /** The M0 m1. */ M0M1("-0/-1"), + + /** The M0 m2. */ M0M2("-0/-2"), + + /** The M1 m0. */ M1M0("-1/-0"), + + /** The M1 m1. */ M1M1("-1/-1"), + + /** The M2 m1. */ M2M1("-2/-1"), + + /** The M2 m2. */ M2M2("-2/-2"), + + /** The MANA. */ MANA(), + + /** The MINE. */ MINE(), + + /** The MINING. */ MINING(), + + /** The MIRE. */ MIRE(), + + /** The OMEN. */ OMEN(), + + /** The ORE. */ ORE(), + + /** The PAGE. */ PAGE(), + + /** The PAIN. */ PAIN(), + + /** The PARALYZATION. */ PARALYZATION(), + + /** The PETAL. */ PETAL(), + + /** The PIN. */ PIN(), + + /** The PLAGUE. */ PLAGUE(), + + /** The PRESSURE. */ PRESSURE(), + + /** The PHYLACTERY. */ PHYLACTERY, + + /** The POLYP. */ POLYP(), + + /** The PUPA. */ PUPA(), + + /** The P0 p1. */ P0P1("+0/+1"), + + /** The P1 p0. */ P1P0("+1/+0"), + + /** The P1 p1. */ P1P1("+1/+1"), + + /** The P1 p2. */ P1P2("+1/+2"), + + /** The P2 p2. */ P2P2("+2/+2"), + + /** The QUEST. */ QUEST(), + + /** The SCREAM. */ SCREAM(), + + /** The SHELL. */ SHELL(), + + /** The SHIELD. */ SHIELD(), + + /** The SHRED. */ SHRED(), + + /** The SLEEP. */ SLEEP(), + + /** The SLEIGHT. */ SLEIGHT(), + + /** The SOOT. */ SOOT(), + + /** The SPORE. */ SPORE(), + + /** The STORAGE. */ STORAGE(), + + /** The STUDY. */ STUDY(), + + /** The TIDE. */ TIDE(), + + /** The TIME. */ TIME(), + + /** The TOWER. */ TOWER("tower"), + + /** The TRAINING. */ TRAINING(), + + /** The TRAP. */ TRAP(), + + /** The TREASURE. */ TREASURE(), + + /** The VELOCITY. */ VELOCITY(), + + /** The VERSE. */ VERSE(), + + /** The VITALITY. */ VITALITY(), + + /** The WAGE. */ WAGE(), + + /** The WIND. */ WIND(), + + /** The WISH. */ WISH(); private String name; /** - *

Constructor for Counters.

+ *

+ * Constructor for Counters. + *

*/ private Counters() { this.name = name().substring(0, 1).toUpperCase() + name().substring(1).toLowerCase(); } /** - *

Constructor for Counters.

- * - * @param name a {@link java.lang.String} object. + *

+ * Constructor for Counters. + *

+ * + * @param name + * a {@link java.lang.String} object. */ private Counters(final String nameIn) { this.name = nameIn; } /** - *

Getter for the field name.

- * + *

+ * Getter for the field name. + *

+ * * @return a {@link java.lang.String} object. */ public String getName() { @@ -136,9 +328,12 @@ public enum Counters { } /** - *

getType.

- * - * @param name a {@link java.lang.String} object. + *

+ * getType. + *

+ * + * @param name + * a {@link java.lang.String} object. * @return a {@link forge.Counters} object. */ public static Counters getType(final String name) { diff --git a/src/main/java/forge/EndOfTurn.java b/src/main/java/forge/EndOfTurn.java index 12462591943..2eac2b49bd3 100644 --- a/src/main/java/forge/EndOfTurn.java +++ b/src/main/java/forge/EndOfTurn.java @@ -6,8 +6,10 @@ import forge.card.spellability.SpellAbility; //handles "until end of turn" and "at end of turn" commands from cards /** - *

EndOfTurn class.

- * + *

+ * EndOfTurn class. + *

+ * * @author Forge * @version $Id$ */ @@ -20,44 +22,55 @@ public class EndOfTurn implements java.io.Serializable { private CommandList last = new CommandList(); /** - *

addAt.

- * - * @param c a {@link forge.Command} object. + *

+ * addAt. + *

+ * + * @param c + * a {@link forge.Command} object. */ public final void addAt(final Command c) { at.add(c); } /** - *

addUntil.

- * - * @param c a {@link forge.Command} object. + *

+ * addUntil. + *

+ * + * @param c + * a {@link forge.Command} object. */ public final void addUntil(final Command c) { until.add(c); } /** - *

addLast.

- * - * @param c a {@link forge.Command} object. + *

+ * addLast. + *

+ * + * @param c + * a {@link forge.Command} object. */ public final void addLast(final Command c) { last.add(c); } /** - *

executeAt.

+ *

+ * executeAt. + *

*/ public final void executeAt() { - //Pyrohemia and Pestilence + // Pyrohemia and Pestilence CardList all = AllZoneUtil.getCardsIn(Zone.Battlefield); GameActionUtil.endOfTurn_Wall_Of_Reverence(); GameActionUtil.endOfTurn_Lighthouse_Chronologist(); - //reset mustAttackEntity for me + // reset mustAttackEntity for me AllZone.getPhase().getPlayerTurn().setMustAttackEntity(null); GameActionUtil.removeAttackedBlockedThisTurn(); @@ -65,9 +78,7 @@ public class EndOfTurn implements java.io.Serializable { AllZone.getStaticEffects().rePopulateStateBasedList(); for (Card c : all) { - if (!c.isFaceDown() - && c.hasKeyword("At the beginning of the end step, sacrifice CARDNAME.")) - { + if (!c.isFaceDown() && c.hasKeyword("At the beginning of the end step, sacrifice CARDNAME.")) { final Card card = c; final SpellAbility sac = new Ability(card, "0") { @Override @@ -84,9 +95,7 @@ public class EndOfTurn implements java.io.Serializable { AllZone.getStack().addSimultaneousStackEntry(sac); } - if (!c.isFaceDown() - && c.hasKeyword("At the beginning of the end step, exile CARDNAME.")) - { + if (!c.isFaceDown() && c.hasKeyword("At the beginning of the end step, exile CARDNAME.")) { final Card card = c; final SpellAbility exile = new Ability(card, "0") { @Override @@ -103,9 +112,7 @@ public class EndOfTurn implements java.io.Serializable { AllZone.getStack().addSimultaneousStackEntry(exile); } - if (!c.isFaceDown() - && c.hasKeyword("At the beginning of the end step, destroy CARDNAME.")) - { + if (!c.isFaceDown() && c.hasKeyword("At the beginning of the end step, destroy CARDNAME.")) { final Card card = c; final SpellAbility destroy = new Ability(card, "0") { @Override @@ -122,7 +129,7 @@ public class EndOfTurn implements java.io.Serializable { AllZone.getStack().addSimultaneousStackEntry(destroy); } - //Berserk is using this, so don't check isFaceDown() + // Berserk is using this, so don't check isFaceDown() if (c.hasKeyword("At the beginning of the next end step, destroy CARDNAME if it attacked this turn.")) { if (c.getCreatureAttackedThisTurn()) { final Card card = c; @@ -151,8 +158,9 @@ public class EndOfTurn implements java.io.Serializable { public void resolve() { if (AllZoneUtil.isCardInPlay(vale)) { vale.addController(vale.getController().getOpponent()); - //AllZone.getGameAction().changeController( - // new CardList(vale), vale.getController(), vale.getController().getOpponent()); + // AllZone.getGameAction().changeController( + // new CardList(vale), vale.getController(), + // vale.getController().getOpponent()); vale.removeExtrinsicKeyword("An opponent gains control of CARDNAME at the beginning of the next end step."); } @@ -165,9 +173,8 @@ public class EndOfTurn implements java.io.Serializable { AllZone.getStack().addSimultaneousStackEntry(change); } - if (c.getName().equals("Erg Raiders") && !c.getCreatureAttackedThisTurn() - && !c.hasSickness() && AllZone.getPhase().isPlayerTurn(c.getController())) - { + if (c.getName().equals("Erg Raiders") && !c.getCreatureAttackedThisTurn() && !c.hasSickness() + && AllZone.getPhase().isPlayerTurn(c.getController())) { final Card raider = c; final SpellAbility change = new Ability(raider, "0") { @Override @@ -186,9 +193,8 @@ public class EndOfTurn implements java.io.Serializable { } if (c.hasKeyword("At the beginning of your end step, sacrifice this creature unless it attacked this turn.") && !c.getCreatureAttackedThisTurn() - /* && !(c.getTurnInZone() == AllZone.getPhase().getTurn())*/ - && AllZone.getPhase().isPlayerTurn(c.getController())) - { + /* && !(c.getTurnInZone() == AllZone.getPhase().getTurn()) */ + && AllZone.getPhase().isPlayerTurn(c.getController())) { final Card source = c; final SpellAbility change = new Ability(source, "0") { @Override @@ -206,9 +212,7 @@ public class EndOfTurn implements java.io.Serializable { } if (c.hasKeyword("At the beginning of your end step, destroy this creature if it didn't attack this turn.") - && !c.getCreatureAttackedThisTurn() - && AllZone.getPhase().isPlayerTurn(c.getController())) - { + && !c.getCreatureAttackedThisTurn() && AllZone.getPhase().isPlayerTurn(c.getController())) { final Card source = c; final SpellAbility change = new Ability(source, "0") { @Override @@ -226,8 +230,7 @@ public class EndOfTurn implements java.io.Serializable { } if (c.hasKeyword("At the beginning of your end step, return CARDNAME to its owner's hand.") - && AllZone.getPhase().isPlayerTurn(c.getController())) - { + && AllZone.getPhase().isPlayerTurn(c.getController())) { final Card source = c; final SpellAbility change = new Ability(source, "0") { @Override @@ -247,10 +250,8 @@ public class EndOfTurn implements java.io.Serializable { } - execute(at); - CardList all2 = AllZoneUtil.getCardsIn(Zone.Battlefield); for (Card c : all2) { c.clearMustBlockCards(); @@ -259,11 +260,12 @@ public class EndOfTurn implements java.io.Serializable { } } - } //executeAt() - + } // executeAt() /** - *

executeUntil.

+ *

+ * executeUntil. + *

*/ public final void executeUntil() { execute(until); @@ -271,8 +273,10 @@ public class EndOfTurn implements java.io.Serializable { } /** - *

sizeAt.

- * + *

+ * sizeAt. + *

+ * * @return a int. */ public final int sizeAt() { @@ -280,8 +284,10 @@ public class EndOfTurn implements java.io.Serializable { } /** - *

sizeUntil.

- * + *

+ * sizeUntil. + *

+ * * @return a int. */ public final int sizeUntil() { @@ -289,8 +295,10 @@ public class EndOfTurn implements java.io.Serializable { } /** - *

sizeLast.

- * + *

+ * sizeLast. + *

+ * * @return a int. */ public final int sizeLast() { @@ -298,9 +306,12 @@ public class EndOfTurn implements java.io.Serializable { } /** - *

execute.

- * - * @param c a {@link forge.CommandList} object. + *

+ * execute. + *

+ * + * @param c + * a {@link forge.CommandList} object. */ private void execute(final CommandList c) { int length = c.size(); @@ -310,4 +321,4 @@ public class EndOfTurn implements java.io.Serializable { } } -} //end class EndOfTurn +} // end class EndOfTurn diff --git a/src/main/java/forge/ExternalPanel.java b/src/main/java/forge/ExternalPanel.java index 0e5d7ad3274..0590d7e53b4 100644 --- a/src/main/java/forge/ExternalPanel.java +++ b/src/main/java/forge/ExternalPanel.java @@ -1,12 +1,16 @@ package forge; -import javax.swing.*; -import java.awt.*; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; /** * ExternalPanel.java @@ -14,10 +18,10 @@ import java.awt.event.WindowEvent; * Created on 13.08.2009 */ - /** - * The class ExternalPanel. A panel with which some other component can be shown in an external window. - * + * The class ExternalPanel. A panel with which some other component can be shown + * in an external window. + * * @author Clemens Koza * @version V0.0 13.08.2009 */ @@ -29,19 +33,26 @@ public class ExternalPanel extends JPanel { private JFrame frame; /** - *

Constructor for ExternalPanel.

- * - * @param child a {@link java.awt.Component} object. + *

+ * Constructor for ExternalPanel. + *

+ * + * @param child + * a {@link java.awt.Component} object. */ public ExternalPanel(final Component child) { this(child, BorderLayout.EAST); } /** - *

Constructor for ExternalPanel.

- * - * @param child a {@link java.awt.Component} object. - * @param side a {@link java.lang.String} object. + *

+ * Constructor for ExternalPanel. + *

+ * + * @param child + * a {@link java.awt.Component} object. + * @param side + * a {@link java.lang.String} object. */ public ExternalPanel(final Component child, final String side) { super(new BorderLayout()); @@ -55,9 +66,12 @@ public class ExternalPanel extends JPanel { } /** - *

setHeadSide.

- * - * @param side a {@link java.lang.String} object. + *

+ * setHeadSide. + *

+ * + * @param side + * a {@link java.lang.String} object. */ public final void setHeadSide(final String side) { remove(head); diff --git a/src/main/java/forge/FileUtil.java b/src/main/java/forge/FileUtil.java index 9e701923f74..985aa61544c 100644 --- a/src/main/java/forge/FileUtil.java +++ b/src/main/java/forge/FileUtil.java @@ -1,9 +1,5 @@ package forge; -import forge.error.ErrorViewer; -import forge.properties.ForgeProps; -import forge.properties.NewConstants.LANG.Gui_DownloadPictures.ERRORS; - import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; @@ -19,10 +15,16 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import forge.error.ErrorViewer; +import forge.properties.ForgeProps; +import forge.properties.NewConstants.LANG.Gui_DownloadPictures.ERRORS; +// TODO: Auto-generated Javadoc /** - *

FileUtil class.

- * + *

+ * FileUtil class. + *

+ * * @author Forge * @version $Id$ */ @@ -33,9 +35,12 @@ public final class FileUtil { } /** - *

doesFileExist.

- * - * @param filename a {@link java.lang.String} object. + *

+ * doesFileExist. + *

+ * + * @param filename + * a {@link java.lang.String} object. * @return a boolean. */ public static boolean doesFileExist(final String filename) { @@ -44,24 +49,32 @@ public final class FileUtil { } /** - *

writeFile.

- * - * @param filename a {@link java.lang.String} object. - * @param data a {@link java.util.List} object. + *

+ * writeFile. + *

+ * + * @param filename + * a {@link java.lang.String} object. + * @param data + * a {@link java.util.List} object. */ public static void writeFile(final String filename, final List data) { writeFile(new File(filename), data); } - //writes each element of ArrayList on a separate line - //this is used to write a file of Strings - //this will create a new file if needed - //if filename already exists, it is deleted + // writes each element of ArrayList on a separate line + // this is used to write a file of Strings + // this will create a new file if needed + // if filename already exists, it is deleted /** - *

writeFile.

- * - * @param file a {@link java.io.File} object. - * @param data a {@link java.util.List} object. + *

+ * writeFile. + *

+ * + * @param file + * a {@link java.io.File} object. + * @param data + * a {@link java.util.List} object. */ public static void writeFile(final File file, final List data) { try { @@ -78,25 +91,31 @@ public final class FileUtil { ErrorViewer.showError(ex); throw new RuntimeException("FileUtil : writeFile() error, problem writing file - " + file + " : " + ex); } - } //writeAllDecks() + } // writeAllDecks() /** - *

readFile.

- * - * @param filename a {@link java.lang.String} object. + *

+ * readFile. + *

+ * + * @param filename + * a {@link java.lang.String} object. * @return a {@link java.util.ArrayList} object. */ public static ArrayList readFile(final String filename) { return readFile(new File(filename)); } - //reads line by line and adds each line to the ArrayList - //this will return blank lines as well - //if filename not found, returns an empty ArrayList + // reads line by line and adds each line to the ArrayList + // this will return blank lines as well + // if filename not found, returns an empty ArrayList /** - *

readFile.

- * - * @param file a {@link java.io.File} object. + *

+ * readFile. + *

+ * + * @param file + * a {@link java.io.File} object. * @return a {@link java.util.ArrayList} object. */ public static ArrayList readFile(final File file) { @@ -108,7 +127,6 @@ public final class FileUtil { return list; } - in = new BufferedReader(new FileReader(file)); String line; @@ -121,31 +139,34 @@ public final class FileUtil { } return list; - } //readFile() - - public static void downloadUrlIntoFile(final String url, final File target) - { - try{ + } // readFile() + + /** + * Download url into file. + * + * @param url the url + * @param target the target + */ + public static void downloadUrlIntoFile(final String url, final File target) { + try { byte[] buf = new byte[1024]; int len; - + Proxy p = Proxy.NO_PROXY; BufferedInputStream in = new BufferedInputStream(new URL(url).openConnection(p).getInputStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); - - //while - read and write file + + // while - read and write file while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); - - }//while - read and write file + + } // while - read and write file in.close(); out.flush(); out.close(); - } - catch (IOException ioex) - { + } catch (IOException ioex) { ErrorViewer.showError(ioex, ForgeProps.getLocalized(ERRORS.OTHER), "deck_temp.html", url); } - + } } diff --git a/src/main/java/forge/GameActionUtil.java b/src/main/java/forge/GameActionUtil.java index d232fdd8be2..007fdc5901c 100644 --- a/src/main/java/forge/GameActionUtil.java +++ b/src/main/java/forge/GameActionUtil.java @@ -1,30 +1,29 @@ package forge; - -import forge.Constant.Zone; -import forge.card.abilityFactory.AbilityFactory; -import forge.card.cardFactory.CardFactoryUtil; -import forge.card.cost.Cost; -import forge.card.spellability.Ability_Activated; -import forge.card.spellability.Ability_Mana; -import forge.card.spellability.SpellAbility; -import forge.card.spellability.Ability; -import forge.card.spellability.Target; -import forge.game.GameLossReason; -import forge.gui.GuiUtils; -import forge.gui.input.Input_PayManaCostUtil; -import forge.gui.input.Input_PayManaCost_Ability; - - import java.util.ArrayList; import java.util.HashMap; import javax.swing.JOptionPane; +import forge.Constant.Zone; +import forge.card.abilityFactory.AbilityFactory; +import forge.card.cardFactory.CardFactoryUtil; +import forge.card.cost.Cost; +import forge.card.spellability.Ability; +import forge.card.spellability.Ability_Activated; +import forge.card.spellability.Ability_Mana; +import forge.card.spellability.SpellAbility; +import forge.card.spellability.Target; +import forge.game.GameLossReason; +import forge.gui.GuiUtils; +import forge.gui.input.Input_PayManaCostUtil; +import forge.gui.input.Input_PayManaCost_Ability; /** - *

GameActionUtil class.

- * + *

+ * GameActionUtil class. + *

+ * * @author Forge * @version $Id$ */ @@ -35,9 +34,12 @@ public final class GameActionUtil { } /** - *

executePlayCardEffects.

- * - * @param sa a {@link forge.card.spellability.SpellAbility} object. + *

+ * executePlayCardEffects. + *

+ * + * @param sa + * a {@link forge.card.spellability.SpellAbility} object. */ public static void executePlayCardEffects(final SpellAbility sa) { // experimental: @@ -51,9 +53,12 @@ public final class GameActionUtil { } /** - *

playCard_Cascade.

- * - * @param c a {@link forge.Card} object. + *

+ * playCard_Cascade. + *

+ * + * @param c + * a {@link forge.Card} object. */ public static void playCard_Cascade(final Card c) { Command cascade = new Command() { @@ -61,23 +66,27 @@ public final class GameActionUtil { public void execute() { - if(!c.isCopiedSpell()) { + if (!c.isCopiedSpell()) { CardList humanNexus = AllZone.getHumanPlayer().getCardsIn(Zone.Battlefield, "Maelstrom Nexus"); - CardList computerNexus = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield, "Maelstrom Nexus"); - + CardList computerNexus = AllZone.getComputerPlayer() + .getCardsIn(Zone.Battlefield, "Maelstrom Nexus"); + CardList maelstromNexii = new CardList(); maelstromNexii.addAll(humanNexus); maelstromNexii.addAll(computerNexus); - - - for(Card nexus : maelstromNexii) { - if(CardUtil.getThisTurnCast("Card.YouCtrl", nexus).size() == 1) { + + for (Card nexus : maelstromNexii) { + if (CardUtil.getThisTurnCast("Card.YouCtrl", nexus).size() == 1) { doCascade(c); } } } - if (c.hasKeyword("Cascade") - || c.getName().equals("Bituminous Blast")) //keyword gets cleared for Bitumonous Blast + if (c.hasKeyword("Cascade") || c.getName().equals("Bituminous Blast")) // keyword + // gets + // cleared + // for + // Bitumonous + // Blast { doCascade(c); } @@ -103,14 +112,15 @@ public final class GameActionUtil { while (cascadedCard == null) { crd = topOfLibrary.get(count++); revealed.add(crd); - if ((!crd.isLand() && CardUtil.getConvertedManaCost(crd.getManaCost()) < CardUtil.getConvertedManaCost(cascCard.getManaCost()))) + if ((!crd.isLand() && CardUtil.getConvertedManaCost(crd.getManaCost()) < CardUtil + .getConvertedManaCost(cascCard.getManaCost()))) cascadedCard = crd; if (count == topOfLibrary.size()) { break; } - } //while + } // while GuiUtils.getChoiceOptional("Revealed cards:", revealed.toArray()); if (cascadedCard != null && !cascadedCard.isUnCastable()) { @@ -122,8 +132,8 @@ public final class GameActionUtil { question.append("Cast ").append(cascadedCard.getName()); question.append(" without paying its mana cost?"); - int answer = JOptionPane.showConfirmDialog(null, question.toString(), - title.toString(), JOptionPane.YES_NO_OPTION); + int answer = JOptionPane.showConfirmDialog(null, question.toString(), title.toString(), + JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) { AllZone.getGameAction().playCardNoCost(cascadedCard); @@ -159,9 +169,12 @@ public final class GameActionUtil { } /** - *

playCard_Ripple.

- * - * @param c a {@link forge.Card} object. + *

+ * playCard_Ripple. + *

+ * + * @param c + * a {@link forge.Card} object. */ public static void playCard_Ripple(final Card c) { Command ripple = new Command() { @@ -170,7 +183,8 @@ public final class GameActionUtil { public void execute() { CardList humanThrummingStone = AllZone.getHumanPlayer().getCardsIn(Zone.Battlefield, "Thrumming Stone"); - CardList computerThrummingStone = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield, "Thrumming Stone"); + CardList computerThrummingStone = AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield, + "Thrumming Stone"); for (int i = 0; i < humanThrummingStone.size(); i++) { if (c.getController().isHuman()) { @@ -197,11 +211,11 @@ public final class GameActionUtil { final Card rippleCard = c; boolean activateRipple = false; if (controller.isHuman()) { - Object[] possibleValues = {"Yes", "No"}; + Object[] possibleValues = { "Yes", "No" }; AllZone.getDisplay().showMessage("Activate Ripple? "); Object q = JOptionPane.showOptionDialog(null, "Activate Ripple for " + c, "Ripple", - JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, - null, possibleValues, possibleValues[0]); + JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, possibleValues, + possibleValues[0]); if (q.equals(0)) { activateRipple = true; } @@ -219,7 +233,8 @@ public final class GameActionUtil { return; } - // Shouldn't Have more than Ripple 10, seeing as no cards exist with a ripple greater than 4 + // Shouldn't Have more than Ripple 10, seeing as no + // cards exist with a ripple greater than 4 int rippleMax = 10; Card[] rippledCards = new Card[rippleMax]; Card crd; @@ -233,16 +248,17 @@ public final class GameActionUtil { if (crd.getName().equals(rippleCard.getName())) { rippledCards[i] = crd; } - } //for + } // for GuiUtils.getChoiceOptional("Revealed cards:", revealed.toArray()); for (int i = 0; i < rippleMax; i++) { if (rippledCards[i] != null && !rippledCards[i].isUnCastable()) { if (rippledCards[i].getController().isHuman()) { - Object[] possibleValues = {"Yes", "No"}; - Object q = JOptionPane.showOptionDialog(null, "Cast " + rippledCards[i].getName() + "?", "Ripple", - JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, - null, possibleValues, possibleValues[0]); + Object[] possibleValues = { "Yes", "No" }; + Object q = JOptionPane.showOptionDialog(null, + "Cast " + rippledCards[i].getName() + "?", "Ripple", + JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, + possibleValues, possibleValues[0]); if (q.equals(0)) { AllZone.getGameAction().playCardNoCost(rippledCards[i]); revealed.remove(rippledCards[i]); @@ -251,7 +267,7 @@ public final class GameActionUtil { ArrayList choices = rippledCards[i].getBasicSpells(); for (SpellAbility sa : choices) { - if (sa.canPlayAI() && !sa.getSourceCard().isType("Legendary")) { + if (sa.canPlayAI() && !sa.getSourceCard().isType("Legendary")) { ComputerUtil.playStackFree(sa); revealed.remove(rippledCards[i]); break; @@ -276,30 +292,38 @@ public final class GameActionUtil { } }; ripple.execute(); - } //playCard_Ripple() + } // playCard_Ripple() /** - *

payManaDuringAbilityResolve.

- * - * @param message a {@link java.lang.String} object. - * @param manaCost a {@link java.lang.String} object. - * @param paid a {@link forge.Command} object. - * @param unpaid a {@link forge.Command} object. + *

+ * payManaDuringAbilityResolve. + *

+ * + * @param message + * a {@link java.lang.String} object. + * @param manaCost + * a {@link java.lang.String} object. + * @param paid + * a {@link forge.Command} object. + * @param unpaid + * a {@link forge.Command} object. */ - public static void payManaDuringAbilityResolve(final String message, final String manaCost, - final Command paid, final Command unpaid) - { - // temporarily disable the Resolve flag, so the user can payMana for the resolving Ability + public static void payManaDuringAbilityResolve(final String message, final String manaCost, final Command paid, + final Command unpaid) { + // temporarily disable the Resolve flag, so the user can payMana for the + // resolving Ability boolean bResolving = AllZone.getStack().getResolving(); AllZone.getStack().setResolving(false); AllZone.getInputControl().setInput(new Input_PayManaCost_Ability(message, manaCost, paid, unpaid)); AllZone.getStack().setResolving(bResolving); } - //START ENDOFTURN CARDS + // START ENDOFTURN CARDS /** - *

endOfTurn_Wall_Of_Reverence.

+ *

+ * endOfTurn_Wall_Of_Reverence. + *

*/ public static void endOfTurn_Wall_Of_Reverence() { final Player player = AllZone.getPhase().getPlayerTurn(); @@ -317,13 +341,14 @@ public final class GameActionUtil { } if (player.isHuman()) { - Object o = GuiUtils.getChoiceOptional("Select target creature for Wall of Reverence life gain", creats.toArray()); + Object o = GuiUtils.getChoiceOptional("Select target creature for Wall of Reverence life gain", + creats.toArray()); if (o != null) { Card c = (Card) o; int power = c.getNetAttack(); player.gainLife(power, card); } - } else { //computer + } else { // computer CardListUtil.sortAttack(creats); Card c = creats.get(0); if (c != null) { @@ -341,10 +366,12 @@ public final class GameActionUtil { AllZone.getStack().addSimultaneousStackEntry(ability); } - } //endOfTurn_Wall_Of_Reverence() + } // endOfTurn_Wall_Of_Reverence() /** - *

endOfTurn_Lighthouse_Chronologist.

+ *

+ * endOfTurn_Lighthouse_Chronologist. + *

*/ public static void endOfTurn_Lighthouse_Chronologist() { final Player player = AllZone.getPhase().getPlayerTurn(); @@ -375,10 +402,12 @@ public final class GameActionUtil { } } - //END ENDOFTURN CARDS + // END ENDOFTURN CARDS /** - *

removeAttackedBlockedThisTurn.

+ *

+ * removeAttackedBlockedThisTurn. + *

*/ public static void removeAttackedBlockedThisTurn() { // resets the status of attacked/blocked this turn @@ -392,7 +421,8 @@ public final class GameActionUtil { } if (c.getCreatureBlockedThisCombat()) { c.setCreatureBlockedThisCombat(false); - //do not reset setCreatureAttackedThisTurn(), this appears to be combat specific + // do not reset setCreatureAttackedThisTurn(), this appears to + // be combat specific } if (c.getCreatureGotBlockedThisCombat()) { @@ -402,10 +432,14 @@ public final class GameActionUtil { } /** - *

showYesNoDialog.

- * - * @param c a {@link forge.Card} object. - * @param question a {@link java.lang.String} object. + *

+ * showYesNoDialog. + *

+ * + * @param c + * a {@link forge.Card} object. + * @param question + * a {@link java.lang.String} object. * @return a boolean. */ public static boolean showYesNoDialog(final Card c, final String question) { @@ -413,11 +447,16 @@ public final class GameActionUtil { } /** - *

showYesNoDialog.

- * - * @param c a {@link forge.Card} object. - * @param question a {@link java.lang.String} object. - * @param defaultNo true if the default option should be "No", false otherwise + *

+ * showYesNoDialog. + *

+ * + * @param c + * a {@link forge.Card} object. + * @param question + * a {@link java.lang.String} object. + * @param defaultNo + * true if the default option should be "No", false otherwise * @return a boolean. */ public static boolean showYesNoDialog(final Card c, String question, final boolean defaultNo) { @@ -431,12 +470,11 @@ public final class GameActionUtil { int answer; if (defaultNo) { - Object[] options = {"Yes", "No"}; - answer = JOptionPane.showOptionDialog(null, question, title.toString(), JOptionPane.YES_NO_OPTION, - JOptionPane.PLAIN_MESSAGE, null, options, options[1]); - } - else { - answer = JOptionPane.showConfirmDialog(null, question, title.toString(), JOptionPane.YES_NO_OPTION); + Object[] options = { "Yes", "No" }; + answer = JOptionPane.showOptionDialog(null, question, title.toString(), JOptionPane.YES_NO_OPTION, + JOptionPane.PLAIN_MESSAGE, null, options, options[1]); + } else { + answer = JOptionPane.showConfirmDialog(null, question, title.toString(), JOptionPane.YES_NO_OPTION); } if (answer == JOptionPane.YES_OPTION) { @@ -447,24 +485,31 @@ public final class GameActionUtil { } /** - *

showInfoDialg.

- * - * @param message a {@link java.lang.String} object. + *

+ * showInfoDialg. + *

+ * + * @param message + * a {@link java.lang.String} object. */ public static void showInfoDialg(final String message) { JOptionPane.showMessageDialog(null, message); } /** - *

flipACoin.

- * - * @param caller a {@link forge.Player} object. - * @param source a {@link forge.Card} object. + *

+ * flipACoin. + *

+ * + * @param caller + * a {@link forge.Player} object. + * @param source + * a {@link forge.Card} object. * @return a boolean. */ public static boolean flipACoin(final Player caller, final Card source) { String choice = ""; - String[] choices = {"heads", "tails"}; + String[] choices = { "heads", "tails" }; boolean flip = MyRandom.random.nextBoolean(); if (caller.isHuman()) { @@ -476,15 +521,18 @@ public final class GameActionUtil { boolean winFlip = flip == choice.equals("heads"); String winMsg = winFlip ? " wins flip." : " loses flip."; - JOptionPane.showMessageDialog(null, source.getName() + " - " + caller + winMsg, - source.getName(), JOptionPane.PLAIN_MESSAGE); + JOptionPane.showMessageDialog(null, source.getName() + " - " + caller + winMsg, source.getName(), + JOptionPane.PLAIN_MESSAGE); return winFlip; } /** - *

executeLandfallEffects.

- * - * @param c a {@link forge.Card} object. + *

+ * executeLandfallEffects. + *

+ * + * @param c + * a {@link forge.Card} object. */ public static void executeLandfallEffects(final Card c) { if (c.getName().equals("Lotus Cobra")) { @@ -493,14 +541,17 @@ public final class GameActionUtil { } /** - *

showLandfallDialog.

- * - * @param c a {@link forge.Card} object. + *

+ * showLandfallDialog. + *

+ * + * @param c + * a {@link forge.Card} object. * @return a boolean. */ private static boolean showLandfallDialog(final Card c) { AllZone.getDisplay().setCard(c); - String[] choices = {"Yes", "No"}; + String[] choices = { "Yes", "No" }; Object q = null; @@ -514,9 +565,12 @@ public final class GameActionUtil { } /** - *

landfall_Lotus_Cobra.

- * - * @param c a {@link forge.Card} object. + *

+ * landfall_Lotus_Cobra. + *

+ * + * @param c + * a {@link forge.Card} object. */ private static void landfall_Lotus_Cobra(final Card c) { Ability ability = new Ability(c, "0") { @@ -534,7 +588,6 @@ public final class GameActionUtil { } }; - StringBuilder sb = new StringBuilder(); sb.append(c.getName()).append(" - add one mana of any color to your mana pool."); ability.setStackDescription(sb.toString()); @@ -544,16 +597,22 @@ public final class GameActionUtil { AllZone.getStack().addSimultaneousStackEntry(ability); } } else { - // TODO once AI has a mana pool he should choose add Ability and choose a mana as appropriate + // TODO once AI has a mana pool he should choose add Ability and + // choose a mana as appropriate } } - //not restricted to combat damage, not restricted to dealing damage to creatures/players + // not restricted to combat damage, not restricted to dealing damage to + // creatures/players /** - *

executeDamageDealingEffects.

- * - * @param source a {@link forge.Card} object. - * @param damage a int. + *

+ * executeDamageDealingEffects. + *

+ * + * @param source + * a {@link forge.Card} object. + * @param damage + * a int. */ public static void executeDamageDealingEffects(final Card source, final int damage) { @@ -567,13 +626,18 @@ public final class GameActionUtil { } - //restricted to combat damage and dealing damage to creatures + // restricted to combat damage and dealing damage to creatures /** - *

executeCombatDamageToCreatureEffects.

- * - * @param source a {@link forge.Card} object. - * @param affected a {@link forge.Card} object. - * @param damage a int. + *

+ * executeCombatDamageToCreatureEffects. + *

+ * + * @param source + * a {@link forge.Card} object. + * @param affected + * a {@link forge.Card} object. + * @param damage + * a int. */ public static void executeCombatDamageToCreatureEffects(final Card source, final Card affected, final int damage) { @@ -581,16 +645,23 @@ public final class GameActionUtil { return; } - //placeholder for any future needs (everything that was here is converted to script) + // placeholder for any future needs (everything that was here is + // converted to script) } - //not restricted to combat damage, restricted to dealing damage to creatures + // not restricted to combat damage, restricted to dealing damage to + // creatures /** - *

executeDamageToCreatureEffects.

- * - * @param source a {@link forge.Card} object. - * @param affected a {@link forge.Card} object. - * @param damage a int. + *

+ * executeDamageToCreatureEffects. + *

+ * + * @param source + * a {@link forge.Card} object. + * @param affected + * a {@link forge.Card} object. + * @param damage + * a int. */ public static void executeDamageToCreatureEffects(final Card source, final Card affected, final int damage) { @@ -638,7 +709,8 @@ public final class GameActionUtil { ability2.setStackDescription(sb.toString()); if (affected.hasKeyword("When CARDNAME is dealt damage, destroy it. It can't be regenerated.")) { - int amount = affected.getAmountOfKeyword("When CARDNAME is dealt damage, destroy it. It can't be regenerated."); + int amount = affected + .getAmountOfKeyword("When CARDNAME is dealt damage, destroy it. It can't be regenerated."); for (int i = 0; i < amount; i++) { AllZone.getStack().addSimultaneousStackEntry(ability2); @@ -658,19 +730,23 @@ public final class GameActionUtil { } } - //this is for cards like Sengir Vampire + // this is for cards like Sengir Vampire /** - *

executeVampiricEffects.

- * - * @param c a {@link forge.Card} object. + *

+ * executeVampiricEffects. + *

+ * + * @param c + * a {@link forge.Card} object. */ public static void executeVampiricEffects(final Card c) { ArrayList a = c.getKeyword(); for (int i = 0; i < a.size(); i++) { if (AllZoneUtil.isCardInPlay(c) - && a.get(i).toString().startsWith( - "Whenever a creature dealt damage by CARDNAME this turn is put into a graveyard, put")) - { + && a.get(i) + .toString() + .startsWith( + "Whenever a creature dealt damage by CARDNAME this turn is put into a graveyard, put")) { final Card thisCard = c; final String kw = a.get(i).toString(); Ability ability2 = new Ability(c, "0") { @@ -701,13 +777,18 @@ public final class GameActionUtil { } } - //not restricted to just combat damage, restricted to players + // not restricted to just combat damage, restricted to players /** - *

executeDamageToPlayerEffects.

- * - * @param player a {@link forge.Player} object. - * @param c a {@link forge.Card} object. - * @param damage a int. + *

+ * executeDamageToPlayerEffects. + *

+ * + * @param player + * a {@link forge.Player} object. + * @param c + * a {@link forge.Card} object. + * @param damage + * a int. */ public static void executeDamageToPlayerEffects(final Player player, final Card c, final int damage) { if (damage <= 0) { @@ -756,14 +837,18 @@ public final class GameActionUtil { } } - - //restricted to combat damage, restricted to players + // restricted to combat damage, restricted to players /** - *

executeCombatDamageToPlayerEffects.

- * - * @param player a {@link forge.Player} object. - * @param c a {@link forge.Card} object. - * @param damage a int. + *

+ * executeCombatDamageToPlayerEffects. + *

+ * + * @param player + * a {@link forge.Player} object. + * @param c + * a {@link forge.Card} object. + * @param damage + * a int. */ public static void executeCombatDamageToPlayerEffects(final Player player, final Card c, final int damage) { @@ -779,7 +864,9 @@ public final class GameActionUtil { public void resolve() { if (AllZoneUtil.isCardInPlay(zone)) { zone.addController(c.getController()); - //AllZone.getGameAction().changeController(new CardList(zone), zone.getController(), c.getController()); + // AllZone.getGameAction().changeController(new + // CardList(zone), zone.getController(), + // c.getController()); } } }; @@ -845,12 +932,15 @@ public final class GameActionUtil { execute_Celestial_Mantle(c); } - } //executeCombatDamageToPlayerEffects + } // executeCombatDamageToPlayerEffects /** - *

execute_Celestial_Mantle.

- * - * @param enchanted a {@link forge.Card} object. + *

+ * execute_Celestial_Mantle. + *

+ * + * @param enchanted + * a {@link forge.Card} object. */ private static void execute_Celestial_Mantle(final Card enchanted) { ArrayList auras = enchanted.getEnchantedBy(); @@ -872,9 +962,12 @@ public final class GameActionUtil { } /** - *

playerCombatDamage_Treva.

- * - * @param c a {@link forge.Card} object. + *

+ * playerCombatDamage_Treva. + *

+ * + * @param c + * a {@link forge.Card} object. */ private static void playerCombatDamage_Treva(final Card c) { SpellAbility[] sa = c.getSpellAbility(); @@ -887,9 +980,12 @@ public final class GameActionUtil { } /** - *

playerCombatDamage_Whirling_Dervish.

- * - * @param c a {@link forge.Card} object. + *

+ * playerCombatDamage_Whirling_Dervish. + *

+ * + * @param c + * a {@link forge.Card} object. */ private static void playerCombatDamage_Whirling_Dervish(final Card c) { final int power = c.getNetAttack(); @@ -921,9 +1017,12 @@ public final class GameActionUtil { } /** - *

playerCombatDamage_lose_halflife_up.

- * - * @param c a {@link forge.Card} object. + *

+ * playerCombatDamage_lose_halflife_up. + *

+ * + * @param c + * a {@link forge.Card} object. */ private static void playerCombatDamage_lose_halflife_up(final Card c) { final Player player = c.getController(); @@ -970,9 +1069,12 @@ public final class GameActionUtil { } /** - *

playerCombatDamage_Scalpelexis.

- * - * @param c a {@link forge.Card} object. + *

+ * playerCombatDamage_Scalpelexis. + *

+ * + * @param c + * a {@link forge.Card} object. */ private static void playerCombatDamage_Scalpelexis(Card c) { final Player player = c.getController(); @@ -1014,8 +1116,7 @@ public final class GameActionUtil { if (broken == 0) { if ((c1.getName().contains(c2.getName()) || c1.getName().contains(c3.getName()) || c1.getName().contains(c4.getName()) || c2.getName().contains(c3.getName()) - || c2.getName().contains(c4.getName()) || c3.getName().contains(c4.getName()))) - { + || c2.getName().contains(c4.getName()) || c3.getName().contains(c4.getName()))) { count = count + 1; } else { broken = 1; @@ -1048,9 +1149,12 @@ public final class GameActionUtil { } /** - *

playerCombatDamage_Spawnwrithe.

- * - * @param c a {@link forge.Card} object. + *

+ * playerCombatDamage_Spawnwrithe. + *

+ * + * @param c + * a {@link forge.Card} object. */ private static void playerCombatDamage_Spawnwrithe(final Card c) { final Player player = c.getController(); @@ -1059,8 +1163,8 @@ public final class GameActionUtil { Ability ability2 = new Ability(c, "0") { @Override public void resolve() { - CardList cl = CardFactoryUtil.makeToken("Spawnwrithe", "", crd.getController(), "2 G", new String[]{ - "Creature", "Elemental"}, 2, 2, new String[]{"Trample"}); + CardList cl = CardFactoryUtil.makeToken("Spawnwrithe", "", crd.getController(), "2 G", new String[] { + "Creature", "Elemental" }, 2, 2, new String[] { "Trample" }); for (Card c : cl) { c.setText("Whenever Spawnwrithe deals combat damage to a player, put a token that's a copy of Spawnwrithe onto the battlefield."); @@ -1077,7 +1181,6 @@ public final class GameActionUtil { } - /** Constant Elspeth_Emblem. */ public static Command Elspeth_Emblem = new Command() { @@ -1119,8 +1222,7 @@ public final class GameActionUtil { } // execute() }; - - /** Constant Koth_Emblem */ + /** Constant Koth_Emblem. */ public static Command Koth_Emblem = new Command() { private static final long serialVersionUID = -3233715310427996429L; @@ -1186,15 +1288,14 @@ public final class GameActionUtil { public void resolve() { if (getTargetCard() != null) { if (AllZoneUtil.isCardInPlay(getTargetCard()) - && CardFactoryUtil.canTarget(c, getTargetCard())) - { + && CardFactoryUtil.canTarget(c, getTargetCard())) { getTargetCard().addDamage(1, c); } } else { getTargetPlayer().addDamage(1, c); } - } //resolve() - }; //SpellAbility + } // resolve() + }; // SpellAbility ability.setKothThirdAbility(true); ability.setDescription(abCost + "This land deals 1 damage to target creature or player."); @@ -1210,10 +1311,14 @@ public final class GameActionUtil { // Special Conditions /** - *

specialConditionsMet.

- * - * @param sourceCard a {@link forge.Card} object. - * @param specialConditions a {@link java.lang.String} object. + *

+ * specialConditionsMet. + *

+ * + * @param sourceCard + * a {@link forge.Card} object. + * @param specialConditions + * a {@link java.lang.String} object. * @return a boolean. */ public static boolean specialConditionsMet(final Card sourceCard, final String specialConditions) { @@ -1294,7 +1399,8 @@ public final class GameActionUtil { } } if (specialConditions.contains("EnchantedControllerCreaturesGE")) { - CardList enchantedControllerInPlay = sourceCard.getEnchantingCard().getController().getCardsIn(Zone.Battlefield); + CardList enchantedControllerInPlay = sourceCard.getEnchantingCard().getController() + .getCardsIn(Zone.Battlefield); enchantedControllerInPlay = enchantedControllerInPlay.getType("Creature"); String maxnumber = specialConditions.split("/")[1]; if (!(enchantedControllerInPlay.size() >= Integer.valueOf(maxnumber))) { @@ -1337,9 +1443,9 @@ public final class GameActionUtil { return false; } } - - - if (specialConditions.contains("isPresent")) { // is a card of a certain type/color present? + + if (specialConditions.contains("isPresent")) { // is a card of a certain + // type/color present? String requirements = specialConditions.replaceAll("isPresent ", ""); CardList cardsinPlay = AllZoneUtil.getCardsIn(Zone.Battlefield); String[] conditions = requirements.split(","); @@ -1348,7 +1454,9 @@ public final class GameActionUtil { return false; } } - if (specialConditions.contains("isInGraveyard")) { // is a card of a certain type/color present in yard? + if (specialConditions.contains("isInGraveyard")) { // is a card of a + // certain type/color + // present in yard? String requirements = specialConditions.replaceAll("isInGraveyard ", ""); CardList cardsinYards = AllZoneUtil.getCardsIn(Zone.Graveyard); String[] conditions = requirements.split(","); @@ -1357,7 +1465,9 @@ public final class GameActionUtil { return false; } } - if (specialConditions.contains("isNotPresent")) { // is no card of a certain type/color present? + if (specialConditions.contains("isNotPresent")) { // is no card of a + // certain type/color + // present? String requirements = specialConditions.replaceAll("isNotPresent ", ""); CardList cardsInPlay = AllZoneUtil.getCardsIn(Zone.Battlefield); String[] conditions = requirements.split(","); @@ -1381,7 +1491,8 @@ public final class GameActionUtil { return false; } } - if (specialConditions.contains("isValid")) { // does this card meet the valid description? + if (specialConditions.contains("isValid")) { // does this card meet the + // valid description? String requirements = specialConditions.replaceAll("isValid ", ""); if (!sourceCard.isValid(requirements, sourceCard.getController(), sourceCard)) { return false; @@ -1409,13 +1520,13 @@ public final class GameActionUtil { } if (specialConditions.contains("ThisTurnCast")) { String valid = specialConditions.split(" ")[1]; - if(CardUtil.getThisTurnCast(valid, sourceCard).size() == 0) { + if (CardUtil.getThisTurnCast(valid, sourceCard).size() == 0) { return false; } } - if(specialConditions.contains("ThisTurnNotCast")) { + if (specialConditions.contains("ThisTurnNotCast")) { String valid = specialConditions.split(" ")[1]; - if(CardUtil.getThisTurnCast(valid, sourceCard).size() != 0) { + if (CardUtil.getThisTurnCast(valid, sourceCard).size() != 0) { return false; } } @@ -1429,23 +1540,19 @@ public final class GameActionUtil { public void execute() { - HashMap produces = new HashMap(); /* - * for future use - boolean naked = AllZoneUtil.isCardInPlay("Naked Singularity"); - boolean twist = AllZoneUtil.isCardInPlay("Reality Twist"); - //set up what they produce - produces.put("Forest", naked || twist ? "B" : "G"); - produces.put("Island", naked == true ? "G" : "U"); - if(naked) produces.put("Mountain", "U"); - else if(twist) produces.put("Mountain", "W"); - else produces.put("Mountain", "R"); - produces.put("Plains", naked || twist ? "R" : "W"); - if(naked) produces.put("Swamp", "W"); - else if(twist) produces.put("Swamp", "G"); - else produces.put("Swamp", "B"); - */ + * for future use boolean naked = + * AllZoneUtil.isCardInPlay("Naked Singularity"); boolean twist = + * AllZoneUtil.isCardInPlay("Reality Twist"); //set up what they + * produce produces.put("Forest", naked || twist ? "B" : "G"); + * produces.put("Island", naked == true ? "G" : "U"); if(naked) + * produces.put("Mountain", "U"); else if(twist) + * produces.put("Mountain", "W"); else produces.put("Mountain", + * "R"); produces.put("Plains", naked || twist ? "R" : "W"); + * if(naked) produces.put("Swamp", "W"); else if(twist) + * produces.put("Swamp", "G"); else produces.put("Swamp", "B"); + */ produces.put("Forest", "G"); produces.put("Island", "U"); produces.put("Mountain", "R"); @@ -1455,7 +1562,7 @@ public final class GameActionUtil { CardList lands = AllZoneUtil.getCardsInGame(); lands = lands.filter(CardListFilter.lands); - //remove all abilities granted by this Command + // remove all abilities granted by this Command for (Card land : lands) { ArrayList sas = land.getManaAbility(); for (SpellAbility sa : sas) { @@ -1465,7 +1572,7 @@ public final class GameActionUtil { } } - //add all appropriate mana abilities based on current types + // add all appropriate mana abilities based on current types for (Card land : lands) { if (land.isType("Swamp")) { AbilityFactory af = new AbilityFactory(); @@ -1505,8 +1612,7 @@ public final class GameActionUtil { } } // execute() - }; //stLandManaAbilities - + }; // stLandManaAbilities /** Constant Coat_of_Arms. */ public static Command Coat_of_Arms = new Command() { @@ -1544,10 +1650,8 @@ public final class GameActionUtil { if (!alreadyAdded.contains(type.get(x))) { if (!type.get(x).getType().get(x2).equals("Creature") && !type.get(x).getType().get(x2).equals("Legendary") - && !type.get(x).getType().get(x2).equals("Artifact")) - { - if (crd.isType(type.get(x).getType().get(x2))) - { + && !type.get(x).getType().get(x2).equals("Artifact")) { + if (crd.isType(type.get(x).getType().get(x2))) { alreadyAdded.add(type.get(x)); crd.addSemiPermanentAttackBoost(1); crd.addSemiPermanentDefenseBoost(1); @@ -1561,61 +1665,59 @@ public final class GameActionUtil { } // for outer } // execute }; // Coat of Arms - + private static Command Alpha_Status = new Command() { private static final long serialVersionUID = -3213793711304934358L; CardList previouslyPumped = new CardList(); ArrayList previouslyPumpedValue = new ArrayList(); - + @Override public void execute() { CardList alphaStatuses = AllZone.getHumanPlayer().getCardsIn(Zone.Battlefield).getName("Alpha Status"); alphaStatuses.addAll(AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield).getName("Alpha Status")); - + CardList allCreatures = AllZone.getHumanPlayer().getCardsIn(Zone.Battlefield).getType("Creature"); allCreatures.addAll(AllZone.getComputerPlayer().getCardsIn(Zone.Battlefield).getType("Creature")); - - for(int i=0;iHomarid. */ public static Command Homarid = new Command() { @@ -1725,8 +1826,7 @@ public final class GameActionUtil { return list.size() > 0; } - }; //Liu_Bei - + }; // Liu_Bei /** Constant Sound_the_Call_Wolf. */ public static Command Sound_the_Call_Wolf = new Command() { @@ -1754,7 +1854,7 @@ public final class GameActionUtil { return list.size(); } - }; //Sound_the_Call_Wolf + }; // Sound_the_Call_Wolf /** Constant Tarmogoyf. */ public static Command Tarmogoyf = new Command() { @@ -1857,9 +1957,7 @@ public final class GameActionUtil { for (int i = 0; i < creature.size(); i++) { c = creature.get(i); - if (((c.getAbilityText().trim().equals("") || c.isFaceDown()) - && c.getUnhiddenKeyword().size() == 0)) - { + if (((c.getAbilityText().trim().equals("") || c.isFaceDown()) && c.getUnhiddenKeyword().size() == 0)) { c.addSemiPermanentAttackBoost(2); c.addSemiPermanentDefenseBoost(2); @@ -1875,9 +1973,12 @@ public final class GameActionUtil { // if Computer has 2 Glorious Anthems, AllZone.getComputerPlay() will be // returned twice /** - *

getZone.

- * - * @param cardName a {@link java.lang.String} object. + *

+ * getZone. + *

+ * + * @param cardName + * a {@link java.lang.String} object. * @return an array of {@link forge.PlayerZone} objects. */ private static PlayerZone[] getZone(final String cardName) { @@ -1900,7 +2001,7 @@ public final class GameActionUtil { public static HashMap commands = new HashMap(); static { - //Please add cards in alphabetical order so they are easier to find + // Please add cards in alphabetical order so they are easier to find commands.put("Ajani_Avatar_Token", Ajani_Avatar_Token); commands.put("Alpha_Status", Alpha_Status); @@ -1920,30 +2021,32 @@ public final class GameActionUtil { commands.put("Umbra_Stalker", Umbra_Stalker); - ///The commands above are in alphabetical order by cardname. + // /The commands above are in alphabetical order by cardname. } - /** - *

doPowerSink.

- * - * @param p a {@link forge.Player} object. + *

+ * doPowerSink. + *

+ * + * @param p + * a {@link forge.Player} object. */ public static void doPowerSink(final Player p) { - //get all lands with mana abilities + // get all lands with mana abilities CardList lands = AllZoneUtil.getPlayerLandsInPlay(p); lands = lands.filter(new CardListFilter() { public boolean addCard(final Card c) { return c.getManaAbility().size() > 0; } }); - //tap them + // tap them for (Card c : lands) { c.tap(); } - //empty mana pool + // empty mana pool p.getManaPool().clearPool(); } -} //end class GameActionUtil +} // end class GameActionUtil diff --git a/src/main/java/forge/GameEntity.java b/src/main/java/forge/GameEntity.java index dc58a9d7ba6..cb85b8fc4ff 100644 --- a/src/main/java/forge/GameEntity.java +++ b/src/main/java/forge/GameEntity.java @@ -4,48 +4,60 @@ import java.util.ArrayList; import forge.card.spellability.SpellAbility; - +// TODO: Auto-generated Javadoc /** - *

Abstract Player class.

- * + *

+ * Abstract Player class. + *

+ * * @author Forge * @version $Id: Player.java 10091 2011-08-30 16:11:21Z Sloth $ */ public abstract class GameEntity extends MyObservable { private String name = ""; private int preventNextDamage = 0; + + /** The enchanted by. */ protected ArrayList enchantedBy = new ArrayList(); /** - *

Getter for the field name.

- * + *

+ * Getter for the field name. + *

+ * * @return a {@link java.lang.String} object. */ public String getName() { return name; } - /** - *

Setter for the field name.

- * - * @param s a {@link java.lang.String} object. + *

+ * Setter for the field name. + *

+ * + * @param s + * a {@link java.lang.String} object. */ public void setName(String s) { name = s; } - ////////////////////////// + // //////////////////////// // // methods for handling damage // - ////////////////////////// + // //////////////////////// /** - *

addDamage.

- * - * @param damage a int. - * @param source a {@link forge.Card} object. + *

+ * addDamage. + *

+ * + * @param damage + * a int. + * @param source + * a {@link forge.Card} object. */ public void addDamage(final int damage, final Card source) { int damageToDo = damage; @@ -57,10 +69,14 @@ public abstract class GameEntity extends MyObservable { } /** - *

addDamageWithoutPrevention.

- * - * @param damage a int. - * @param source a {@link forge.Card} object. + *

+ * addDamageWithoutPrevention. + *

+ * + * @param damage + * a int. + * @param source + * a {@link forge.Card} object. */ public void addDamageWithoutPrevention(final int damage, final Card source) { int damageToDo = damage; @@ -70,27 +86,39 @@ public abstract class GameEntity extends MyObservable { addDamageAfterPrevention(damageToDo, source, false); } - //This function handles damage after replacement and prevention effects are applied + // This function handles damage after replacement and prevention effects are + // applied /** - *

addDamageAfterPrevention.

- * - * @param damage a int. - * @param source a {@link forge.Card} object. - * @param isCombat a boolean. + *

+ * addDamageAfterPrevention. + *

+ * + * @param damage + * a int. + * @param source + * a {@link forge.Card} object. + * @param isCombat + * a boolean. */ public void addDamageAfterPrevention(final int damage, final Card source, final boolean isCombat) { - + } /** - *

predictDamage.

- * - * @param damage a int. - * @param source a {@link forge.Card} object. - * @param isCombat a boolean. + *

+ * predictDamage. + *

+ * + * @param damage + * a int. + * @param source + * a {@link forge.Card} object. + * @param isCombat + * a boolean. * @return a int. */ - //This function helps the AI calculate the actual amount of damage an effect would deal + // This function helps the AI calculate the actual amount of damage an + // effect would deal public int predictDamage(final int damage, final Card source, final boolean isCombat) { int restDamage = damage; @@ -101,26 +129,38 @@ public abstract class GameEntity extends MyObservable { return restDamage; } - //This should be also usable by the AI to forecast an effect (so it must not change the game state) + // This should be also usable by the AI to forecast an effect (so it must + // not change the game state) /** - *

staticDamagePrevention.

- * - * @param damage a int. - * @param source a {@link forge.Card} object. - * @param isCombat a boolean. + *

+ * staticDamagePrevention. + *

+ * + * @param damage + * a int. + * @param source + * a {@link forge.Card} object. + * @param isCombat + * a boolean. * @return a int. */ public int staticDamagePrevention(final int damage, final Card source, final boolean isCombat) { return 0; } - //This should be also usable by the AI to forecast an effect (so it must not change the game state) + // This should be also usable by the AI to forecast an effect (so it must + // not change the game state) /** - *

staticReplaceDamage.

- * - * @param damage a int. - * @param source a {@link forge.Card} object. - * @param isCombat a boolean. + *

+ * staticReplaceDamage. + *

+ * + * @param damage + * a int. + * @param source + * a {@link forge.Card} object. + * @param isCombat + * a boolean. * @return a int. */ public int staticReplaceDamage(final int damage, Card source, boolean isCombat) { @@ -128,11 +168,16 @@ public abstract class GameEntity extends MyObservable { } /** - *

replaceDamage.

- * - * @param damage a int. - * @param source a {@link forge.Card} object. - * @param isCombat a boolean. + *

+ * replaceDamage. + *

+ * + * @param damage + * a int. + * @param source + * a {@link forge.Card} object. + * @param isCombat + * a boolean. * @return a int. */ public int replaceDamage(final int damage, Card source, boolean isCombat) { @@ -140,36 +185,46 @@ public abstract class GameEntity extends MyObservable { } /** - *

preventDamage.

- * - * @param damage a int. - * @param source a {@link forge.Card} object. - * @param isCombat a boolean. + *

+ * preventDamage. + *

+ * + * @param damage + * a int. + * @param source + * a {@link forge.Card} object. + * @param isCombat + * a boolean. * @return a int. */ public int preventDamage(final int damage, Card source, boolean isCombat) { return 0; } - ////////////////////////// + // //////////////////////// // // methods for handling Damage Prevention // - ////////////////////////// + // //////////////////////// - //PreventNextDamage + // PreventNextDamage /** - *

Setter for the field preventNextDamage.

- * - * @param n a int. + *

+ * Setter for the field preventNextDamage. + *

+ * + * @param n + * a int. */ public void setPreventNextDamage(int n) { preventNextDamage = n; } /** - *

Getter for the field preventNextDamage.

- * + *

+ * Getter for the field preventNextDamage. + *

+ * * @return a int. */ public int getPreventNextDamage() { @@ -177,65 +232,106 @@ public abstract class GameEntity extends MyObservable { } /** - *

addPreventNextDamage.

- * - * @param n a int. + *

+ * addPreventNextDamage. + *

+ * + * @param n + * a int. */ public void addPreventNextDamage(int n) { preventNextDamage += n; } /** - *

subtractPreventNextDamage.

- * - * @param n a int. + *

+ * subtractPreventNextDamage. + *

+ * + * @param n + * a int. */ public void subtractPreventNextDamage(int n) { preventNextDamage -= n; } /** - *

resetPreventNextDamage.

+ *

+ * resetPreventNextDamage. + *

*/ public void resetPreventNextDamage() { preventNextDamage = 0; } - - - public boolean hasKeyword(String keyword){ - return false; - } /** + * Checks for keyword. * - * @param sa - * @return a boolean + * @param keyword the keyword + * @return true, if successful */ - public boolean canTarget(SpellAbility sa) { + public boolean hasKeyword(String keyword) { return false; } - + + /** + * Can target. + * + * @param sa the sa + * @return a boolean + */ + public boolean canTarget(SpellAbility sa) { + return false; + } + + /** + * Checks if is valid. + * + * @param Restrictions the restrictions + * @param sourceController the source controller + * @param source the source + * @return true, if is valid + */ public boolean isValid(final String Restrictions[], final Player sourceController, final Card source) { for (int i = 0; i < Restrictions.length; i++) { - if (isValid(Restrictions[i], sourceController, source)) return true; + if (isValid(Restrictions[i], sourceController, source)) + return true; } return false; - }//isValid - + }// isValid + + /** + * Checks if is valid. + * + * @param Restriction the restriction + * @param sourceController the source controller + * @param source the source + * @return true, if is valid + */ public boolean isValid(final String Restriction, final Player sourceController, final Card source) { return false; } - + + /** + * Checks for property. + * + * @param Property the property + * @param sourceController the source controller + * @param source the source + * @return true, if successful + */ public boolean hasProperty(String Property, final Player sourceController, final Card source) { return false; } - + // GameEntities can now be Enchanted /** - *

Getter for the field enchantedBy.

- * + *

+ * Getter for the field enchantedBy. + *

+ * * @return a {@link java.util.ArrayList} object. */ public final ArrayList getEnchantedBy() { @@ -243,28 +339,35 @@ public abstract class GameEntity extends MyObservable { } /** - *

Setter for the field enchantedBy.

- * - * @param list a {@link java.util.ArrayList} object. + *

+ * Setter for the field enchantedBy. + *

+ * + * @param list + * a {@link java.util.ArrayList} object. */ public final void setEnchantedBy(final ArrayList list) { enchantedBy = list; } - + /** - *

isEnchanted.

- * + *

+ * isEnchanted. + *

+ * * @return a boolean. */ public final boolean isEnchanted() { return enchantedBy.size() != 0; } - /** - *

addEnchantedBy.

- * - * @param c a {@link forge.Card} object. + *

+ * addEnchantedBy. + *

+ * + * @param c + * a {@link forge.Card} object. */ public final void addEnchantedBy(final Card c) { enchantedBy.add(c); @@ -272,17 +375,22 @@ public abstract class GameEntity extends MyObservable { } /** - *

removeEnchantedBy.

- * - * @param c a {@link forge.Card} object. + *

+ * removeEnchantedBy. + *

+ * + * @param c + * a {@link forge.Card} object. */ public final void removeEnchantedBy(final Card c) { enchantedBy.remove(c); this.updateObservers(); } - + /** - *

unEnchantAllCards.

+ *

+ * unEnchantAllCards. + *

*/ public final void unEnchantAllCards() { for (int i = 0; i < enchantedBy.size(); i++) { @@ -290,12 +398,11 @@ public abstract class GameEntity extends MyObservable { } } - - //////////////////////////////// + // ////////////////////////////// // // generic Object overrides // - ///////////////////////////////// + // /////////////////////////////// /** {@inheritDoc} */ @Override diff --git a/src/main/java/forge/Gui_DownloadPictures_LQ.java b/src/main/java/forge/Gui_DownloadPictures_LQ.java index 06d1b0c7b74..531517ea238 100644 --- a/src/main/java/forge/Gui_DownloadPictures_LQ.java +++ b/src/main/java/forge/Gui_DownloadPictures_LQ.java @@ -66,7 +66,7 @@ public class Gui_DownloadPictures_LQ extends GuiDownloader { list.add(cardPlay[i]); } } - + //add missing tokens to the list of things to download File filebase = ForgeProps.getFile(IMAGE_TOKEN); for (int i = 0; i < cardTokenLQ.length; i++) { diff --git a/src/main/java/forge/Gui_DownloadPrices.java b/src/main/java/forge/Gui_DownloadPrices.java index 2dad24421e7..7deb55729eb 100644 --- a/src/main/java/forge/Gui_DownloadPrices.java +++ b/src/main/java/forge/Gui_DownloadPrices.java @@ -1,33 +1,46 @@ package forge; -import forge.properties.ForgeProps; -import forge.properties.NewConstants.LANG.Gui_DownloadPrices.DOWNLOADPRICES; -import forge.properties.NewConstants.QUEST; - -import javax.swing.*; -import java.awt.*; -import java.io.*; +import java.awt.Point; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; import java.net.Proxy; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; + +import forge.properties.ForgeProps; +import forge.properties.NewConstants.LANG.Gui_DownloadPrices.DOWNLOADPRICES; +import forge.properties.NewConstants.QUEST; + /** - *

Gui_DownloadPrices class.

- * + *

+ * Gui_DownloadPrices class. + *

+ * * @author Forge * @version $Id$ */ public class Gui_DownloadPrices extends JFrame { - /** Constant serialVersionUID=1L */ + /** Constant serialVersionUID=1L. */ private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JButton jButton = null; /** - * This is the default constructor + * This is the default constructor. */ public Gui_DownloadPrices() { super(); @@ -35,7 +48,7 @@ public class Gui_DownloadPrices extends JFrame { } /** - * This method initializes this + * This method initializes this. */ private void initialize() { this.setSize(386, 200); @@ -44,8 +57,8 @@ public class Gui_DownloadPrices extends JFrame { } /** - * This method initializes jContentPane - * + * This method initializes jContentPane. + * * @return javax.swing.JPanel */ private JPanel getJContentPane() { @@ -58,8 +71,8 @@ public class Gui_DownloadPrices extends JFrame { } /** - * This method initializes jButton - * + * This method initializes jButton. + * * @return javax.swing.JButton */ private JButton getJButton() { @@ -70,9 +83,10 @@ public class Gui_DownloadPrices extends JFrame { jButton.setSize(158, 89); jButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - if (jButton.getText().equals("Done!")) + public void actionPerformed(final java.awt.event.ActionEvent e) { + if (jButton.getText().equals("Done!")) { Gui_DownloadPrices.this.dispose(); + } BufferedInputStream in = null; BufferedOutputStream out = null; @@ -85,14 +99,12 @@ public class Gui_DownloadPrices extends JFrame { String s = "Downloading"; try { - in = new BufferedInputStream(new URL(url) - .openConnection(p).getInputStream()); + in = new BufferedInputStream(new URL(url).openConnection(p).getInputStream()); out = new BufferedOutputStream(new FileOutputStream(f)); jButton.setText(ForgeProps.getLocalized(DOWNLOADPRICES.DOWNLOADING)); jContentPane.paintImmediately(jButton.getBounds()); - int len = 0; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); @@ -100,8 +112,7 @@ public class Gui_DownloadPrices extends JFrame { if (++x % 50 == 0) { s += "."; jButton.setText(s); - jContentPane.paintImmediately(jButton - .getBounds()); + jContentPane.paintImmediately(jButton.getBounds()); if (x >= 300) { x = 0; @@ -116,14 +127,16 @@ public class Gui_DownloadPrices extends JFrame { return; } finally { try { - if (in != null) + if (in != null) { in.close(); - if (out != null) + } + if (out != null) { out.close(); + } } catch (IOException ex) { return; } - }// while - read and write file + } // while - read and write file FileReader fr = null; FileWriter fw = null; @@ -144,7 +157,7 @@ public class Gui_DownloadPrices extends JFrame { x = 0; s = "Compiling"; while (line != null && !line.equals("")) { - String ll[] = line.split("\\|"); + String[] ll = line.split("\\|"); if (ll[0].contains("(")) { int indx = ll[0].indexOf(" ("); @@ -160,21 +173,25 @@ public class Gui_DownloadPrices extends JFrame { if (cp >= inp) { fScl = 1 - (float) inp / (float) cp; - if (fScl > .333) + if (fScl > .333) { cp = cp / 2; + } } else { fScl = 1 - (float) cp / (float) inp; - if (fScl > .333) + if (fScl > .333) { inp = inp / 2; + } } int ap = (cp + inp) / 2; - if (ap < 7) + if (ap < 7) { ap += 10; + } prices.put(ll[0], ap); } else { - if (inp < 7) + if (inp < 7) { inp += 10; + } prices.put(ll[0], inp); } @@ -185,8 +202,7 @@ public class Gui_DownloadPrices extends JFrame { if (++x % 100 == 0) { s += "."; jButton.setText(s); - jContentPane.paintImmediately(jButton - .getBounds()); + jContentPane.paintImmediately(jButton.getBounds()); if (x >= 500) { x = 0; @@ -195,14 +211,12 @@ public class Gui_DownloadPrices extends JFrame { } } - String pfn = ForgeProps.getFile(QUEST.PRICE) - .getAbsolutePath(); + String pfn = ForgeProps.getFile(QUEST.PRICE).getAbsolutePath(); String pfnb = pfn.replace(".txt", ".bak"); File ff = new File(pfn); ff.renameTo(new File(pfnb)); - fw = new FileWriter(ForgeProps - .getFile(QUEST.PRICE)); + fw = new FileWriter(ForgeProps.getFile(QUEST.PRICE)); BufferedWriter outBW = new BufferedWriter(fw); // Collection keys = prices.keySet(); @@ -213,24 +227,22 @@ public class Gui_DownloadPrices extends JFrame { for (int i = 0; i < keys.size(); i++) { // keys.add(key); String k = keys.get(i); - if (k.equals("Plains") || k.equals("Island") - || k.equals("Swamp") - || k.equals("Mountain") + if (k.equals("Plains") || k.equals("Island") || k.equals("Swamp") || k.equals("Mountain") || k.equals("Forest")) + { outBW.write(k + "=5\r\n"); - - else if (k.equals("Snow-Covered Plains") - || k.equals("Snow-Covered Island") - || k.equals("Snow-Covered Swamp") - || k.equals("Snow-Covered Mountain") + } else if (k.equals("Snow-Covered Plains") || k.equals("Snow-Covered Island") + || k.equals("Snow-Covered Swamp") || k.equals("Snow-Covered Mountain") || k.equals("Snow-Covered Forest")) + { outBW.write(k + "=10\r\n"); - else - outBW.write(keys.get(i) + "=" - + prices.get(keys.get(i)) + "\r\n"); + } else { + outBW.write(keys.get(i) + "=" + prices.get(keys.get(i)) + "\r\n"); + } - if (i % 100 == 0) + if (i % 100 == 0) { outBW.flush(); + } } outBW.flush(); @@ -244,10 +256,12 @@ public class Gui_DownloadPrices extends JFrame { return; } finally { try { - if (fr != null) + if (fr != null) { fr.close(); - if (fw != null) + } + if (fw != null) { fw.close(); + } } catch (IOException ex) { return; }