diff --git a/.gitattributes b/.gitattributes index 4a84b9da627..7f382759944 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9514,7 +9514,6 @@ src/main/java/forge/CardListFilter.java svneol=native#text/plain src/main/java/forge/CardListUtil.java svneol=native#text/plain src/main/java/forge/CardPowerToughness.java svneol=native#text/plain src/main/java/forge/CardReader.java svneol=native#text/plain -src/main/java/forge/CardShopTableModel.java svneol=native#text/plain src/main/java/forge/CardUtil.java svneol=native#text/plain src/main/java/forge/Card_Color.java svneol=native#text/plain src/main/java/forge/Card_Type.java svneol=native#text/plain @@ -9539,7 +9538,6 @@ src/main/java/forge/CopyFiles.java svneol=native#text/plain src/main/java/forge/Counters.java svneol=native#text/plain src/main/java/forge/CustomDraft.java svneol=native#text/plain src/main/java/forge/DeckColors.java svneol=native#text/plain -src/main/java/forge/DeckDisplay.java svneol=native#text/plain src/main/java/forge/DefaultPlayerZone.java svneol=native#text/plain src/main/java/forge/Display.java svneol=native#text/plain src/main/java/forge/EndOfCombat.java svneol=native#text/plain @@ -9554,15 +9552,7 @@ src/main/java/forge/GameActionUtil.java svneol=native#text/plain src/main/java/forge/GameEntity.java -text src/main/java/forge/GuiDisplay4.java svneol=native#text/plain src/main/java/forge/GuiDisplayUtil.java svneol=native#text/plain -src/main/java/forge/GuiFilter.java svneol=native#text/plain -src/main/java/forge/GuiFilterCheckBox.java svneol=native#text/plain src/main/java/forge/GuiInput.java svneol=native#text/plain -src/main/java/forge/GuiQuestFilter.java svneol=native#text/plain -src/main/java/forge/Gui_BoosterDraft.java svneol=native#text/plain -src/main/java/forge/Gui_CardShop.java svneol=native#text/plain -src/main/java/forge/Gui_DeckEditor.java svneol=native#text/plain -src/main/java/forge/Gui_DeckEditorBase.java -text -src/main/java/forge/Gui_DeckEditor_Menu.java svneol=native#text/plain src/main/java/forge/Gui_DownloadPictures_LQ.java svneol=native#text/plain src/main/java/forge/Gui_DownloadPrices.java svneol=native#text/plain src/main/java/forge/Gui_DownloadSetPictures_LQ.java svneol=native#text/plain @@ -9571,8 +9561,6 @@ src/main/java/forge/Gui_MultipleBlockers4.java svneol=native#text/plain src/main/java/forge/Gui_NewGame.java svneol=native#text/plain src/main/java/forge/Gui_ProgressBarWindow.java svneol=native#text/plain src/main/java/forge/Gui_QuestOptions.java svneol=native#text/plain -src/main/java/forge/Gui_Quest_DeckEditor.java svneol=native#text/plain -src/main/java/forge/Gui_Quest_DeckEditor_Menu.java svneol=native#text/plain src/main/java/forge/Gui_WinLose.java svneol=native#text/plain src/main/java/forge/HandSizeOp.java svneol=native#text/plain src/main/java/forge/HttpUtil.java svneol=native#text/plain @@ -9606,8 +9594,6 @@ src/main/java/forge/SimpleCombat.java svneol=native#text/plain src/main/java/forge/Singletons.java svneol=native#text/plain src/main/java/forge/StaticEffect.java svneol=native#text/plain src/main/java/forge/StaticEffects.java svneol=native#text/plain -src/main/java/forge/TableModel.java svneol=native#text/plain -src/main/java/forge/TableSorter.java svneol=native#text/plain src/main/java/forge/Time.java svneol=native#text/plain src/main/java/forge/UndoCommand.java svneol=native#text/plain src/main/java/forge/Upkeep.java svneol=native#text/plain @@ -9781,6 +9767,24 @@ src/main/java/forge/gui/ListChooser.java svneol=native#text/plain src/main/java/forge/gui/MultiLineLabel.java svneol=native#text/plain src/main/java/forge/gui/MultiLineLabelUI.java svneol=native#text/plain src/main/java/forge/gui/MultiPhaseProgressMonitorWithETA.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/CardColumnPresets.java -text +src/main/java/forge/gui/deckeditor/CardDisplay.java -text +src/main/java/forge/gui/deckeditor/CardShop.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/CardViewPanel.java -text +src/main/java/forge/gui/deckeditor/CardViewPanelLite.java -text +src/main/java/forge/gui/deckeditor/DeckDisplay.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/DeckEditor.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/DeckEditorBase.java -text +src/main/java/forge/gui/deckeditor/DeckEditorMenu.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/DeckEditorQuest.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/DeckEditorQuestMenu.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/FilterCheckBoxes.java -text +src/main/java/forge/gui/deckeditor/GuiFilterCheckBox.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/Gui_BoosterDraft.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/TableColumnInfo.java -text +src/main/java/forge/gui/deckeditor/TableModel.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/TableSorter.java svneol=native#text/plain +src/main/java/forge/gui/deckeditor/package-info.java -text src/main/java/forge/gui/game/CardDetailPanel.java svneol=native#text/plain src/main/java/forge/gui/game/CardPanel.java svneol=native#text/plain src/main/java/forge/gui/game/CardPicturePanel.java svneol=native#text/plain @@ -9899,11 +9903,9 @@ src/test/java/forge/GameActionTest.java svneol=native#text/plain src/test/java/forge/GuiBoosterDraftTest.java svneol=native#text/plain src/test/java/forge/GuiDownloadPicturesLQTest.java svneol=native#text/plain src/test/java/forge/GuiDownloadSetPicturesLQTest.java svneol=native#text/plain -src/test/java/forge/GuiFilterTest.java svneol=native#text/plain src/test/java/forge/GuiMigrateLocalMWSSetPicturesHQTest.java svneol=native#text/plain src/test/java/forge/GuiMultipleBlockers4Test.java svneol=native#text/plain src/test/java/forge/GuiProgressBarWindowTest.java svneol=native#text/plain -src/test/java/forge/GuiQuestFilterTest.java svneol=native#text/plain src/test/java/forge/GuiQuestOptionsTest.java svneol=native#text/plain src/test/java/forge/GuiWinLoseTest.java svneol=native#text/plain src/test/java/forge/PanelTest.java svneol=native#text/plain diff --git a/src/main/java/forge/BoosterDraft.java b/src/main/java/forge/BoosterDraft.java index 0b26d4e25a2..dad2959a21e 100644 --- a/src/main/java/forge/BoosterDraft.java +++ b/src/main/java/forge/BoosterDraft.java @@ -1,5 +1,7 @@ package forge; +import forge.card.CardPoolView; +import forge.card.CardPrinted; import forge.deck.Deck; import java.util.Map; import java.util.TreeMap; @@ -16,14 +18,14 @@ public interface BoosterDraft { * * @return a {@link forge.CardList} object. */ - public CardList nextChoice(); + public CardPoolView nextChoice(); /** *

setChoice.

* * @param c a {@link forge.Card} object. */ - public void setChoice(Card c); + public void setChoice(CardPrinted c); /** *

hasNextChoice.

diff --git a/src/main/java/forge/BoosterDraftAI.java b/src/main/java/forge/BoosterDraftAI.java index d0437ea18de..e61783f8241 100644 --- a/src/main/java/forge/BoosterDraftAI.java +++ b/src/main/java/forge/BoosterDraftAI.java @@ -37,22 +37,22 @@ public class BoosterDraftAI { /** *

choose.

* - * @param in_choose a {@link forge.CardList} object. + * @param chooseFrom a {@link forge.CardList} object. * @param player a int. * @return a {@link forge.CardList} object. */ - public CardList choose(final CardList in_choose, int player) { + public Card choose(final CardList chooseFrom, int player) { //in_choose should ONLY be on the RIGHT side of any equal sign //only 1 card should be removed from in_choose if (Constant.Runtime.DevMode[0]) - System.out.println("Player[" + player + "] pack: " + in_choose.toString()); + System.out.println("Player[" + player + "] pack: " + chooseFrom.toString()); - CardList list = new CardList(); + CardList wouldPick = new CardList(); boolean hasPicked = false; Card pickedCard = new Card(); - CardList AIPlayables = in_choose.filter(new CardListFilter() { + CardList AIPlayables = chooseFrom.filter(new CardListFilter() { public boolean addCard(Card c) { if (c.getSVar("RemAIDeck").equals("True") || c.getSVar("RemRandomDeck").equals("True")) return false; @@ -112,32 +112,32 @@ public class BoosterDraftAI { if (typeList.size() > 0) { typeList.sort(bestCreature); typeList.reverse(); - list.add(typeList.get(0)); + wouldPick.add(typeList.get(0)); if (typeList.size() > 1) - list.add(typeList.get(1)); + wouldPick.add(typeList.get(1)); } typeList = colorList.getType("Instant"); typeList.addAll(colorList.getType("Sorcery")); if (typeList.size() > 0) { CardListUtil.sortCMC(typeList); - list.add(typeList.get(typeList.size() / 2)); + wouldPick.add(typeList.get(typeList.size() / 2)); } typeList = colorList.getType("Enchantment"); if (typeList.size() > 0) { CardListUtil.sortCMC(typeList); - list.add(typeList.get(0)); + wouldPick.add(typeList.get(0)); } typeList = colorList.getType("Planeswalker"); if (typeList.size() > 0) - list.add(typeList.get(0)); + wouldPick.add(typeList.get(0)); typeList = colorList.getType("Artifact"); if (typeList.size() > 0) { CardListUtil.sortCMC(typeList); - list.add(typeList.get(0)); + wouldPick.add(typeList.get(0)); } } else { @@ -177,7 +177,7 @@ public class BoosterDraftAI { ArrayList maList = typeList.get(i).getManaAbility(); for (int j = 0; j < maList.size(); j++) { if (maList.get(j).canProduce(playerColors.get(player).Mana1) || maList.get(j).canProduce(playerColors.get(player).Mana2)) //|| maList.get(j).canProduce(playerColors.get(player).ManaS)) - list.add(typeList.get(i)); + wouldPick.add(typeList.get(i)); } } } @@ -188,28 +188,27 @@ public class BoosterDraftAI { if (!hasPicked) { Random r = new Random(); - if (list.size() > 0) { - list.shuffle(); - pickedCard = list.get(r.nextInt(list.size())); - hasPicked = true; + if (wouldPick.size() > 0) { + wouldPick.shuffle(); + pickedCard = wouldPick.get(r.nextInt(wouldPick.size())); } else { - in_choose.shuffle(); - pickedCard = in_choose.get(r.nextInt(in_choose.size())); - hasPicked = true; + chooseFrom.shuffle(); + pickedCard = chooseFrom.get(r.nextInt(chooseFrom.size())); } - + + hasPicked = true; } if (hasPicked) { - in_choose.remove(pickedCard); + chooseFrom.remove(pickedCard); deck[player].add(pickedCard); if (Constant.Runtime.DevMode[0]) System.out.println("Player[" + player + "] picked " + pickedCard.getName() + " (" + pickedCard.getManaCost() + ") " + pickedCard.getType().toString() + "\n"); } - return in_choose; - }//choose() + return pickedCard; + } /* I get some wierd error when I have this method, I don't know whats wrong diff --git a/src/main/java/forge/BoosterDraft_1.java b/src/main/java/forge/BoosterDraft_1.java index 62af763016b..a2699bb12b1 100644 --- a/src/main/java/forge/BoosterDraft_1.java +++ b/src/main/java/forge/BoosterDraft_1.java @@ -1,11 +1,16 @@ package forge; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; import forge.deck.Deck; import forge.gui.GuiUtils; import javax.swing.*; import java.io.File; import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; public class BoosterDraft_1 implements BoosterDraft { private final BoosterDraftAI draftAI = new BoosterDraftAI(); @@ -14,7 +19,7 @@ public class BoosterDraft_1 implements BoosterDraft { private static int stopCount = 45; //boosterPackSize * 3;//should total of 45 private int currentCount = 0; - private CardList[] pack;//size 8 + private List> pack;//size 8 //private BoosterGenerator packs[] = {new BoosterGenerator(), new BoosterGenerator(), new BoosterGenerator()}; private ArrayList packs = new ArrayList(); private int packNum = 0; @@ -206,13 +211,12 @@ public class BoosterDraft_1 implements BoosterDraft { * * @return a {@link forge.CardList} object. */ - public CardList nextChoice() { - if (pack[getMod()].size() == 0) + public CardPoolView nextChoice() { + if (pack.get(getCurrentBoosterIndex()).size() == 0) pack = get8BoosterPack(); computerChoose(); - CardList list = pack[getMod()]; - return list; + return new CardPool(pack.get(getCurrentBoosterIndex())); } /** @@ -220,25 +224,12 @@ public class BoosterDraft_1 implements BoosterDraft { * * @return an array of {@link forge.CardList} objects. */ - public CardList[] get8BoosterPack() { - CardList[] list = new CardList[] - {//nPlayers is 8 - new CardList(), - new CardList(), - new CardList(), - new CardList(), - - new CardList(), - new CardList(), - new CardList(), - new CardList(), - }; - //ReadDraftBoosterPack pack = new ReadDraftBoosterPack(); + public List> get8BoosterPack() { + List> list = new ArrayList>(); if (packNum < packs.size()) { - for (int i = 0; i < list.length; i++) - //list[i].addAll(pack.getBoosterPack()); - list[i].addAll(packs.get(packNum).getBoosterPack()); + for (int i = 0; i < 8; i++) + list.add(packs.get(packNum).getBoosterPack()); } packNum++; @@ -258,13 +249,29 @@ public class BoosterDraft_1 implements BoosterDraft { } private void computerChoose() { - int row[] = computerChoose[getMod()]; + int row[] = computerChoose[getCurrentBoosterIndex()]; - for (int i = 0; i < row.length; i++) - draftAI.choose(pack[row[i]], i); + for (int i = 0; i < row.length; i++) { + CardList forAi = new CardList(); + List booster = pack.get(row[i]); + for (CardPrinted cr : booster) { + forAi.add(cr.toForgeCard()); + } + // TODO: Please write this drafting code to work without heavy cards + Card aiPick = draftAI.choose(forAi, i); + String pickedName = aiPick.getName(); + + for (int pick = booster.size()-1; pick >= 0; pick--) { + CardPrinted cp = booster.get(pick); + if (cp.getName().equalsIgnoreCase(pickedName)) { + booster.remove(pick); + break; + } + } + } }//computerChoose() - private int getMod() { + private int getCurrentBoosterIndex() { return currentCount % nPlayers; } @@ -278,20 +285,20 @@ public class BoosterDraft_1 implements BoosterDraft { } /** {@inheritDoc} */ - public void setChoice(Card c) { - CardList list = pack[getMod()]; + public void setChoice(CardPrinted c) { + List thisBooster = pack.get(getCurrentBoosterIndex()); - if (!list.contains(c)) - throw new RuntimeException("BoosterDraft : setChoice() error - card not found - " + c + " - booster pack = " + list); + if (!thisBooster.contains(c)) + throw new RuntimeException("BoosterDraft : setChoice() error - card not found - " + c + " - booster pack = " + thisBooster); if (Constant.Runtime.UpldDrft[0]) { - for (int i = 0; i < list.size(); i++) { - Card cc = list.get(i); - String CnBk = cc.getName() + "|" + cc.getCurSetCode(); + for (int i = 0; i < thisBooster.size(); i++) { + CardPrinted cc = thisBooster.get(i); + String CnBk = cc.getName() + "|" + cc.getSet(); float pickValue = 0; if (cc.equals(c)) - pickValue = (float)list.size() * (((((float)stopCount - (float)currentCount) * 100) / (float)stopCount) / 50); + pickValue = thisBooster.size() * (1f - ((float) currentCount) / stopCount) * 2f; else pickValue = 0; @@ -305,7 +312,7 @@ public class BoosterDraft_1 implements BoosterDraft { } } - list.remove(c); + thisBooster.remove(c); currentCount++; }//setChoice() } diff --git a/src/main/java/forge/BoosterGenerator.java b/src/main/java/forge/BoosterGenerator.java index fb2d938596e..59b2a87a73e 100644 --- a/src/main/java/forge/BoosterGenerator.java +++ b/src/main/java/forge/BoosterGenerator.java @@ -1,12 +1,20 @@ package forge; +import forge.card.CardDb; +import forge.card.CardPoolView; +import forge.card.CardPrinted; import forge.deck.Deck; import forge.deck.DeckManager; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.Map.Entry; import java.util.Random; +import net.slightlymagic.maxmtg.Predicate; + /** *

BoosterGenerator class.

* @@ -14,11 +22,11 @@ import java.util.Random; * @version $Id$ */ public class BoosterGenerator { - private CardList commons = new CardList(); - private CardList uncommons = new CardList(); - private CardList rares = new CardList(); - private CardList mythics = new CardList(); - private CardList specials = new CardList(); + private List commons = new ArrayList(); + private List uncommons = new ArrayList(); + private List rares = new ArrayList(); + private List mythics = new ArrayList(); + private List specials = new ArrayList(); private int iCommons = 0; private int iUncommons = 0; @@ -44,47 +52,14 @@ public class BoosterGenerator { numMythics = 0; numSpecials = 0; - for (Card c : AllZone.getCardFactory()) { - SetInfo si = SetInfoUtil.getSetInfo_Code(c.getSets(), SetInfoUtil.getMostRecentSet(c.getSets())); - - addToRarity(c, si); + + for (CardPrinted c : CardDb.instance().getAllUniqueCards()) { + addToRarity(c); } shuffleAll(); - -/* //reduce cardpool to approximate the size of a small set (175) for better drafting in full mode - tList.clear(); - for (int i=0; i<100; i++) // 8 x 11 x 3 commons = 264 cards with each card showing up about once per round - tList.add(commons.get(i)); - commons.clear(); - commons.addAll(tList); - - tList.clear(); - for (int i=0; i<50; i++) // 8 x 3 x 3 uncommons = 72 cards with some cards showing up twice - tList.add(uncommons.get(i)); - uncommons.clear(); - uncommons.addAll(tList); - - tList.clear(); - for (int i=0; i<25; i++) // 8 x 1 x 3 rares = 24 cards with no cards - tList.add(rares.get(i)); - rares.clear(); - rares.addAll(tList); - - // don't worry about reducing the mythics -*/ } + } - /** - *

Constructor for BoosterGenerator.

- * - * @param DeckFile a {@link java.lang.String} object. - * @param nCommons a int. - * @param nUncommons a int. - * @param nRares a int. - * @param nMythics a int. - * @param nSpecials a int. - * @param ignoreRarity a boolean. - */ public BoosterGenerator(String DeckFile, int nCommons, int nUncommons, int nRares, int nMythics, int nSpecials, boolean ignoreRarity) { numCommons = nCommons; numUncommons = nUncommons; @@ -98,41 +73,10 @@ public class BoosterGenerator { if (dPool == null) throw new RuntimeException("BoosterGenerator : deck not found - " + DeckFile); - CardList cList = new CardList(); - List tList = dPool.getMain(); - - for (int i = 0; i < tList.size(); i++) { - String cardName = tList.get(i); - String setCode = ""; - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - setCode = s[1]; - } - - Card c = AllZone.getCardFactory().getCard(cardName, AllZone.getHumanPlayer()); - - if (!setCode.equals("")) - c.setCurSetCode(setCode); - else if ((c.getSets().size() > 0)) // && card.getCurSetCode().equals("")) - c.setRandomSetCode(); - - cList.add(c); - } - - - for (int i = 0; i < cList.size(); i++) { - Card c = cList.get(i); - SetInfo si = null; - if (c.getCurSetCode().equals("")) - si = SetInfoUtil.getSetInfo_Code(c.getSets(), SetInfoUtil.getMostRecentSet(c.getSets())); - else - si = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()); - - if (ignoreRarity) - commons.add(c); - else - addToRarity(c, si); + CardPoolView tList = dPool.getMain(); + for (Entry e : tList) { + if (ignoreRarity) { commons.add(e.getKey()); } + else { addToRarity(e.getKey()); } } shuffleAll(); @@ -143,31 +87,24 @@ public class BoosterGenerator { * * @param SetCode a {@link java.lang.String} object. */ - public BoosterGenerator(final String SetCode) { + public BoosterGenerator(final String setCode) { numCommons = 0; numUncommons = 0; numRares = 0; numMythics = 0; numSpecials = 0; - for (Card c : AllZone.getCardFactory()) { - SetInfo si = SetInfoUtil.getSetInfo_Code(c.getSets(), SetCode); + List setsList = Arrays.asList(new String[]{ setCode }); + Predicate filter = CardPrinted.Predicates.printedInSets(setsList, true); + List cardsInThisSet = filter.select(CardDb.instance().getAllCards()); - if (si != null) { - c.setCurSetCode(SetCode); - - Random r = new Random(); - int n = si.PicCount; - if (n > 1) - c.setRandomPicture(r.nextInt(n - 1) + 1); - - addToRarity(c, si); - } + for (CardPrinted c : cardsInThisSet) { + addToRarity(c); } shuffleAll(); - ArrayList bpData = FileUtil.readFile("res/boosterdata/" + SetCode + ".pack"); + ArrayList bpData = FileUtil.readFile("res/boosterdata/" + setCode + ".pack"); for (String line : bpData) { if (line.startsWith("Commons:")) { @@ -194,46 +131,16 @@ public class BoosterGenerator { } - /** - *

addToRarity.

- * - * @param c a {@link forge.Card} object. - * @param si a {@link forge.SetInfo} object. - */ - private void addToRarity(Card c, SetInfo si) { - if (si != null) { - if (si.Rarity.equals("Common")) - commons.add(c); - else if (si.Rarity.equals("Uncommon")) - uncommons.add(c); - else if (si.Rarity.equals("Rare")) - rares.add(c); - else if (si.Rarity.equals("Mythic")) - mythics.add(c); - else if (si.Rarity.equals("Special")) - specials.add(c); - } - } - /** *

shuffleAll.

*/ private void shuffleAll() { - if (commons.size() > 0) - commons.shuffle(); - - if (uncommons.size() > 0) - uncommons.shuffle(); - - if (rares.size() > 0) - rares.shuffle(); - - if (mythics.size() > 0) - mythics.shuffle(); - - if (specials.size() > 0) - specials.shuffle(); + if (!commons.isEmpty()) { Collections.shuffle(commons, MyRandom.random); } + if (!uncommons.isEmpty()) { Collections.shuffle(uncommons, MyRandom.random); } + if (!rares.isEmpty()) { Collections.shuffle(rares, MyRandom.random); } + if (!mythics.isEmpty()) { Collections.shuffle(mythics, MyRandom.random); } + if (!specials.isEmpty()) { Collections.shuffle(specials, MyRandom.random); } if (Constant.Runtime.DevMode[0]) { System.out.println("commons.size: " + commons.size()); @@ -249,8 +156,8 @@ public class BoosterGenerator { * * @return a {@link forge.CardList} object. */ - public CardList getBoosterPack() { - CardList temp = new CardList(); + public List getBoosterPack() { + List temp = new ArrayList(); int i = 0; @@ -317,4 +224,16 @@ public class BoosterGenerator { public int getBoosterPackSize() { return numCommons + numUncommons + numRares + numSpecials; } + + private void addToRarity(CardPrinted c) { + switch(c.getRarity()) { + case Common: commons.add(c); break; + case Uncommon: uncommons.add(c); break; + case Rare: rares.add(c); break; + case MythicRare: mythics.add(c); break; + case Special: specials.add(c); break; + default: return; + } + } + } diff --git a/src/main/java/forge/CardShopTableModel.java b/src/main/java/forge/CardShopTableModel.java deleted file mode 100644 index 1dab7566254..00000000000 --- a/src/main/java/forge/CardShopTableModel.java +++ /dev/null @@ -1,398 +0,0 @@ -package forge; - - -import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; -import java.awt.event.*; -import java.util.Arrays; - - -/** - *

CardShopTableModel class.

- * - * @author Forge - * @version $Id$ - */ -class CardShopTableModel extends AbstractTableModel { - - /** Constant serialVersionUID=1L */ - private static final long serialVersionUID = 1L; - - //holds 1 copy of each card, DOES NOT HOLD multiple cards with the same name - private CardList dataNoCopies = new CardList(); - - //holds multiple card - //example: if there are 4 Elvish Pipers, dataNoCopies has 1 copy, and dataCopies has 3 - private CardList dataCopies = new CardList(); - - //used by sort(), holds old data to compare with sorted data, to see if any change was made - //private CardList oldList = new CardList(); - - private CardContainer cardDetail; - private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "R", "Value"}; - - //used to resort(), used when addCard(Card) is called - private int recentSortedColumn; - private boolean recentAscending; - - /** - *

Constructor for CardShopTableModel.

- * - * @param cd a {@link forge.CardContainer} object. - */ - public CardShopTableModel(CardContainer cd) { - this(new CardList(), cd); - } - - /** - *

Constructor for CardShopTableModel.

- * - * @param inData a {@link forge.CardList} object. - * @param in_cardDetail a {@link forge.CardContainer} object. - */ - public CardShopTableModel(CardList inData, CardContainer in_cardDetail) { - cardDetail = in_cardDetail; - //intialize dataNoCopies and dataCopies - addCard(inData); - } - - - /** - *

resizeCols.

- * - * @param table a {@link javax.swing.JTable} object. - */ - public void resizeCols(final JTable table) { - TableColumn column = null; - for (int i = 0; i < table.getColumnCount(); i++) { - column = table.getColumnModel().getColumn(i); - - if (i == 0) { - column.setPreferredWidth(25); //make first column small - column.setMaxWidth(25); - } else if (i == 1) { - column.setPreferredWidth(190); - column.setMinWidth(190); - column.setMaxWidth(190); - } else if (i == 2) { - column.setPreferredWidth(85); - column.setMinWidth(85); - column.setMaxWidth(126); - } else if (i == 3) { - column.setPreferredWidth(58); - column.setMaxWidth(58); - } else if (i == 4) column.setPreferredWidth(130); - else if (i == 5) { - column.setPreferredWidth(32); - column.setMaxWidth(42); - } else if (i == 6) { - column.setPreferredWidth(20); - column.setMaxWidth(20); - } else if (i == 7) { - column.setPreferredWidth(40); - column.setMaxWidth(40); - } - }//for - - /*for(int j = 0; j < table.getColumnCount(); j++) { - column = table.getColumnModel().getColumn(j); - //System.out.println("col Width:" + column.getPreferredWidth()); - }*/ - } - - /** - *

clear.

- */ - public void clear() { - dataNoCopies.clear(); - dataCopies.clear(); - //fireTableDataChanged(); - } - - /** - *

getCards.

- * - * @return a {@link forge.CardList} object. - */ - public CardList getCards() { - CardList all = new CardList(); - all.addAll(dataCopies); - all.addAll(dataNoCopies); - - return all; - } - - /** - *

removeCard.

- * - * @param c a {@link forge.Card} object. - */ - public void removeCard(Card c) { - //remove card from "dataCopies", - //if not found there, remove card from "dataNoCopies" - int index = findCardName(c.getName(), dataCopies); - - if (index != -1) //found card name - dataCopies.remove(index); - else { - index = findCardName(c.getName(), dataNoCopies); - dataNoCopies.remove(index); - } - - fireTableDataChanged(); - } - - /** - *

findCardName.

- * - * @param name a {@link java.lang.String} object. - * @param list a {@link forge.CardList} object. - * @return a int. - */ - private int findCardName(String name, CardList list) { - for (int i = 0; i < list.size(); i++) - if (list.get(i).getName().equals(name)) return i; - - return -1; - } - - /** - *

addCard.

- * - * @param c a {@link forge.Card} object. - */ - public void addCard(Card c) { - if (0 == countQuantity(c, dataNoCopies)) dataNoCopies.add(c); - else dataCopies.add(c); - } - - /** - *

addCard.

- * - * @param c a {@link forge.CardList} object. - */ - public void addCard(CardList c) { - for (int i = 0; i < c.size(); i++) - addCard(c.get(i)); - - fireTableDataChanged(); - } - - /** - *

rowToCard.

- * - * @param row a int. - * @return a {@link forge.Card} object. - */ - public Card rowToCard(int row) { - return dataNoCopies.get(row); - } - - /** - *

countQuantity.

- * - * @param c a {@link forge.Card} object. - * @return a int. - */ - private int countQuantity(Card c) { - return countQuantity(c, dataNoCopies) + countQuantity(c, dataCopies); - } - - //CardList data is either class members "dataNoCopies" or "dataCopies" - /** - *

countQuantity.

- * - * @param c a {@link forge.Card} object. - * @param data a {@link forge.CardList} object. - * @return a int. - */ - private int countQuantity(Card c, CardList data) { - int count = 0; - for (int i = 0; i < data.size(); i++) - //are the card names the same? - if (data.get(i).getName().equals(c.getName())) count++; - - return count; - } - - /** - *

getRowCount.

- * - * @return a int. - */ - public int getRowCount() { - return dataNoCopies.size(); - } - - /** - *

getColumnCount.

- * - * @return a int. - */ - public int getColumnCount() { - return column.length; - } - - /** {@inheritDoc} */ - @Override - public String getColumnName(int n) { - return column[n]; - } - - /** {@inheritDoc} */ - public Object getValueAt(int row, int column) { - return getColumn(dataNoCopies.get(row), column); - } - - /** - *

Getter for the field column.

- * - * @param c a {@link forge.Card} object. - * @param column a int. - * @param column a int. - * @return a {@link java.lang.Object} object. - */ - private Object getColumn(Card c, int column) { - switch (column) { - case 0: - return Integer.valueOf(countQuantity(c)); - case 1: - return c.getName(); - case 2: - return c.getManaCost(); - case 3: - return TableSorter.getColor(c); - case 4: - return GuiDisplayUtil.formatCardType(c); - case 5: - return c.isCreature() ? c.getBaseAttack() + "/" + c.getBaseDefense() : ""; - case 6: - String rarity = c.getRarity(); - if (rarity.length() > 0) rarity = rarity.substring(0, 1); - return rarity; - case 7: - long value = c.getValue(); - return value; - default: - return "error"; - } - } - - /** - *

addListeners.

- * - * @param table a {@link javax.swing.JTable} object. - */ - public void addListeners(final JTable table) { - //updates card detail, listens to any key strokes - table.getSelectionModel().addListSelectionListener( new ListSelectionListener() { - - @Override - public void valueChanged(ListSelectionEvent arg0) { - int row = table.getSelectedRow(); - if (row != -1) { - cardDetail.setCard(dataNoCopies.get(row)); - } - } - - }); - - - //sorts - MouseListener mouse = new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - TableColumnModel columnModel = table.getColumnModel(); - int viewColumn = columnModel.getColumnIndexAtX(e.getX()); - int column = table.convertColumnIndexToModel(viewColumn); - - - if (column != -1) { - //sort ascending - @SuppressWarnings("unused") - boolean change = sort(column, true); - - //if(! change) - // sort(column, false);//sort descending - - //fireTableDataChanged(); - } - }//mousePressed() - };//MouseListener - table.getTableHeader().addMouseListener(mouse); - }//addCardListener() - - //called by the GUI when a card is added to re-sort - /** - *

resort.

- */ - public void resort() { - sort(recentSortedColumn, recentAscending); - //this.fireTableDataChanged(); - } - - //returns true if any data changed positions - // @SuppressWarnings("unchecked") - // Arrays.sort - /** - *

sort.

- * - * @param column a int. - * @param ascending a boolean. - * @return a boolean. - */ - public boolean sort(int column, boolean ascending) { - //used by addCard() to resort the cards - recentSortedColumn = column; - recentAscending = ascending; - - CardList all = new CardList(); - all.addAll(dataNoCopies); - all.addAll(dataCopies); - - TableSorter sorter = new TableSorter(all, column, ascending); - Card[] array = all.toArray(); - Arrays.sort(array, sorter); - - /* - //determine if any data changed position - boolean hasChanged = false; - CardList check = removeDuplicateNames(array); - for(int i = 0; i < check.size(); i++) - //do the card names match? - if(! check.get(i).getName().equals(dataNoCopies.get(i).getName())) - hasChanged = true; - */ - - //clear everything, and add sorted data back into the model - dataNoCopies.clear(); - dataCopies.clear(); - addCard(new CardList(array)); - - //this value doesn't seem to matter: - //return hasChanged; - return true; - }//sort() - /* - private CardList removeDuplicateNames(Card[] c) - { - TreeSet check = new TreeSet(); - CardList list = new CardList(); - - for(int i = 0; i < c.length; i++) - { - if(! check.contains(c[i].getName())) - { - check.add(c[i].getName()); - list.add(c[i]); - } - } - - return list; - } - */ -}//CardTableModel diff --git a/src/main/java/forge/GUI_DeckAnalysis.java b/src/main/java/forge/GUI_DeckAnalysis.java index d50e75282af..03eeb46fcdd 100644 --- a/src/main/java/forge/GUI_DeckAnalysis.java +++ b/src/main/java/forge/GUI_DeckAnalysis.java @@ -8,6 +8,9 @@ import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.math.BigDecimal; import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map.Entry; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; @@ -25,6 +28,13 @@ import javax.swing.border.BevelBorder; import javax.swing.event.MouseInputAdapter; import javax.swing.table.DefaultTableModel; +import forge.card.CardManaCost; +import forge.card.CardRules; +import forge.card.CardPoolView; +import forge.card.CardPrinted; +import forge.card.CardType; +import forge.gui.deckeditor.TableModel; + import net.miginfocom.swing.MigLayout; /** @@ -100,7 +110,7 @@ public class GUI_DeckAnalysis extends javax.swing.JDialog { * @param g * a {@link javax.swing.JFrame} object. * @param tb - * a {@link forge.TableModel} object. + * a {@link forge.gui.deckeditor.TableModel} object. */ public GUI_DeckAnalysis(JFrame g, TableModel tb) { super(g); @@ -146,7 +156,7 @@ public class GUI_DeckAnalysis extends javax.swing.JDialog { int cArtifact, cCreature, cEnchant, cInstant, cLandType, cPlaneswalker, cSorcery; int mZero, mOne, mTwo, mThree, mFour, mFive, mSixMore; float tManaCost; - Card c; + CardRules c; cBlack = 0; cBlue = 0; cGreen = 0; @@ -170,188 +180,103 @@ public class GUI_DeckAnalysis extends javax.swing.JDialog { mFive = 0; mSixMore = 0; tManaCost = 0; - CardList cList; - cList = tModel.getCards(); - for (int i = 0; i < cList.size(); i++) { - c = cList.getCard(i); - if (CardUtil.getColors(c).size() > 1) { - cMulticolor = cMulticolor + 1; + CardPoolView cardList = tModel.getCards(); + + for (Entry e : cardList) { + c = e.getKey().getCard(); + int cnt = e.getValue(); + + if (c.getColor().isMulticolor()) { + cMulticolor = cMulticolor + cnt; } else { - if (CardUtil.getColors(c).contains(Constant.Color.Black)) { - cBlack = cBlack + 1; - } - if (CardUtil.getColors(c).contains(Constant.Color.Blue)) { - cBlue = cBlue + 1; - } - if (CardUtil.getColors(c).contains(Constant.Color.Green)) { - cGreen = cGreen + 1; - } - if (CardUtil.getColors(c).contains(Constant.Color.Red)) { - cRed = cRed + 1; - } - if (CardUtil.getColors(c).contains(Constant.Color.White)) { - cWhite = cWhite + 1; - } - if (CardUtil.getColors(c).contains(Constant.Color.Colorless)) { - if (c.isLand()) { - cLand = cLand + 1; - } else { - cColorless = cColorless + 1; - } + if (c.getColor().isBlack()) { cBlack = cBlack + cnt; } + if (c.getColor().isBlue()) { cBlue = cBlue + cnt; } + if (c.getColor().isGreen()) { cGreen = cGreen + cnt; } + if (c.getColor().isRed()) { cRed = cRed + cnt; } + if (c.getColor().isWhite()) { cWhite = cWhite + cnt; } + if (c.getColor().isColorless()) { + if (c.getType().isLand()) { cLand = cLand + cnt; } + else { cColorless = cColorless + cnt; } } } - } + // count card types + CardType cType = c.getType(); + if (cType.isArtifact()) { cArtifact = cArtifact + cnt; } + if (cType.isCreature()) { cCreature = cCreature + cnt; } + if (cType.isEnchantment()) { cEnchant = cEnchant + cnt; } + if (cType.isInstant()) { cInstant = cInstant + cnt; } + if (cType.isLand()) { cLandType = cLandType + cnt; } + if (cType.isPlaneswalker()) { cPlaneswalker = cPlaneswalker + cnt; } + if (cType.isSorcery()) { cSorcery = cSorcery + cnt; } - for (int i = 0; i < cList.size(); i++) { - c = cList.getCard(i); - if (c.isArtifact()) { - cArtifact = cArtifact + 1; - } - if (c.isCreature()) { - cCreature = cCreature + 1; - } - if (c.isEnchantment()) { - cEnchant = cEnchant + 1; - } - if (c.isInstant()) { - cInstant = cInstant + 1; - } - if (c.isLand()) { - cLandType = cLandType + 1; - } - if (c.isPlaneswalker()) { - cPlaneswalker = cPlaneswalker + 1; - } - if (c.isSorcery()) { - cSorcery = cSorcery + 1; - } - } - for (int i = 0; i < cList.size(); i++) { - c = cList.getCard(i); - if (CardUtil.getConvertedManaCost(c.getManaCost()) == 0) { - mZero = mZero + 1; + int cmc = c.getManaCost().getCMC(); + if (cmc == 0) { mZero = mZero + cnt; + } else if (cmc == 1) { mOne = mOne + cnt; + } else if (cmc == 2) { mTwo = mTwo + cnt; + } else if (cmc == 3) { mThree = mThree + cnt; + } else if (cmc == 4) { mFour = mFour + cnt; + } else if (cmc == 5) { mFive = mFive + 1; + } else if (cmc >= 6) { mSixMore = mSixMore + 1; } - if (CardUtil.getConvertedManaCost(c.getManaCost()) == 1) { - mOne = mOne + 1; - } - if (CardUtil.getConvertedManaCost(c.getManaCost()) == 2) { - mTwo = mTwo + 1; - } - if (CardUtil.getConvertedManaCost(c.getManaCost()) == 3) { - mThree = mThree + 1; - } - if (CardUtil.getConvertedManaCost(c.getManaCost()) == 4) { - mFour = mFour + 1; - } - if (CardUtil.getConvertedManaCost(c.getManaCost()) == 5) { - mFive = mFive + 1; - } - if (CardUtil.getConvertedManaCost(c.getManaCost()) >= 6) { - mSixMore = mSixMore + 1; - } - } - for (int i = 0; i < cList.size(); i++) { - c = cList.getCard(i); - tManaCost = tManaCost + CardUtil.getConvertedManaCost(c.getManaCost()); + tManaCost = tManaCost + cmc * cnt; } - BigDecimal aManaCost = new BigDecimal(tManaCost / cList.size()); + int total = cardList.countAll(); + BigDecimal aManaCost = new BigDecimal(tManaCost / total); aManaCost = aManaCost.setScale(2, BigDecimal.ROUND_HALF_UP); - jLabelTotal.setText("Information about deck (total cards: " + cList.size() + "):"); + + jLabelTotal.setText("Information about deck (total cards: " + total + "):"); jLabelManaCost.setText("Mana cost (ACC:" + aManaCost + ")"); Color cr = new Color(100, 100, 100); - if (cBlack == 0) { - jLabelBlack.setForeground(cr); - } - jLabelBlack.setText("Black: " + cBlack + " (" + cBlack * 100 / cList.size() + "%)"); - if (cBlue == 0) { - jLabelBlue.setForeground(cr); - } - jLabelBlue.setText("Blue: " + cBlue + " (" + cBlue * 100 / cList.size() + "%)"); - if (cGreen == 0) { - jLabelGreen.setForeground(cr); - } - jLabelGreen.setText("Green: " + cGreen + " (" + cGreen * 100 / cList.size() + "%)"); - if (cRed == 0) { - jLabelRed.setForeground(cr); - } - jLabelRed.setText("Red: " + cRed + " (" + cRed * 100 / cList.size() + "%)"); - if (cWhite == 0) { - jLabelWhite.setForeground(cr); - } - jLabelWhite.setText("White: " + cWhite + " (" + cWhite * 100 / cList.size() + "%)"); - if (cMulticolor == 0) { - jLabelMultiColor.setForeground(cr); - } - jLabelMultiColor.setText("Multicolor: " + cMulticolor + " (" + cMulticolor * 100 / cList.size() - + "%)"); - if (cColorless == 0) { - jLabelColorless.setForeground(cr); - } - jLabelColorless.setText("Colorless: " + cColorless + " (" + cColorless * 100 / cList.size() + "%)"); - if (cLand == 0) { - jLabelLand.setForeground(cr); - } - jLabelLand.setText("Land: " + cLand + " (" + cLand * 100 / cList.size() + "%)"); - if (cArtifact == 0) { - jLabelArtifact.setForeground(cr); - } - jLabelArtifact.setText("Artifact: " + cArtifact + " (" + cArtifact * 100 / cList.size() + "%)"); - if (cCreature == 0) { - jLabelCreature.setForeground(cr); - } - jLabelCreature.setText("Creature: " + cCreature + " (" + cCreature * 100 / cList.size() + "%)"); - if (cEnchant == 0) { - jLabelEnchant.setForeground(cr); - } - jLabelEnchant.setText("Enchant: " + cEnchant + " (" + cEnchant * 100 / cList.size() + "%)"); - if (cInstant == 0) { - jLabelInstant.setForeground(cr); - } - jLabelInstant.setText("Instant: " + cInstant + " (" + cInstant * 100 / cList.size() + "%)"); - if (cLandType == 0) { - jLabelLandType.setForeground(cr); - } - jLabelLandType.setText("Land: " + cLandType + " (" + cLandType * 100 / cList.size() + "%)"); - if (cPlaneswalker == 0) { - jLabelPlaneswalker.setForeground(cr); - } - jLabelPlaneswalker.setText("Planeswalker: " + cPlaneswalker + " (" + cPlaneswalker * 100 - / cList.size() + "%)"); - if (cSorcery == 0) { - jLabelSorcery.setForeground(cr); - } - jLabelSorcery.setText("Sorcery: " + cSorcery + " (" + cSorcery * 100 / cList.size() + "%)"); - if (mZero == 0) { - jLabelZeroMana.setForeground(cr); - } - jLabelZeroMana.setText("Zero mana: " + mZero + " (" + mZero * 100 / cList.size() + "%)"); - if (mOne == 0) { - jLabelOneMana.setForeground(cr); - } - jLabelOneMana.setText("One mana: " + mOne + " (" + mOne * 100 / cList.size() + "%)"); - if (mTwo == 0) { - jLabelTwoMana.setForeground(cr); - } - jLabelTwoMana.setText("Two mana: " + mTwo + " (" + mTwo * 100 / cList.size() + "%)"); - if (mThree == 0) { - jLabelThreeMana.setForeground(cr); - } - jLabelThreeMana.setText("Three mana :" + mThree + " (" + mThree * 100 / cList.size() + "%)"); - if (mFour == 0) { - jLabelFourMana.setForeground(cr); - } - jLabelFourMana.setText("Four mana: " + mFour + " (" + mFour * 100 / cList.size() + "%)"); - if (mFive == 0) { - jLabelFiveMana.setForeground(cr); - } - jLabelFiveMana.setText("Five mana: " + mFive + " (" + mFive * 100 / cList.size() + "%)"); - if (mSixMore == 0) { - jLabelSixMana.setForeground(cr); - } - jLabelSixMana.setText("Six and more: " + mSixMore + " (" + mSixMore * 100 / cList.size() + "%)"); + + if (cBlack == 0) { jLabelBlack.setForeground(cr); } + jLabelBlack.setText(formatStat("Black", cBlack, total)); + if (cBlue == 0) { jLabelBlue.setForeground(cr); } + jLabelBlue.setText(formatStat("Blue", cBlue, total)); + if (cGreen == 0) { jLabelGreen.setForeground(cr); } + jLabelGreen.setText(formatStat("Green", cGreen, total)); + if (cRed == 0) { jLabelRed.setForeground(cr); } + jLabelRed.setText(formatStat("Red", cRed, total)); + if (cWhite == 0) { jLabelWhite.setForeground(cr); } + jLabelWhite.setText(formatStat("White", cWhite, total)); + if (cMulticolor == 0) { jLabelMultiColor.setForeground(cr); } + jLabelMultiColor.setText(formatStat("Multicolor", cMulticolor, total)); + if (cColorless == 0) { jLabelColorless.setForeground(cr); } + jLabelColorless.setText(formatStat("Colorless", cColorless, total)); + + if (cLand == 0) { jLabelLand.setForeground(cr); } + jLabelLand.setText(formatStat("Land", cLand, total)); + if (cArtifact == 0) { jLabelArtifact.setForeground(cr); } + jLabelArtifact.setText(formatStat("Artifact", cArtifact, total)); + if (cCreature == 0) { jLabelCreature.setForeground(cr); } + jLabelCreature.setText(formatStat("Creature", cCreature, total)); + if (cEnchant == 0) { jLabelEnchant.setForeground(cr); } + jLabelEnchant.setText(formatStat("Enchant", cEnchant, total)); + if (cInstant == 0) { jLabelInstant.setForeground(cr); } + jLabelInstant.setText(formatStat("Instant", cInstant, total)); + if (cLandType == 0) { jLabelLandType.setForeground(cr); } + jLabelLandType.setText(formatStat("Land", cLandType, total)); + if (cPlaneswalker == 0) { jLabelPlaneswalker.setForeground(cr); } + jLabelPlaneswalker.setText(formatStat("Planeswalker", cPlaneswalker, total)); + + if (cSorcery == 0) { jLabelSorcery.setForeground(cr); } + jLabelSorcery.setText(formatStat("Sorcery", cSorcery, total)); + if (mZero == 0) { jLabelZeroMana.setForeground(cr); } + jLabelZeroMana.setText(formatStat("Zero mana", mZero, total)); + if (mOne == 0) { jLabelOneMana.setForeground(cr); } + jLabelOneMana.setText(formatStat("One mana", mOne, total)); + if (mTwo == 0) { jLabelTwoMana.setForeground(cr); } + jLabelTwoMana.setText(formatStat("Two mana", mTwo, total)); + if (mThree == 0) { jLabelThreeMana.setForeground(cr); } + jLabelThreeMana.setText(formatStat("Three mana", mThree, total)); + if (mFour == 0) { jLabelFourMana.setForeground(cr); } + jLabelFourMana.setText(formatStat("Four mana", mFour, total)); + if (mFive == 0) { jLabelFiveMana.setForeground(cr); } + jLabelFiveMana.setText(formatStat("Five mana", mFive, total)); + if (mSixMore == 0) { jLabelSixMana.setForeground(cr); } + jLabelSixMana.setText(formatStat("Six and more", mSixMore, total)); } }); @@ -369,6 +294,11 @@ public class GUI_DeckAnalysis extends javax.swing.JDialog { e.printStackTrace(); } } + + private String formatStat(String statName, int value, int deckSize ) + { + return String.format("%s: %d (%f%%)", statName, value, 100f * value / deckSize); + } /** *

@@ -991,31 +921,23 @@ public class GUI_DeckAnalysis extends javax.swing.JDialog { * @return a {@link javax.swing.JList} object. */ private JList getJList1() { - CardList rList; - rList = tModel.getCards(); + List rList = tModel.getCards().toFlatList(); + + Collections.shuffle(rList, MyRandom.random); + Collections.shuffle(rList, MyRandom.random); - rList.shuffle(); ListModel jList1Model; if (jListFirstHand == null) { - if (rList.size() >= 40) { - jList1Model = new DefaultComboBoxModel(new String[] { rList.getCard(0).getName(), - rList.getCard(1).getName(), rList.getCard(2).getName(), rList.getCard(3).getName(), - rList.getCard(4).getName(), rList.getCard(5).getName(), rList.getCard(6).getName() }); - jListFirstHand = new JList(); - } else { - jList1Model = new DefaultComboBoxModel(new String[] { "Few cards." }); - jListFirstHand = new JList(); - } + jListFirstHand = new JList(); + } + + if (rList.size() >= 40) { + jList1Model = new DefaultComboBoxModel(new String[] { rList.get(0).getName(), + rList.get(1).getName(), rList.get(2).getName(), rList.get(3).getName(), + rList.get(4).getName(), rList.get(5).getName(), rList.get(6).getName() }); + } else { - if (rList.size() >= 40) { - jList1Model = new DefaultComboBoxModel(new String[] { rList.getCard(0).getName(), - rList.getCard(1).getName(), rList.getCard(2).getName(), rList.getCard(3).getName(), - rList.getCard(4).getName(), rList.getCard(5).getName(), rList.getCard(6).getName() }); - - } else { - jList1Model = new DefaultComboBoxModel(new String[] { "Few cards." }); - - } + jList1Model = new DefaultComboBoxModel(new String[] { "Few cards." }); } jListFirstHand.setModel(jList1Model); @@ -1108,10 +1030,9 @@ public class GUI_DeckAnalysis extends javax.swing.JDialog { * @return a {@link javax.swing.JButton} object. */ private JButton getJButton1() { - CardList rList; - rList = tModel.getCards(); + CardPoolView rList = tModel.getCards(); if (jButtonRegenerate == null) { - if (rList.size() >= 40) { + if (rList.countAll() >= 40) { jButtonRegenerate = new JButton(); jButtonRegenerate.setLayout(null); jButtonRegenerate.setText("Regenerate hand"); @@ -1186,15 +1107,14 @@ public class GUI_DeckAnalysis extends javax.swing.JDialog { "6th", "7th" }); jTable1 = new JTable(dm); - CardList rList; - rList = tModel.getCards(); + List rList = tModel.getCards().toFlatList(); String[] cardsName = new String[rList.size()]; int cCount; float fCount; float firstTurnF, secondTurnF, thirdTurnF, fourthTurnF, fivethTurnF, sixthTurnF, seventhTurnF; for (int i = 0; i < rList.size(); i++) { - cardsName[i] = rList.getCard(i).getName(); + cardsName[i] = rList.get(i).getName(); } Arrays.sort(cardsName); jTable1.setValueAt("Few cards.", 0, 0); diff --git a/src/main/java/forge/GameAction.java b/src/main/java/forge/GameAction.java index 12d59904ef1..45415810fa7 100644 --- a/src/main/java/forge/GameAction.java +++ b/src/main/java/forge/GameAction.java @@ -1,6 +1,7 @@ package forge; +import forge.card.CardPrinted; import forge.card.abilityFactory.AbilityFactory; import forge.card.abilityFactory.AbilityFactory_Attach; import forge.card.cardFactory.CardFactoryInterface; @@ -25,6 +26,7 @@ import forge.properties.NewConstants.LANG.GameAction.GAMEACTION_TEXT; import javax.swing.*; import java.util.*; +import java.util.Map.Entry; /** *

GameAction class.

@@ -1052,102 +1054,95 @@ public class GameAction { Card.resetUniqueNumber(); Random generator = MyRandom.random; - - for (int i = 0; i < humanDeck.countMain(); i++) { - Card card = new Card(); - - String cardName = humanDeck.getMain(i); - String setCode = ""; - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - setCode = s[1]; - } - - card = c.getCard(cardName, AllZone.getHumanPlayer()); - - if (!setCode.equals("")) - card.setCurSetCode(setCode); - else if ((card.getSets().size() > 0)) // && card.getCurSetCode().equals("")) - card.setRandomSetCode(); - - if (!card.getCurSetCode().equals("")) { - int n = SetInfoUtil.getSetInfo_Code(card.getSets(), card.getCurSetCode()).PicCount; - if (n > 1) - card.setRandomPicture(generator.nextInt(n - 1) + 1); - - card.setImageFilename(CardUtil.buildFilename(card)); - } - - // Assign random foiling on approximately 1:20 cards - if (Constant.Runtime.RndCFoil[0] && Constant.Runtime.GameType[0].equals(Constant.GameType.Constructed)) { - if (MyRandom.percentTrue(5)) - card.setFoil(MyRandom.random.nextInt(9) + 1); - } - - //System.out.println("human random number:" + card.getRandomPicture()); - //} - - AllZone.getHumanLibrary().add(card); - - for (Trigger trig : card.getTriggers()) { - AllZone.getTriggerHandler().registerTrigger(trig); + for (Entry cardPile : humanDeck.getMain()) { + for (int i = 0; i < cardPile.getValue(); i++) { + String cardName = cardPile.getKey().getName(); + String setCode = cardPile.getKey().getSet(); + + Card card = c.getCard(cardName, AllZone.getHumanPlayer()); + + if (!setCode.equals("")) + card.setCurSetCode(setCode); + else if ((card.getSets().size() > 0)) // && card.getCurSetCode().equals("")) + card.setRandomSetCode(); + + if (!card.getCurSetCode().equals("")) { + int n = SetInfoUtil.getSetInfo_Code(card.getSets(), card.getCurSetCode()).PicCount; + if (n > 1) + card.setRandomPicture(generator.nextInt(n - 1) + 1); + + card.setImageFilename(CardUtil.buildFilename(card)); + } + + // Assign random foiling on approximately 1:20 cards + if (Constant.Runtime.RndCFoil[0] && Constant.Runtime.GameType[0].equals(Constant.GameType.Constructed)) { + if (MyRandom.percentTrue(5)) + card.setFoil(MyRandom.random.nextInt(9) + 1); + } + // foiling for cards explicitly foiled in deck + if (cardPile.getKey().isFoil()) { card.setFoil(MyRandom.random.nextInt(9) + 1); } + + //System.out.println("human random number:" + card.getRandomPicture()); + //} + + AllZone.getHumanLibrary().add(card); + + for (Trigger trig : card.getTriggers()) { + AllZone.getTriggerHandler().registerTrigger(trig); + } } } ArrayList RAICards = new ArrayList(); - for (int i = 0; i < computerDeck.countMain(); i++) { - Card card = new Card(); - - String cardName = computerDeck.getMain(i); - String setCode = ""; - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - setCode = s[1]; + for (Entry cardPile : computerDeck.getMain()) { + for (int i = 0; i < cardPile.getValue(); i++) { + + String cardName = cardPile.getKey().getName(); + String setCode = cardPile.getKey().getSet(); + + Card card = c.getCard(cardName, AllZone.getComputerPlayer()); + + //if(card.isBasicLand()) { + //String PC = card.getSVar("PicCount"); + //int n = 0; + //if (PC.matches("[0-9][0-9]?")) + // n = Integer.parseInt(PC); + //if (n > 1) + // card.setRandomPicture(generator.nextInt(n)); + //System.out.println("computer random number:" + card.getRandomPicture()); + //} + + if (!setCode.equals("")) + card.setCurSetCode(setCode); + else if ((card.getSets().size() > 0)) // && card.getCurSetCode().equals("")) + card.setRandomSetCode(); + + if (!card.getCurSetCode().equals("")) { + int n = SetInfoUtil.getSetInfo_Code(card.getSets(), card.getCurSetCode()).PicCount; + if (n > 1) + card.setRandomPicture(generator.nextInt(n - 1) + 1); + + card.setImageFilename(CardUtil.buildFilename(card)); + } + + // Assign random foiling on approximately 1:20 cards + if (Constant.Runtime.RndCFoil[0] && Constant.Runtime.GameType[0].equals(Constant.GameType.Constructed)) { + if (MyRandom.percentTrue(5)) + card.setFoil(MyRandom.random.nextInt(9) + 1); + } + if (cardPile.getKey().isFoil()) { card.setFoil(MyRandom.random.nextInt(9) + 1); } + + AllZone.getComputerLibrary().add(card); + + for (Trigger trig : card.getTriggers()) { + AllZone.getTriggerHandler().registerTrigger(trig); + } + + if (card.getSVar("RemAIDeck").equals("True")) + RAICards.add(card.getName()); + //get card picture so that it is in the image cache + // ImageCache.getImage(card); } - - card = c.getCard(cardName, AllZone.getComputerPlayer()); - - //if(card.isBasicLand()) { - //String PC = card.getSVar("PicCount"); - //int n = 0; - //if (PC.matches("[0-9][0-9]?")) - // n = Integer.parseInt(PC); - //if (n > 1) - // card.setRandomPicture(generator.nextInt(n)); - //System.out.println("computer random number:" + card.getRandomPicture()); - //} - - if (!setCode.equals("")) - card.setCurSetCode(setCode); - else if ((card.getSets().size() > 0)) // && card.getCurSetCode().equals("")) - card.setRandomSetCode(); - - if (!card.getCurSetCode().equals("")) { - int n = SetInfoUtil.getSetInfo_Code(card.getSets(), card.getCurSetCode()).PicCount; - if (n > 1) - card.setRandomPicture(generator.nextInt(n - 1) + 1); - - card.setImageFilename(CardUtil.buildFilename(card)); - } - - // Assign random foiling on approximately 1:20 cards - if (Constant.Runtime.RndCFoil[0] && Constant.Runtime.GameType[0].equals(Constant.GameType.Constructed)) { - if (MyRandom.percentTrue(5)) - card.setFoil(MyRandom.random.nextInt(9) + 1); - } - - AllZone.getComputerLibrary().add(card); - - for (Trigger trig : card.getTriggers()) { - AllZone.getTriggerHandler().registerTrigger(trig); - } - - if (card.getSVar("RemAIDeck").equals("True")) - RAICards.add(card.getName()); - //get card picture so that it is in the image cache - // ImageCache.getImage(card); } if (RAICards.size() > 0) { diff --git a/src/main/java/forge/GuiDisplay4.java b/src/main/java/forge/GuiDisplay4.java index 04e1fd48da4..40e178e49d2 100644 --- a/src/main/java/forge/GuiDisplay4.java +++ b/src/main/java/forge/GuiDisplay4.java @@ -35,6 +35,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Map.Entry; import java.util.Observable; import java.util.Observer; @@ -77,6 +78,7 @@ import com.google.code.jyield.YieldUtils; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.XStreamException; +import forge.card.CardPrinted; import forge.card.cardFactory.CardFactoryUtil; import forge.error.ErrorViewer; import forge.gui.ForgeAction; @@ -1588,11 +1590,8 @@ public class GuiDisplay4 extends JFrame implements CardContainer, Display, NewCo if (Constant.Runtime.HumanDeck[0].countMain() > 1) { HashMap deckMap = new HashMap(); - for (String s : Constant.Runtime.HumanDeck[0].getMain()){ - if (deckMap.containsKey(s)) - deckMap.put(s, (Integer)(deckMap.get(s)) + 1); - else - deckMap.put(s, 1); + for (Entry s : Constant.Runtime.HumanDeck[0].getMain()){ + deckMap.put(s.getKey().getName(), s.getValue()); } String nl = System.getProperty("line.separator"); diff --git a/src/main/java/forge/GuiFilter.java b/src/main/java/forge/GuiFilter.java deleted file mode 100644 index 77f32653fd4..00000000000 --- a/src/main/java/forge/GuiFilter.java +++ /dev/null @@ -1,590 +0,0 @@ -package forge; - -import java.awt.Dimension; -import java.awt.Font; -import java.awt.event.KeyAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.border.BevelBorder; -import javax.swing.event.MouseInputAdapter; - -import net.miginfocom.swing.MigLayout; - -/** - * @author Forge - * @version $Id$ - */ -public class GuiFilter extends javax.swing.JDialog { - - /**. - * Constant serialVersionUID=-8475271235196182185L - */ - private static final long serialVersionUID = -8475271235196182185L; - private JLabel nameLabel; - private JTextField nameTextField; - private JLabel cardTextLabel; - private JTextField cardTextField; - private JPanel colorPanel; - private JPanel bottomPanel; - private JCheckBox jCheckBoxColorless; - private JCheckBox jCheckBoxWhite; - private JCheckBox jCheckBoxRed; - private JCheckBox jCheckBoxGreen; - private JCheckBox jCheckBoxBlue; - private JLabel colorLabel; - private JLabel typeLabel; - private JCheckBox jCheckBoxPlaneswalker; - private JCheckBox jCheckBoxArtifact; - private JCheckBox jCheckBoxCreature; - private JCheckBox jCheckBoxEnchant; - private JCheckBox jCheckBoxInstant; - private JCheckBox jCheckBoxLand; - private JCheckBox jCheckBoxSorcery; - private JPanel typePanel; - private JCheckBox jCheckBoxBlack; - private JButton jButtonOk; - private JPanel topPanel; - private DeckDisplay deckDisplay; - private java.awt.Color gray = new java.awt.Color(192, 192, 192); - - /** - *

- * Constructor for GUI_Filter. - *

- * @param g - * a {@link javax.swing.JFrame} object. - * @param display - * a {@link forge.DeckDisplay} object. - */ - public GuiFilter(final JFrame g, final DeckDisplay display) { - super(g); - deckDisplay = display; - initGUI(); - } - - private KeyAdapter fnKeyPressed = new KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }; - /** - *

- * initGUI. - *

- */ - private void initGUI() { - try { - this.isResizable(); - - getContentPane().setLayout(new MigLayout("fill")); - getContentPane().add(getTopPanel(), "span 3, wrap"); - getContentPane().add(getColorPanel(), "aligny top, growy"); - getContentPane().add(getTypePanel(), "aligny top, wrap"); - getContentPane().add(getBottomPanel(), "align center, span 3"); - setVisible(true); - Dimension screen = getToolkit().getScreenSize(); - int x = (screen.width - 340) / 2; - int y = (screen.height - 500) / 2; - this.setBounds(x, y, 340, 500); - this.setResizable(true); - this.setTitle("Filter"); - - setIconImage(null); - - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(final WindowEvent arg0) { - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; - g.setEnabled(true); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - private JTextField getNameTextField() { - if (nameTextField == null) { - nameTextField = new JTextField(30); - nameTextField.addKeyListener(fnKeyPressed); - } - return nameTextField; - } - - private JLabel getNameLabel() { - if (nameLabel == null) { - nameLabel = new JLabel(); - nameLabel.setText("Name:"); - nameLabel.setFont(new Font("Segoe UI", 0, 16)); - } - return nameLabel; - } - - private JPanel getTopPanel() { - if (topPanel == null) { - topPanel = new JPanel(); - topPanel.setLayout(new MigLayout()); - topPanel.add(getNameLabel(), "gap"); - topPanel.add(getNameTextField(), "span 3, wrap"); - topPanel.add(getCardTextLabel(), "gap"); - topPanel.add(getCardTextField(), "span 3, wrap"); - } - - return topPanel; - } - - /** - *

- * Getter for the field colorPanel. - *

- * - * @return a {@link javax.swing.JPanel} object. - */ - private JPanel getColorPanel() { - if (colorPanel == null) { - colorPanel = new JPanel(); - colorPanel.setLayout(new MigLayout()); - colorPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); - colorPanel.setBackground(gray); - colorPanel.add(getColorLabel(), "align, wrap"); - colorPanel.add(getJCheckBoxBlack(), "wrap"); - colorPanel.add(getJCheckBoxColorless(), "wrap"); - colorPanel.add(getJCheckBoxWhite(), "wrap"); - colorPanel.add(getJCheckBoxRed(), "wrap"); - colorPanel.add(getJCheckBoxGreen(), "wrap"); - colorPanel.add(getJCheckBoxBlue(), "wrap"); - } - return colorPanel; - } - - private JPanel getBottomPanel() { - if (bottomPanel == null) { - bottomPanel = new JPanel(); - bottomPanel.setLayout(new MigLayout()); - bottomPanel.add(getJButtonOk(), "align, span 3, grow"); - } - return bottomPanel; - } - - /** - *

- * Getter for the field jCheckBoxBlue. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxBlue() { - if (jCheckBoxBlue == null) { initCheckBox(jCheckBoxBlue = new JCheckBox(), "Blue" ); } - return jCheckBoxBlue; - } - - /** - *

- * Getter for the field jCheckBoxGreen. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxGreen() { - if (jCheckBoxGreen == null) { initCheckBox(jCheckBoxGreen = new JCheckBox(), "Green"); } - return jCheckBoxGreen; - } - - /** - *

- * Getter for the field jCheckBoxRed. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxRed() { - if (jCheckBoxRed == null) { initCheckBox(jCheckBoxRed = new JCheckBox(), "Red"); } - return jCheckBoxRed; - } - - /** - *

- * Getter for the field jCheckBoxWhite. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxWhite() { - if (jCheckBoxWhite == null) { initCheckBox(jCheckBoxWhite = new JCheckBox(), "White"); } - return jCheckBoxWhite; - } - - /** - *

- * Getter for the field jCheckBoxColorless. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxColorless() { - if (jCheckBoxColorless == null) { initCheckBox(jCheckBoxColorless = new JCheckBox(), "Colorless"); } - return jCheckBoxColorless; - } - - /** - *

- * Getter for the field jButtonOk. - *

- * - * @return a {@link javax.swing.JButton} object. - */ - private JButton getJButtonOk() { - if (jButtonOk == null) { - jButtonOk = new JButton(); - jButtonOk.setText("OK"); - jButtonOk.addMouseListener(new MouseInputAdapter() { - @Override - public void mouseClicked(final MouseEvent e) { - filterCardTable(); - } - }); - } - return jButtonOk; - } - - /** - *

- * Getter for the field jCheckBoxBlack. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxBlack() { - if (jCheckBoxBlack == null) { initCheckBox(jCheckBoxBlack = new JCheckBox(), "Black"); } - return jCheckBoxBlack; - } - - /** - *

- * Getter for the field typePanel. - *

- * - * @return a {@link javax.swing.JPanel} object. - */ - private JPanel getTypePanel() { - if (typePanel == null) { - typePanel = new JPanel(); - typePanel.setLayout(new MigLayout()); - typePanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); - typePanel.setBackground(gray); - typePanel.add(getTypeLabel(), "align, wrap"); - typePanel.add(getJCheckBoxSorcery(), "wrap"); - typePanel.add(getJCheckBoxPlaneswalker(), "wrap"); - typePanel.add(getJCheckBoxLand(), "wrap"); - typePanel.add(getJCheckBoxInstant(), "wrap"); - typePanel.add(getJCheckBoxEnchant(), "wrap"); - typePanel.add(getJCheckBoxCreature(), "wrap"); - typePanel.add(getJCheckBoxArtifact(), "wrap"); - } - return typePanel; - } - - /** - *

- * Getter for the field colorLabel. - *

- * - * @return a {@link javax.swing.JLabel} object. - */ - private JLabel getColorLabel() { - if (colorLabel == null) { - colorLabel = new JLabel(); - colorLabel.setText("Color"); - colorLabel.setFont(new java.awt.Font("Segoe UI", 0, 14)); - } - return colorLabel; - } - - /** - *

- * Getter for the field typeLabel. - *

- * - * @return a {@link javax.swing.JLabel} object. - */ - private JLabel getTypeLabel() { - if (typeLabel == null) { - typeLabel = new JLabel(); - typeLabel.setText("Type"); - typeLabel.setFont(new java.awt.Font("Segoe UI", 0, 14)); - } - return typeLabel; - } - - /** - *

- * getJCheckBoxSorcery. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxSorcery() { - if (jCheckBoxSorcery == null) { initCheckBox(jCheckBoxSorcery = new JCheckBox(), "Sorcery"); } - return jCheckBoxSorcery; - } - - /** - *

- * getJCheckBoxPlaneswalker. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxPlaneswalker() { - if (jCheckBoxPlaneswalker == null) { initCheckBox(jCheckBoxPlaneswalker = new JCheckBox(), "Planeswalker"); } - return jCheckBoxPlaneswalker; - } - - /** - *

- * getJCheckBoxLand. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxLand() { - if (jCheckBoxLand == null) { initCheckBox(jCheckBoxLand = new JCheckBox(), "Land"); } - return jCheckBoxLand; - } - - /** - *

- * getJCheckBoxInstant. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxInstant() { - if (jCheckBoxInstant == null) { initCheckBox(jCheckBoxInstant = new JCheckBox(), "Instant"); } - return jCheckBoxInstant; - } - - /** - *

- * getJCheckBoxEnchant. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxEnchant() { - if (jCheckBoxEnchant == null) { initCheckBox(jCheckBoxEnchant = new JCheckBox(), "Enchant"); } - return jCheckBoxEnchant; - } - - /** - *

- * getJCheckBoxCreature. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxCreature() { - if (jCheckBoxCreature == null) { initCheckBox(jCheckBoxCreature = new JCheckBox(), "Creature"); } - return jCheckBoxCreature; - } - - /** - *

- * getJCheckBoxArtifact. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxArtifact() { - if (jCheckBoxArtifact == null) { initCheckBox(jCheckBoxArtifact = new JCheckBox(), "Artifact"); } - return jCheckBoxArtifact; - } - - private void initCheckBox(final JCheckBox box, final String text) { - box.setText(text); - box.setSelected(true); - box.setBackground(gray); - box.addKeyListener(fnKeyPressed); - } - - /** - *

- * getCardTextField. - *

- * - * @return a {@link javax.swing.JTextField} object. - */ - private JTextField getCardTextField() { - if (cardTextField == null) { - cardTextField = new JTextField(30); - cardTextField.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return cardTextField; - } - - /** - *

- * Getter for the field cardTextLabel. - *

- * - * @return a {@link javax.swing.JLabel} object. - */ - private JLabel getCardTextLabel() { - if (cardTextLabel == null) { - cardTextLabel = new JLabel(); - cardTextLabel.setText("Card Text:"); - cardTextLabel.setFont(new java.awt.Font("Segoe UI", 0, 16)); - } - return cardTextLabel; - } - - /** - *

- * FilterCardTable. - *

- */ - private void filterCardTable() { - - String name = nameTextField.getText(); - String cText = cardTextField.getText(); - - CardList filterCardList; - CardFilter filter = new CardFilter(); - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; - g.blackCheckBox.setSelected(true); - g.blackCheckBox.setEnabled(true); - g.blueCheckBox.setSelected(true); - g.blueCheckBox.setEnabled(true); - g.greenCheckBox.setSelected(true); - g.greenCheckBox.setEnabled(true); - g.redCheckBox.setSelected(true); - g.redCheckBox.setEnabled(true); - g.whiteCheckBox.setSelected(true); - g.whiteCheckBox.setEnabled(true); - g.colorlessCheckBox.setSelected(true); - g.colorlessCheckBox.setEnabled(true); - g.artifactCheckBox.setSelected(true); - g.artifactCheckBox.setEnabled(true); - g.creatureCheckBox.setSelected(true); - g.creatureCheckBox.setEnabled(true); - g.enchantmentCheckBox.setSelected(true); - g.enchantmentCheckBox.setEnabled(true); - g.instantCheckBox.setSelected(true); - g.instantCheckBox.setEnabled(true); - g.landCheckBox.setSelected(true); - g.landCheckBox.setEnabled(true); - g.planeswalkerCheckBox.setSelected(true); - g.planeswalkerCheckBox.setEnabled(true); - g.sorceryCheckBox.setSelected(true); - g.sorceryCheckBox.setEnabled(true); - g.setEnabled(true); - if (name != "") { - if (cText != "") { - filterCardList = filter.cardListNameFilter(AllZone.getCardFactory(), name); - - if (filterCardList.size() == 0) { - JOptionPane.showMessageDialog(null, "Sorry, cards with name: " + name + " not found.", "Filter", - JOptionPane.INFORMATION_MESSAGE); - } else { - filterCardList = filter.CardListTextFilter(filterCardList, cText); - if (filterCardList.size() == 0) { - JOptionPane.showMessageDialog(null, "Sorry, cards with text: " + cText + " not found.", - "Filter", JOptionPane.INFORMATION_MESSAGE); - } else { - if (!jCheckBoxBlack.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "black"); - g.blackCheckBox.setSelected(false); - g.blackCheckBox.setEnabled(false); - } - if (!jCheckBoxBlue.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "blue"); - g.blueCheckBox.setSelected(false); - g.blueCheckBox.setEnabled(false); - } - if (!jCheckBoxGreen.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "green"); - g.greenCheckBox.setSelected(false); - g.greenCheckBox.setEnabled(false); - } - if (!jCheckBoxRed.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "red"); - g.redCheckBox.setSelected(false); - g.redCheckBox.setEnabled(false); - } - if (!jCheckBoxWhite.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "white"); - g.whiteCheckBox.setSelected(false); - g.whiteCheckBox.setEnabled(false); - } - if (!jCheckBoxColorless.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "colorless"); - g.colorlessCheckBox.setSelected(false); - g.colorlessCheckBox.setEnabled(false); - } - if (!jCheckBoxArtifact.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "artifact"); - g.artifactCheckBox.setSelected(false); - g.artifactCheckBox.setEnabled(false); - } - if (!jCheckBoxCreature.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "creature"); - g.creatureCheckBox.setSelected(false); - g.creatureCheckBox.setEnabled(false); - } - if (!jCheckBoxEnchant.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "enchantment"); - g.enchantmentCheckBox.setSelected(false); - g.enchantmentCheckBox.setEnabled(false); - } - if (!jCheckBoxInstant.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "instant"); - g.instantCheckBox.setSelected(false); - g.instantCheckBox.setEnabled(false); - } - if (!jCheckBoxLand.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "land"); - g.landCheckBox.setSelected(false); - g.landCheckBox.setEnabled(false); - } - if (!jCheckBoxPlaneswalker.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "planeswalker"); - g.planeswalkerCheckBox.setSelected(false); - g.planeswalkerCheckBox.setEnabled(false); - } - if (!jCheckBoxSorcery.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "sorcery"); - g.sorceryCheckBox.setSelected(false); - g.sorceryCheckBox.setEnabled(false); - } - deckDisplay.updateDisplay(filterCardList, deckDisplay.getBottom()); - } - } - } - - } - dispose(); - } -} diff --git a/src/main/java/forge/GuiQuestFilter.java b/src/main/java/forge/GuiQuestFilter.java deleted file mode 100644 index 5e8c872bd57..00000000000 --- a/src/main/java/forge/GuiQuestFilter.java +++ /dev/null @@ -1,739 +0,0 @@ -package forge; - -import java.awt.Dimension; -import java.awt.Font; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.border.BevelBorder; -import javax.swing.event.MouseInputAdapter; - -import net.miginfocom.swing.MigLayout; - -/** - * @author Forge - * @version $Id$ - */ -public class GuiQuestFilter extends JDialog { - - /**. - * Constant serialVersionUID=-8475271235196182185L - */ - private static final long serialVersionUID = -8475271235196182185L; - private JLabel nameLabel; - private JTextField nameTextField; - private JLabel cardTextLabel; - private JTextField cardTextField; - private JPanel colorPanel; - private JPanel bottomPanel; - private JCheckBox jCheckBoxColorless; - private JCheckBox jCheckBoxWhite; - private JCheckBox jCheckBoxRed; - private JCheckBox jCheckBoxGreen; - private JCheckBox jCheckBoxBlue; - private JLabel colorLabel; - private JLabel typeLabel; - private JCheckBox jCheckBoxPlaneswalker; - private JCheckBox jCheckBoxArtifact; - private JCheckBox jCheckBoxCreature; - private JCheckBox jCheckBoxEnchant; - private JCheckBox jCheckBoxInstant; - private JCheckBox jCheckBoxLand; - private JCheckBox jCheckBoxSorcery; - private JPanel typePanel; - private JCheckBox jCheckBoxBlack; - private JButton jButtonOk; - private JPanel topPanel; - private DeckDisplay deckDisplay; - private java.awt.Color gray = new java.awt.Color(192, 192, 192); - - /** - *

- * Constructor for GUI_Quest_Filter. - *

- * - * @param g - * a {@link javax.swing.JFrame} object. - * @param display - * a {@link forge.DeckDisplay} object. - */ - public GuiQuestFilter(final JFrame g, final DeckDisplay display) { - super(g); - deckDisplay = display; - initGUI(); - } - - /** - *

- * initGUI. - *

- */ - private void initGUI() { - try { - this.isResizable(); - getContentPane().setLayout(new MigLayout("fill")); - getContentPane().add(getTopPanel(), "span 3, wrap"); - getContentPane().add(getColorPanel(), "aligny top, growy"); - getContentPane().add(getTypePanel(), "aligny top, wrap"); - getContentPane().add(getBottomPanel(), "align center, span 3"); - setVisible(true); - Dimension screen = getToolkit().getScreenSize(); - int x = (screen.width - 340) / 2; - int y = (screen.height - 500) / 2; - this.setBounds(x, y, 340, 500); - this.setResizable(true); - this.setTitle("Filter"); - - setIconImage(null); - - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(final WindowEvent arg0) { - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; - g.setEnabled(true); - } - }); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - private JTextField getNameTextField() { - if (nameTextField == null) { - nameTextField = new JTextField(30); - nameTextField.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return nameTextField; - } - - private JLabel getNameLabel() { - if (nameLabel == null) { - nameLabel = new JLabel(); - nameLabel.setText("Name:"); - nameLabel.setFont(new Font("Segoe UI", 0, 16)); - } - return nameLabel; - } - - private JPanel getTopPanel() { - if (topPanel == null) { - topPanel = new JPanel(); - topPanel.setLayout(new MigLayout()); - topPanel.add(getNameLabel(), "gap"); - topPanel.add(getNameTextField(), "span 3, wrap"); - topPanel.add(getCardTextLabel(), "gap"); - topPanel.add(getCardTextField(), "span 3, wrap"); - } - - return topPanel; - } - - /** - *

- * Getter for the field colorPanel. - *

- * - * @return a {@link javax.swing.JPanel} object. - */ - private JPanel getColorPanel() { - if (colorPanel == null) { - colorPanel = new JPanel(); - colorPanel.setLayout(new MigLayout()); - colorPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); - colorPanel.setBackground(gray); - colorPanel.add(getColorLabel(), "align, wrap"); - colorPanel.add(getJCheckBoxBlack(), "wrap"); - colorPanel.add(getJCheckBoxColorless(), "wrap"); - colorPanel.add(getJCheckBoxWhite(), "wrap"); - colorPanel.add(getJCheckBoxRed(), "wrap"); - colorPanel.add(getJCheckBoxGreen(), "wrap"); - colorPanel.add(getJCheckBoxBlue(), "wrap"); - } - return colorPanel; - } - - private JPanel getBottomPanel() { - if (bottomPanel == null) { - bottomPanel = new JPanel(); - bottomPanel.setLayout(new MigLayout()); - bottomPanel.add(getJButtonOk(), "align, span 3, grow"); - } - return bottomPanel; - } - - /** - *

- * Getter for the field jCheckBoxBlue. - *

- * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxBlue() { - if (jCheckBoxBlue == null) { - jCheckBoxBlue = new JCheckBox(); - jCheckBoxBlue.setText("Blue"); - jCheckBoxBlue.setSelected(true); - jCheckBoxBlue.setBackground(gray); - jCheckBoxBlue.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxBlue; - } - - /** - *

- * Getter for the field jCheckBoxGreen. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxGreen() { - if (jCheckBoxGreen == null) { - jCheckBoxGreen = new JCheckBox(); - jCheckBoxGreen.setText("Green"); - jCheckBoxGreen.setSelected(true); - jCheckBoxGreen.setBackground(gray); - jCheckBoxGreen.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxGreen; - } - - /** - *

- * Getter for the field jCheckBoxRed. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxRed() { - if (jCheckBoxRed == null) { - jCheckBoxRed = new JCheckBox(); - jCheckBoxRed.setText("Red"); - jCheckBoxRed.setSelected(true); - jCheckBoxRed.setBackground(gray); - jCheckBoxRed.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxRed; - } - - /** - *

- * Getter for the field jCheckBoxWhite. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxWhite() { - if (jCheckBoxWhite == null) { - jCheckBoxWhite = new JCheckBox(); - jCheckBoxWhite.setText("White"); - jCheckBoxWhite.setSelected(true); - jCheckBoxWhite.setBackground(gray); - jCheckBoxWhite.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxWhite; - } - - /** - *

- * Getter for the field jCheckBoxColorless. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxColorless() { - if (jCheckBoxColorless == null) { - jCheckBoxColorless = new JCheckBox(); - jCheckBoxColorless.setText("Colorless"); - jCheckBoxColorless.setSelected(true); - jCheckBoxColorless.setBackground(gray); - jCheckBoxColorless.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxColorless; - } - - /** - *

- * Getter for the field jButtonOk. - *

- * - * @return a {@link javax.swing.JButton} object. - */ - private JButton getJButtonOk() { - if (jButtonOk == null) { - jButtonOk = new JButton(); - jButtonOk.setText("OK"); - jButtonOk.addMouseListener(new MouseInputAdapter() { - @Override - public void mouseClicked(final MouseEvent e) { - filterCardTable(); - } - }); - } - return jButtonOk; - } - - /** - *

- * Getter for the field jCheckBoxBlack. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxBlack() { - if (jCheckBoxBlack == null) { - jCheckBoxBlack = new JCheckBox(); - jCheckBoxBlack.setText("Black"); - jCheckBoxBlack.setBackground(gray); - jCheckBoxBlack.setSelected(true); - jCheckBoxBlack.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxBlack; - } - - /** - *

- * Getter for the field typePanel. - *

- * - * @return a {@link javax.swing.JPanel} object. - */ - private JPanel getTypePanel() { - if (typePanel == null) { - typePanel = new JPanel(); - typePanel.setLayout(new MigLayout()); - typePanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); - typePanel.setBackground(gray); - typePanel.add(getTypeLabel(), "align, wrap"); - typePanel.add(getJCheckBoxSorcery(), "wrap"); - typePanel.add(getJCheckBoxPlaneswalker(), "wrap"); - typePanel.add(getJCheckBoxLand(), "wrap"); - typePanel.add(getJCheckBoxInstant(), "wrap"); - typePanel.add(getJCheckBoxEnchant(), "wrap"); - typePanel.add(getJCheckBoxCreature(), "wrap"); - typePanel.add(getJCheckBoxArtifact(), "wrap"); - } - return typePanel; - } - - /** - *

- * Getter for the field colorLabel. - *

- * - * @return a {@link javax.swing.JLabel} object. - */ - private JLabel getColorLabel() { - if (colorLabel == null) { - colorLabel = new JLabel(); - colorLabel.setText("Color"); - colorLabel.setFont(new java.awt.Font("Segoe UI", 0, 14)); - } - return colorLabel; - } - - /** - *

- * Getter for the field typeLabel. - *

- * - * @return a {@link javax.swing.JLabel} object. - */ - private JLabel getTypeLabel() { - if (typeLabel == null) { - typeLabel = new JLabel(); - typeLabel.setText("Type"); - typeLabel.setFont(new java.awt.Font("Segoe UI", 0, 14)); - } - return typeLabel; - } - - /** - *

- * getJCheckBoxSorcery. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxSorcery() { - if (jCheckBoxSorcery == null) { - jCheckBoxSorcery = new JCheckBox(); - jCheckBoxSorcery.setText("Sorcery"); - jCheckBoxSorcery.setSelected(true); - jCheckBoxSorcery.setBackground(gray); - jCheckBoxSorcery.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxSorcery; - } - - /** - *

- * getJCheckBoxPlaneswalker. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxPlaneswalker() { - if (jCheckBoxPlaneswalker == null) { - jCheckBoxPlaneswalker = new JCheckBox(); - jCheckBoxPlaneswalker.setText("Planeswalker"); - jCheckBoxPlaneswalker.setSelected(true); - jCheckBoxPlaneswalker.setBackground(gray); - jCheckBoxPlaneswalker.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxPlaneswalker; - } - - /** - *

- * getJCheckBoxLand. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxLand() { - if (jCheckBoxLand == null) { - jCheckBoxLand = new JCheckBox(); - jCheckBoxLand.setText("Land"); - jCheckBoxLand.setSelected(true); - jCheckBoxLand.setBackground(gray); - jCheckBoxLand.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxLand; - } - - /** - *

- * getJCheckBoxInstant. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxInstant() { - if (jCheckBoxInstant == null) { - jCheckBoxInstant = new JCheckBox(); - jCheckBoxInstant.setText("Instant"); - jCheckBoxInstant.setSelected(true); - jCheckBoxInstant.setBackground(gray); - jCheckBoxInstant.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxInstant; - } - - /** - *

- * getJCheckBoxEnchant. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxEnchant() { - if (jCheckBoxEnchant == null) { - jCheckBoxEnchant = new JCheckBox(); - jCheckBoxEnchant.setText("Enchant"); - jCheckBoxEnchant.setSelected(true); - jCheckBoxEnchant.setBackground(gray); - jCheckBoxEnchant.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxEnchant; - } - - /** - *

- * getJCheckBoxCreature. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxCreature() { - if (jCheckBoxCreature == null) { - jCheckBoxCreature = new JCheckBox(); - jCheckBoxCreature.setText("Creature"); - jCheckBoxCreature.setSelected(true); - jCheckBoxCreature.setBackground(gray); - jCheckBoxCreature.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxCreature; - } - - /** - *

- * getJCheckBoxArtifact. - *

- * - * @return a {@link javax.swing.JCheckBox} object. - */ - private JCheckBox getJCheckBoxArtifact() { - if (jCheckBoxArtifact == null) { - jCheckBoxArtifact = new JCheckBox(); - jCheckBoxArtifact.setText("Artifact"); - jCheckBoxArtifact.setSelected(true); - jCheckBoxArtifact.setBackground(gray); - jCheckBoxArtifact.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return jCheckBoxArtifact; - } - - /** - *

- * getCardTextField. - *

- * - * @return a {@link javax.swing.JTextField} object. - */ - private JTextField getCardTextField() { - if (cardTextField == null) { - cardTextField = new JTextField(30); - cardTextField.addKeyListener(new java.awt.event.KeyAdapter() { - @Override - public void keyPressed(final java.awt.event.KeyEvent e) { - - if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { - filterCardTable(); - } - } - }); - } - return cardTextField; - } - - /** - *

- * Getter for the field cardTextLabel. - *

- * - * @return a {@link javax.swing.JLabel} object. - */ - private JLabel getCardTextLabel() { - if (cardTextLabel == null) { - cardTextLabel = new JLabel(); - cardTextLabel.setText("Card Text:"); - cardTextLabel.setFont(new java.awt.Font("Segoe UI", 0, 16)); - } - return cardTextLabel; - } - - /** - *

- * FilterCardTable. - *

- */ - private void filterCardTable() { - String name = nameTextField.getText(); - String cText = cardTextField.getText(); - Gui_Quest_DeckEditor g = (Gui_Quest_DeckEditor) deckDisplay; - CardFilter filter = new CardFilter(); - g.setEnabled(true); - CardList filterCardList = g.stCardList; - if (name != "") { - if (cText != "") { - filterCardList = filter.cardListNameFilter(filterCardList, name); - if (filterCardList.size() == 0) { - JOptionPane.showMessageDialog(null, "Sorry, cards with name: " + name + " not found.", "Filter", - JOptionPane.INFORMATION_MESSAGE); - g.filterUsed = false; - deckDisplay.updateDisplay(g.stCardList, deckDisplay.getBottom()); - } else { - filterCardList = filter.CardListTextFilter(filterCardList, cText); - if (filterCardList.size() == 0) { - JOptionPane.showMessageDialog(null, "Sorry, cards with text: " + cText + " not found.", - "Filter", JOptionPane.INFORMATION_MESSAGE); - g.filterUsed = false; - deckDisplay.updateDisplay(g.stCardList, deckDisplay.getBottom()); - } else { - if (!jCheckBoxBlack.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "black"); - g.blackCheckBox.setSelected(false); - g.blackCheckBox.setEnabled(false); - } - if (!jCheckBoxBlue.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "blue"); - g.blueCheckBox.setSelected(false); - g.blueCheckBox.setEnabled(false); - } - if (!jCheckBoxGreen.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "green"); - g.greenCheckBox.setSelected(false); - g.greenCheckBox.setEnabled(false); - } - if (!jCheckBoxRed.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "red"); - g.redCheckBox.setSelected(false); - g.redCheckBox.setEnabled(false); - } - if (!jCheckBoxWhite.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "white"); - g.whiteCheckBox.setSelected(false); - g.whiteCheckBox.setEnabled(false); - } - if (!jCheckBoxColorless.isSelected()) { - filterCardList = filter.CardListColorFilter(filterCardList, "colorless"); - g.colorlessCheckBox.setSelected(false); - g.colorlessCheckBox.setEnabled(false); - } - if (!jCheckBoxArtifact.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "artifact"); - g.artifactCheckBox.setSelected(false); - g.artifactCheckBox.setEnabled(false); - } - if (!jCheckBoxCreature.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "creature"); - g.creatureCheckBox.setSelected(false); - g.creatureCheckBox.setEnabled(false); - } - if (!jCheckBoxEnchant.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "enchantment"); - g.enchantmentCheckBox.setSelected(false); - g.enchantmentCheckBox.setEnabled(false); - } - if (!jCheckBoxInstant.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "instant"); - g.instantCheckBox.setSelected(false); - g.instantCheckBox.setEnabled(false); - } - if (!jCheckBoxLand.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "land"); - g.landCheckBox.setSelected(false); - g.landCheckBox.setEnabled(false); - } - if (!jCheckBoxPlaneswalker.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "planeswalker"); - g.planeswalkerCheckBox.setSelected(false); - g.planeswalkerCheckBox.setEnabled(false); - } - if (!jCheckBoxSorcery.isSelected()) { - filterCardList = filter.CardListTypeFilter(filterCardList, "sorcery"); - g.sorceryCheckBox.setSelected(false); - g.sorceryCheckBox.setEnabled(false); - } - - deckDisplay.updateDisplay(filterCardList, deckDisplay.getBottom()); - } - } - } - - } - dispose(); - } -} diff --git a/src/main/java/forge/Gui_CardShop.java b/src/main/java/forge/Gui_CardShop.java deleted file mode 100644 index 56582cbacc9..00000000000 --- a/src/main/java/forge/Gui_CardShop.java +++ /dev/null @@ -1,810 +0,0 @@ -package forge; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.Image; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Map; -import java.util.Random; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.SwingUtilities; -import javax.swing.border.Border; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; -import javax.swing.event.MouseInputAdapter; -import javax.swing.event.MouseInputListener; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableCellRenderer; - -import forge.deck.Deck; -import forge.error.ErrorViewer; -import forge.gui.game.CardDetailPanel; -import forge.gui.game.CardPicturePanel; -import forge.properties.NewConstants; -import forge.view.swing.OldGuiNewGame; - -/** - *

- * Gui_CardShop class. - *

- * - * @author Forge - * @version $Id$ - */ -public class Gui_CardShop extends JFrame implements CardContainer, DeckDisplay, NewConstants { - - /** Constant serialVersionUID=3988857075791576483L */ - private static final long serialVersionUID = 3988857075791576483L; - - Gui_DeckEditor_Menu customMenu; - - // private ImageIcon upIcon = Constant.IO.upIcon; - // private ImageIcon downIcon = Constant.IO.downIcon; - - private CardShopTableModel topModel; - private CardShopTableModel bottomModel; - - private JScrollPane jScrollPane1 = new JScrollPane(); - private JScrollPane jScrollPane2 = new JScrollPane(); - private JButton sellButton = new JButton(); - @SuppressWarnings("unused") - // border1 - private Border border1; - private TitledBorder titledBorder1; - private Border border2; - private TitledBorder titledBorder2; - private JButton buyButton = new JButton(); - - private JTable topTable; - private JTable bottomTable; - private JScrollPane jScrollPane3 = new JScrollPane(); - private JPanel jPanel3 = new JPanel(); - private GridLayout gridLayout1 = new GridLayout(); - private JLabel creditsLabel = new JLabel(); - private JLabel jLabel1 = new JLabel(); - private JLabel sellPercentageLabel = new JLabel(); - - private double multi; - - private CardList top; - private CardList bottom; - public Card cCardHQ; - - private CardDetailPanel detail = new CardDetailPanel(null); - private CardPicturePanel picture = new CardPicturePanel(null); - private JPanel glassPane; - - private forge.quest.data.QuestData questData; - - /** {@inheritDoc} */ - @Override - public void setTitle(String message) { - super.setTitle(message); - } - - /** {@inheritDoc} */ - public void updateDisplay(CardList topParam, CardList bottomParam) { - - this.top = topParam; - this.bottom = bottomParam; - - topModel.clear(); - bottomModel.clear(); - - topParam = AllZone.getNameChanger().changeCardsIfNeeded(topParam); - bottomParam = AllZone.getNameChanger().changeCardsIfNeeded(bottomParam); - - Card c; - String cardName; - ReadBoosterPack pack = new ReadBoosterPack(); - - // update top - for (int i = 0; i < topParam.size(); i++) { - c = topParam.get(i); - - // add rarity to card if this is a sealed card pool - - cardName = AllZone.getNameChanger().getOriginalName(c.getName()); - if (!pack.getRarity(cardName).equals("error")) { - c.setRarity(pack.getRarity(cardName)); - } - - // String PC = c.getSVar("PicCount"); - Random r = MyRandom.random; - // int n = 0; - // if (PC.matches("[0-9][0-9]?")) - // n = Integer.parseInt(PC); - // if (n > 1) - // c.setRandomPicture(r.nextInt(n)); - - if (c.getCurSetCode().equals("")) - c.setCurSetCode(c.getMostRecentSet()); - - if (!c.getCurSetCode().equals("")) { - int n = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()).PicCount; - if (n > 1) - c.setRandomPicture(r.nextInt(n - 1) + 1); - - c.setImageFilename(CardUtil.buildFilename(c)); - } - - topModel.addCard(c); - - }// for - - // update bottom - for (int i = 0; i < bottomParam.size(); i++) { - c = bottomParam.get(i); - - // add rarity to card if this is a sealed card pool - if (!customMenu.getGameType().equals(Constant.GameType.Constructed)) - c.setRarity(pack.getRarity(c.getName())); - - // String PC = c.getSVar("PicCount"); - Random r = MyRandom.random; - // int n = 0; - // if (PC.matches("[0-9][0-9]?")) - // n = Integer.parseInt(PC); - // if (n > 1) - // c.setRandomPicture(r.nextInt(n)); - - if (c.getCurSetCode().equals("")) - c.setCurSetCode(c.getMostRecentSet()); - - if (!c.getCurSetCode().equals("")) { - int n = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()).PicCount; - if (n > 1) - c.setRandomPicture(r.nextInt(n - 1) + 1); - - c.setImageFilename(CardUtil.buildFilename(c)); - } - - bottomModel.addCard(c); - }// for - - topModel.resort(); - bottomModel.resort(); - }// updateDisplay - - /** - *

- * updateDisplay. - *

- */ - public void updateDisplay() { - // updateDisplay(this.top, this.bottom); - - topModel.clear(); - - top = AllZone.getNameChanger().changeCardsIfNeeded(top); - bottom = AllZone.getNameChanger().changeCardsIfNeeded(bottom); - - Card c; - String cardName; - ReadBoosterPack pack = new ReadBoosterPack(); - - // update top - for (int i = 0; i < top.size(); i++) { - c = top.get(i); - - // add rarity to card if this is a sealed card pool - - cardName = AllZone.getNameChanger().getOriginalName(c.getName()); - if (!pack.getRarity(cardName).equals("error")) { - c.setRarity(pack.getRarity(cardName)); - } - - topModel.addCard(c); - }// for - - topModel.resort(); - } - - /** - *

- * getTopTableModel. - *

- * - * @return a {@link forge.CardShopTableModel} object. - */ - public CardShopTableModel getTopTableModel() { - return topModel; - } - - /** - *

- * Getter for the field top. - *

- * - * @return a {@link forge.CardList} object. - */ - public CardList getTop() { - return topModel.getCards(); - } - - // bottom shows cards that the user has chosen for his library - /** - *

- * Getter for the field bottom. - *

- * - * @return a {@link forge.CardList} object. - */ - public CardList getBottom() { - return bottomModel.getCards(); - } - - /** - *

- * show. - *

- * - * @param exitCommand - * a {@link forge.Command} object. - */ - public void show(final Command exitCommand) { - final Command exit = new Command() { - private static final long serialVersionUID = 5210924838133689758L; - - public void execute() { - Gui_CardShop.this.dispose(); - exitCommand.execute(); - } - }; - - customMenu = new Gui_DeckEditor_Menu(this, exit); - customMenu.setTitle("Card Shop"); - // this.setJMenuBar(customMenu); - - // do not change this!!!! - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent ev) { - customMenu.close(); - } - }); - - setup(); - - // show cards, makes this user friendly - // customMenu.newConstructed(); - - // get pricelist: - ReadPriceList r = new ReadPriceList(); - Map map = r.getPriceList(); - - ReadBoosterPack pack = new ReadBoosterPack(); - CardList shop; - - if (questData.getShopList() == null || questData.getShopList().size() == 0) { - shop = pack.getShopCards(questData.getWin(), questData.getLevel()); - ArrayList shopListToBeSaved = new ArrayList(); - - for (int i = 0; i < shop.size(); i++) { - Card crd = shop.get(i); - if (map.containsKey(crd.getName())) - crd.setValue(map.get(crd.getName())); - else { - System.out.println("Card " + crd.getName() + " is not in the price list."); - crd.setValue(10); - if (crd.getRarity().equals("Common")) - crd.setValue(10); - else if (crd.getRarity().equals("Uncommon")) - crd.setValue(50); - else if (crd.getRarity().equals("Rare")) - crd.setValue(200); - } - shopListToBeSaved.add(crd.getName()); - } - questData.setShopList(shopListToBeSaved); - } else // grab existing shopList - { - java.util.List shopList = questData.getShopList(); - shop = new CardList(); - - for (String aShopList : shopList) { - Card c = AllZone.getCardFactory().getCard(aShopList, null); - c.setRarity(pack.getRarity(c.getName())); - if (map.containsKey(c.getName())) { - c.setValue(map.get(c.getName())); - } else // card is not on pricelist - { - System.out.println("Card " + c.getName() + " is not in the price list."); - if (c.getRarity().equals("Common")) { - c.setValue(10); - } else if (c.getRarity().equals("Uncommon")) { - c.setValue(50); - } else if (c.getRarity().equals("Rare")) { - c.setValue(200); - } - } - - shop.add(c); - } - } - - java.util.List list = questData.getCardpool(); - CardList owned = new CardList(); - - for (String aList : list) { - Card c = AllZone.getCardFactory().getCard(aList, null); - - c.setRarity(pack.getRarity(c.getName())); - if (map.containsKey(c.getName())) { - c.setValue(map.get(c.getName())); - } else // card is not on pricelist - { - System.out.println("Card " + c.getName() + " is not in the price list."); - if (c.getRarity().equals("Common")) { - c.setValue(10); - } else if (c.getRarity().equals("Uncommon")) { - c.setValue(50); - } else if (c.getRarity().equals("Rare")) { - c.setValue(200); - } - } - owned.add(c); - } - - customMenu.populateShop(shop, owned); - - double multiPercent = multi * 100; - NumberFormat formatter = new DecimalFormat("#0.00"); - String maxSellingPrice = ""; - if (questData.getWin() <= 50) - maxSellingPrice = " Max selling price: 1000"; - sellPercentageLabel.setText("(Sell percentage: " + formatter.format(multiPercent) + "% of value)" - + maxSellingPrice); - - topModel.sort(1, true); - bottomModel.sort(1, true); - }// show(Command) - - /** - *

- * addListeners. - *

- */ - private void addListeners() { - MouseInputListener l = new MouseInputListener() { - public void mouseReleased(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mousePressed(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseExited(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseEntered(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseClicked(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseMoved(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseDragged(MouseEvent e) { - redispatchMouseEvent(e); - } - - private void redispatchMouseEvent(MouseEvent e) { - Container content = getContentPane(); - Point glassPoint = e.getPoint(); - Point contentPoint = SwingUtilities.convertPoint(glassPane, glassPoint, content); - - Component component = SwingUtilities.getDeepestComponentAt(content, contentPoint.x, contentPoint.y); - if (component == null || !SwingUtilities.isDescendingFrom(component, picture)) { - glassPane.setVisible(false); - } - } - }; - - glassPane.addMouseMotionListener(l); - glassPane.addMouseListener(l); - - picture.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent e) { - Card c = picture.getCard(); - if (c == null) - return; - Image i = ImageCache.getOriginalImage(c); - if (i == null) - return; - if (i.getWidth(null) < 300) - return; - glassPane.setVisible(true); - } - }); - }// addListeners() - - /** - *

- * setup. - *

- */ - private void setup() { - multi = 0.20 + (0.001 * questData.getWin()); - if (multi > 0.6) - multi = 0.6; - - if (questData.getMode().equals(forge.quest.data.QuestData.FANTASY)) { - if (questData.getInventory().getItemLevel("Estates") == 1) - multi += 0.01; - else if (questData.getInventory().getItemLevel("Estates") == 2) - multi += 0.0175; - else if (questData.getInventory().getItemLevel("Estates") >= 3) - multi += 0.025; - } - - addListeners(); - - // construct topTable, get all cards - topModel = new CardShopTableModel(new CardList(), this); - topModel.addListeners(topTable); - - topTable.setModel(topModel); - topModel.resizeCols(topTable); - - // construct bottomModel - bottomModel = new CardShopTableModel(this); - bottomModel.addListeners(bottomTable); - - bottomTable.setModel(bottomModel); - topModel.resizeCols(bottomTable); - - setSize(1024, 768); - this.setResizable(false); - Dimension screen = getToolkit().getScreenSize(); - Rectangle bounds = getBounds(); - bounds.width = 1024; - bounds.height = 768; - bounds.x = (screen.width - bounds.width) / 2; - bounds.y = (screen.height - bounds.height) / 2; - setBounds(bounds); - // TODO use this as soon the deck editor has resizable GUI - // //Use both so that when "un"maximizing, the frame isn't tiny - // setSize(1024, 740); - // setExtendedState(Frame.MAXIMIZED_BOTH); - }// setupAndDisplay() - - /** - *

- * Constructor for Gui_CardShop. - *

- * - * @param qd - * a {@link forge.quest.data.QuestData} object. - */ - public Gui_CardShop(forge.quest.data.QuestData qd) { - questData = qd; - try { - jbInit(); - } catch (Exception ex) { - ErrorViewer.showError(ex); - } - } - - /** - *

- * getCard. - *

- * - * @return a {@link forge.Card} object. - */ - public Card getCard() { - return detail.getCard(); - } - - /** {@inheritDoc} */ - public void setCard(Card card) { - detail.setCard(card); - picture.setCard(card); - } - - /** - *

- * jbInit. - *

- * - * @throws java.lang.Exception - * if any. - */ - private void jbInit() throws Exception { - - // Replace cell renderer with one that displays the cell text as - // tooltip. - topTable = new JTable() { - private static final long serialVersionUID = -1103518241118990299L; - - public TableCellRenderer getCellRenderer(int row, int column) { - TableCellRenderer renderer = new DefaultTableCellRenderer() { - private static final long serialVersionUID = -9208011190616028553L; - - public String getToolTipText() { - return this.getText(); - } - }; - return renderer; - } - }; - - bottomTable = new JTable() { - private static final long serialVersionUID = -3703821828491920769L; - - public TableCellRenderer getCellRenderer(int row, int column) { - TableCellRenderer renderer = new DefaultTableCellRenderer() { - private static final long serialVersionUID = -2544330968158633077L; - - public String getToolTipText() { - return this.getText(); - } - }; - return renderer; - } - }; - - border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white, new Color(148, 145, 140)); - titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)), - "All Cards"); - border2 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)); - titledBorder2 = new TitledBorder(border2, "Owned Cards"); - this.getContentPane().setLayout(null); - jScrollPane1.setBorder(titledBorder1); - jScrollPane1.setBounds(new Rectangle(19, 20, 726, 346)); - jScrollPane2.setBorder(titledBorder2); - jScrollPane2.setBounds(new Rectangle(19, 458, 726, 218)); - sellButton.setBounds(new Rectangle(180, 403, 146, 49)); - // removeButton.setIcon(upIcon); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - sellButton.setFont(new java.awt.Font("Dialog", 0, 13)); - sellButton.setText("Sell Card"); - sellButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - sellButton_actionPerformed(e); - } - }); - buyButton.setText("Buy Card"); - buyButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - buyButton_actionPerformed(e); - } - }); - - if (!OldGuiNewGame.useLAFFonts.isSelected()) - buyButton.setFont(new java.awt.Font("Dialog", 0, 13)); - buyButton.setBounds(new Rectangle(23, 403, 146, 49)); - - detail.setBounds(new Rectangle(765, 23, 239, 323)); - picture.setBounds(new Rectangle(765, 372, 239, 338)); - picture.addMouseListener(new MouseInputAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - } - }); - // Do not lower statsLabel any lower, we want this to be visible at 1024 - // x 768 screen size - this.setTitle("Card Shop"); - jScrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - jScrollPane3.setBounds(new Rectangle(6, 168, 225, 143)); - jPanel3.setBounds(new Rectangle(7, 21, 224, 141)); - jPanel3.setLayout(gridLayout1); - gridLayout1.setColumns(1); - gridLayout1.setRows(0); - creditsLabel.setBounds(new Rectangle(19, 365, 720, 31)); - creditsLabel.setText("Total credits: " + questData.getCredits()); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - creditsLabel.setFont(new java.awt.Font("Dialog", 0, 14)); - sellPercentageLabel.setBounds(new Rectangle(350, 403, 450, 31)); - sellPercentageLabel.setText("(Sell percentage: " + multi + ")"); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - sellPercentageLabel.setFont(new java.awt.Font("Dialog", 0, 14)); - jLabel1.setText("Click on the column name (like name or color) to sort the cards"); - jLabel1.setBounds(new Rectangle(20, 1, 400, 19)); - this.getContentPane().add(detail, null); - this.getContentPane().add(picture, null); - this.getContentPane().add(jScrollPane1, null); - this.getContentPane().add(jScrollPane2, null); - this.getContentPane().add(creditsLabel, null); - this.getContentPane().add(buyButton, null); - this.getContentPane().add(sellButton, null); - this.getContentPane().add(sellPercentageLabel, null); - this.getContentPane().add(jLabel1, null); - jScrollPane2.getViewport().add(bottomTable, null); - jScrollPane1.getViewport().add(topTable, null); - - glassPane = new JPanel() { - private static final long serialVersionUID = 7394924497724994317L; - - @Override - protected void paintComponent(java.awt.Graphics g) { - Image image = ImageCache.getOriginalImage(picture.getCard()); - g.drawImage(image, glassPane.getWidth() - image.getWidth(null), - glassPane.getHeight() - image.getHeight(null), null); - } - }; - setGlassPane(glassPane); - } - - /** - *

- * buyButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void buyButton_actionPerformed(ActionEvent e) { - int n = topTable.getSelectedRow(); - if (n != -1) { - Card c = topModel.rowToCard(n); - - if (c.getValue() <= questData.getCredits()) { - bottomModel.addCard(c); - bottomModel.resort(); - - topModel.removeCard(c); - - questData.subtractCredits(c.getValue()); - questData.addCard(c); - - questData.removeCardFromShopList(c); - - creditsLabel.setText("Total credits: " + questData.getCredits()); - - // 3 conditions" 0 cards left, select the same row, select next - // row - int size = topModel.getRowCount(); - if (size != 0) { - if (size == n) - n--; - topTable.addRowSelectionInterval(n, n); - } - } else { - JOptionPane.showMessageDialog(null, "Not enough credits!"); - } - }// if(valid row) - }// buyButton_actionPerformed - - /** - *

- * sellButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void sellButton_actionPerformed(ActionEvent e) { - - int n = bottomTable.getSelectedRow(); - if (n != -1) { - Card c = bottomModel.rowToCard(n); - bottomModel.removeCard(c); - - topModel.addCard(c); - topModel.resort(); - - // bottomModel.removeCard(c); - questData.addCardToShopList(c); - - long price = (long) (multi * c.getValue()); - if (questData.getWin() <= 50 && price > 1000) - price = 1000; - - questData.addCredits(price); - questData.removeCard(c); - - creditsLabel.setText("Total credits: " + questData.getCredits()); - - // remove sold cards from all decks: - java.util.List deckNames = questData.getDeckNames(); - for (String deckName : deckNames) { - Deck deck = questData.getDeck(deckName); - if (deck.getMain().contains(c.getName())) { - // count occurences: - int cardPoolCount = 0; - java.util.List cpList = questData.getCards(); - while (cpList.contains(c.getName())) { - cpList.remove(cpList.indexOf(c.getName())); - cardPoolCount++; - } - if (cardPoolCount < 4) - deck.removeMain(c); - } - } - - // 3 conditions" 0 cards left, select the same row, select next row - int size = bottomModel.getRowCount(); - if (size != 0) { - if (size == n) - n--; - bottomTable.addRowSelectionInterval(n, n); - } - }// if(valid row) - }// sellButton_actionPerformed - - /** - *

- * stats_actionPerformed. - *

- * - * @param list - * a {@link forge.CardList} object. - */ - @SuppressWarnings("unused") - // stats_actionPerformed - private void stats_actionPerformed(CardList list) { - - } - - /* - * //refresh Gui from deck, Gui shows the cards in the deck - *//** - *

- * refreshGui. - *

- */ - /* - * @SuppressWarnings("unused") // refreshGui private void refreshGui() { - * Deck deck = Constant.Runtime.HumanDeck[0]; if (deck == null) //this is - * just a patch, i know deck = new Deck(Constant.Runtime.GameType[0]); - * - * topModel.clear(); bottomModel.clear(); - * - * Card c; ReadBoosterPack pack = new ReadBoosterPack(); for (int i = 0; i < - * deck.countMain(); i++) { c = - * AllZone.getCardFactory().getCard(deck.getMain(i), - * AllZone.getHumanPlayer()); - * - * //add rarity to card if this is a sealed card pool if - * (Constant.Runtime.GameType[0].equals(Constant.GameType.Sealed)) - * c.setRarity(pack.getRarity(c.getName())); - * - * bottomModel.addCard(c); }//for - * - * if (deck.isSealed() || deck.isDraft()) { //add sideboard to GUI for (int - * i = 0; i < deck.countSideboard(); i++) { c = - * AllZone.getCardFactory().getCard(deck.getSideboard(i), - * AllZone.getHumanPlayer()); c.setRarity(pack.getRarity(c.getName())); - * topModel.addCard(c); } } else { - * - * Braids: "getAllCards copies the entire array, but that does not seem to - * be needed here. Significant performance improvement is possible if this - * code used getCards instead (along with a for each loop instead of using - * get(i), if applicable)." - * - * CardList all = AllZone.getCardFactory().getAllCards(); for (int i = 0; i - * < all.size(); i++) topModel.addCard(all.get(i)); } - * - * topModel.resort(); bottomModel.resort(); }////refreshGui() - */ - -} diff --git a/src/main/java/forge/Gui_DeckEditor.java b/src/main/java/forge/Gui_DeckEditor.java deleted file mode 100644 index c68ee8ff611..00000000000 --- a/src/main/java/forge/Gui_DeckEditor.java +++ /dev/null @@ -1,1379 +0,0 @@ -package forge; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Font; -import java.awt.Frame; -import java.awt.GridLayout; -import java.awt.Image; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.Random; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; -import javax.swing.border.Border; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; -import javax.swing.event.MouseInputListener; -import javax.swing.event.TableModelEvent; -import javax.swing.event.TableModelListener; -import javax.swing.filechooser.FileFilter; - -import net.miginfocom.swing.MigLayout; -import arcane.ui.CardPanel; -import arcane.ui.ViewPanel; -import forge.deck.Deck; -import forge.error.ErrorViewer; -import forge.gui.game.CardDetailPanel; -import forge.properties.ForgeProps; -import forge.properties.NewConstants; -import forge.view.swing.OldGuiNewGame; - -/** - *

- * Gui_DeckEditor class. - *

- * - * @author Forge - * @version $Id$ - */ -public class Gui_DeckEditor extends JFrame implements CardContainer, DeckDisplay, NewConstants { - /** Constant serialVersionUID=130339644136746796L */ - private static final long serialVersionUID = 130339644136746796L; - - public Gui_DeckEditor_Menu customMenu; - public Gui_ProgressBarWindow gPBW = new Gui_ProgressBarWindow(); - - // private ImageIcon upIcon = Constant.IO.upIcon; - // private ImageIcon downIcon = Constant.IO.downIcon; - - private TableModel topModel; - private TableModel bottomModel; - - private JScrollPane jScrollPane1 = new JScrollPane(); - private JScrollPane jScrollPane2 = new JScrollPane(); - private JButton removeButton = new JButton(); - @SuppressWarnings("unused") - // border1 - private Border border1; - private TitledBorder titledBorder1; - private Border border2; - private TitledBorder titledBorder2; - private JButton addButton = new JButton(); - private JButton analysisButton = new JButton(); - private JButton changePictureButton = new JButton(); - private JButton removePictureButton = new JButton(); - private JLabel statsLabel = new JLabel(); - private JTable topTable = new JTable(); - private JTable bottomTable = new JTable(); - private JScrollPane jScrollPane3 = new JScrollPane(); - private JPanel jPanel3 = new JPanel(); - private GridLayout gridLayout1 = new GridLayout(); - private JLabel statsLabel2 = new JLabel(); - private JLabel jLabel1 = new JLabel(); - - private JLabel jLabel2 = new JLabel(); - private JLabel jLabel3 = new JLabel(); - - private JLabel jLabel4 = new JLabel(); - - /* - * public JCheckBox whiteCheckBox = new JCheckBox("W", true); public - * JCheckBox blueCheckBox = new JCheckBox("U", true); public JCheckBox - * blackCheckBox = new JCheckBox("B", true); public JCheckBox redCheckBox = - * new JCheckBox("R", true); public JCheckBox greenCheckBox = new - * JCheckBox("G", true); public JCheckBox colorlessCheckBox = new - * JCheckBox("C", true); - * - * public JCheckBox landCheckBox = new JCheckBox("Land", true); public - * JCheckBox creatureCheckBox = new JCheckBox("Creature", true); public - * JCheckBox sorceryCheckBox = new JCheckBox("Sorcery", true); public - * JCheckBox instantCheckBox = new JCheckBox("Instant", true); public - * JCheckBox planeswalkerCheckBox = new JCheckBox("Planeswalker", true); - * public JCheckBox artifactCheckBox = new JCheckBox("Artifact", true); - * public JCheckBox enchantmentCheckBox = new JCheckBox("Enchantment", - * true); - */ - - public JCheckBox whiteCheckBox = new GuiFilterCheckBox("white", "White"); - public JCheckBox blueCheckBox = new GuiFilterCheckBox("blue", "Blue"); - public JCheckBox blackCheckBox = new GuiFilterCheckBox("black", "Black"); - public JCheckBox redCheckBox = new GuiFilterCheckBox("red", "Red"); - public JCheckBox greenCheckBox = new GuiFilterCheckBox("green", "Green"); - public JCheckBox colorlessCheckBox = new GuiFilterCheckBox("colorless", "Colorless"); - - public JCheckBox landCheckBox = new GuiFilterCheckBox("land", "Land"); - public JCheckBox creatureCheckBox = new GuiFilterCheckBox("creature", "Creature"); - public JCheckBox sorceryCheckBox = new GuiFilterCheckBox("sorcery", "Sorcery"); - public JCheckBox instantCheckBox = new GuiFilterCheckBox("instant", "Instant"); - public JCheckBox planeswalkerCheckBox = new GuiFilterCheckBox("planeswalker", "Planeswalker"); - public JCheckBox artifactCheckBox = new GuiFilterCheckBox("artifact", "Artifact"); - public JCheckBox enchantmentCheckBox = new GuiFilterCheckBox("enchant", "Enchantment"); - - /* CHOPPIC */ - public JButton filterButton = new JButton(); - private JTextField searchTextField = new JTextField(); - /* CHOPPIC */ - - private JTextField searchTextField2 = new JTextField(); - private JTextField searchTextField3 = new JTextField(); - private JComboBox searchSetCombo = new JComboBox(); - private JButton clearFilterButton = new JButton(); - - private CardList top; - private CardList bottom; - public Card cCardHQ; - /** Constant previousDirectory */ - private static File previousDirectory = null; - - private CardDetailPanel detail = new CardDetailPanel(null); - private CardPanel picture = new CardPanel(null); - private ViewPanel pictureViewPanel = new ViewPanel(); - private JPanel glassPane; - - /** {@inheritDoc} */ - @Override - public void setTitle(String message) { - super.setTitle(message); - } - - /** {@inheritDoc} */ - public void updateDisplay(CardList top, CardList bottom) { - this.top = top; - this.bottom = bottom; - - topModel.clear(); - bottomModel.clear(); - - top = AllZone.getNameChanger().changeCardsIfNeeded(top); - bottom = AllZone.getNameChanger().changeCardsIfNeeded(bottom); - - Card c; - String cardName; - ReadBoosterPack pack = new ReadBoosterPack(); - - if (gPBW.isVisible()) - gPBW.setProgressRange(0, top.size() + bottom.size()); - - // update top - for (int i = 0; i < top.size(); i++) { - if (gPBW.isVisible()) - gPBW.increment(); - - c = top.get(i); - - // add rarity to card if this is a sealed card pool - - cardName = AllZone.getNameChanger().getOriginalName(c.getName()); - if (!pack.getRarity(cardName).equals("error")) { - c.setRarity(pack.getRarity(cardName)); - } - - boolean filteredOut = filterByColor(c); - - if (!filteredOut) { - filteredOut = filterByType(c); - } - - // String PC = c.getSVar("PicCount"); - Random r = MyRandom.random; - // int n = 0; - // if (!PC.equals("")) { - // if (PC.matches("[0-9][0-9]?")) - // n = Integer.parseInt(PC); - // if (n > 1) - // c.setRandomPicture(r.nextInt(n)); - // } - - if (c.getCurSetCode().equals("")) - c.setCurSetCode(c.getMostRecentSet()); - - if (!c.getCurSetCode().equals("")) { - int n = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()).PicCount; - if (n > 1) - c.setRandomPicture(r.nextInt(n - 1) + 1); - - c.setImageFilename(CardUtil.buildFilename(c)); - } - - if (!filteredOut) { - topModel.addCard(c); - } - }// for - - // update bottom - for (int i = 0; i < bottom.size(); i++) { - if (gPBW.isVisible()) - gPBW.increment(); - - c = bottom.get(i); - - // add rarity to card if this is a sealed card pool - if (!customMenu.getGameType().equals(Constant.GameType.Constructed)) - c.setRarity(pack.getRarity(c.getName())); - - // String PC = c.getSVar("PicCount"); - Random r = MyRandom.random; - // int n = 0; - // if (!PC.equals("")) { - // if (PC.matches("[0-9][0-9]?")) - // n = Integer.parseInt(PC); - // if (n > 1) - // c.setRandomPicture(r.nextInt(n)); - // } - - if (c.getCurSetCode().equals("")) - c.setCurSetCode(c.getMostRecentSet()); - - if (!c.getCurSetCode().equals("")) { - int n = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()).PicCount; - if (n > 1) - c.setRandomPicture(r.nextInt(n - 1) + 1); - - c.setImageFilename(CardUtil.buildFilename(c)); - } - - bottomModel.addCard(c); - }// for - - if (gPBW.isVisible()) - gPBW.setTitle("Sorting Deck Editor"); - topModel.resort(); - topTable.repaint(); - bottomModel.resort(); - bottomTable.repaint(); - }// updateDisplay - - /** - *

- * updateDisplay. - *

- */ - public void updateDisplay() { - // updateDisplay(this.top, this.bottom); - - topModel.clear(); - - top = AllZone.getNameChanger().changeCardsIfNeeded(top); - bottom = AllZone.getNameChanger().changeCardsIfNeeded(bottom); - - Card c; - String cardName; - ReadBoosterPack pack = new ReadBoosterPack(); - - // update top - for (int i = 0; i < top.size(); i++) { - c = top.get(i); - - // add rarity to card if this is a sealed card pool - - cardName = AllZone.getNameChanger().getOriginalName(c.getName()); - if (!pack.getRarity(cardName).equals("error")) { - c.setRarity(pack.getRarity(cardName)); - } - - boolean filteredOut = filterByColor(c); - - if (!filteredOut) { - filteredOut = filterByType(c); - } - - if (!filteredOut) { - filteredOut = filterByName(c); - } - - if (!filteredOut) { - filteredOut = filterByCardType(c); - } - - if (!filteredOut) { - filteredOut = filterByCardDescription(c); - } - - if (!filteredOut) { - filteredOut = filterByCardSetCode(c); - } - - if (!filteredOut) { - topModel.addCard(c); - } - }// for - - topModel.resort(); - } - - /* CHOPPIC */ - /** - *

- * filterByName. - *

- * - * @param c - * a {@link forge.Card} object. - * @return a boolean. - */ - private boolean filterByName(Card c) { - boolean filterOut = false; - filterOut = !(c.getName().toLowerCase().contains(searchTextField.getText().toLowerCase())); - return filterOut; - } - - /* CHOPPIC */ - - /** - *

- * filterByCardType. - *

- * - * @param c - * a {@link forge.Card} object. - * @return a boolean. - */ - private boolean filterByCardType(Card c) { - boolean filterOut = false; - if (!(searchTextField2.getText() == "")) { - filterOut = !(c.getType().toString().toLowerCase().contains(searchTextField2.getText().toLowerCase())); - } - return filterOut; - } - - /** - *

- * filterByCardDescription. - *

- * - * @param c - * a {@link forge.Card} object. - * @return a boolean. - */ - private boolean filterByCardDescription(Card c) { - boolean filterOut = false; - if (!(searchTextField3.getText() == "")) { - filterOut = !(c.getText().toString().toLowerCase().contains(searchTextField3.getText().toLowerCase())); - } - return filterOut; - } - - /** - *

- * filterByCardSetCode. - *

- * - * @param c - * a {@link forge.Card} object. - * @return a boolean. - */ - private boolean filterByCardSetCode(Card c) { - boolean filterOut = false; - String SC = ""; - - if (!(searchSetCombo.getSelectedItem().toString().equals(""))) { - SC = SetInfoUtil.getCode3ByName(searchSetCombo.getSelectedItem().toString()); - - boolean result = false; - - if (SetInfoUtil.getSetInfo_Code(c.getSets(), SC) != null) { - c.setCurSetCode(SC); - - Random r = MyRandom.random; - int n = SetInfoUtil.getSetInfo_Code(c.getSets(), SC).PicCount; - if (n > 1) - c.setRandomPicture(r.nextInt(n - 1) + 1); - - result = true; - } - filterOut = !(result); - } else { - SC = c.getMostRecentSet(); - if (!SC.equals("")) - c.setCurSetCode(c.getMostRecentSet()); - } - - c.setImageFilename(CardUtil.buildFilename(c)); - - return filterOut; - } - - /** - *

- * filterByColor. - *

- * - * @param c - * a {@link forge.Card} object. - * @return a boolean. - */ - private boolean filterByColor(Card c) { - boolean filterOut = false; - - if (!whiteCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.White)) { - filterOut = true; - } - } - - if (!blueCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Blue)) { - filterOut = true; - } - } - - if (!blackCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Black)) { - filterOut = true; - } - } - - if (!redCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Red)) { - filterOut = true; - } - } - - if (!greenCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Green)) { - filterOut = true; - } - } - - if (!colorlessCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Colorless)) { - filterOut = true; - } - } - - return filterOut; - } - - /** - *

- * filterByType. - *

- * - * @param c - * a {@link forge.Card} object. - * @return a boolean. - */ - private boolean filterByType(Card c) { - boolean filterOut = false; - - if (!landCheckBox.isSelected() && c.isLand()) { - filterOut = true; - } - - if (!creatureCheckBox.isSelected() && c.isCreature()) { - filterOut = true; - } - - if (!sorceryCheckBox.isSelected() && c.isSorcery()) { - filterOut = true; - } - - if (!instantCheckBox.isSelected() && c.isInstant()) { - filterOut = true; - } - - if (!planeswalkerCheckBox.isSelected() && c.isPlaneswalker()) { - filterOut = true; - } - - if (!artifactCheckBox.isSelected() && c.isArtifact()) { - filterOut = true; - } - - if (!enchantmentCheckBox.isSelected() && c.isEnchantment()) { - filterOut = true; - } - - return filterOut; - } - - // top shows available card pool - // if constructed, top shows all cards - // if sealed, top shows 5 booster packs - // if draft, top shows cards that were chosen - - /** - *

- * getTopTableModel. - *

- * - * @return a {@link forge.TableModel} object. - */ - public TableModel getTopTableModel() { - return topModel; - } - - /** - *

- * Getter for the field top. - *

- * - * @return a {@link forge.CardList} object. - */ - public CardList getTop() { - return topModel.getCards(); - } - - // bottom shows cards that the user has chosen for his library - /** - *

- * Getter for the field bottom. - *

- * - * @return a {@link forge.CardList} object. - */ - public CardList getBottom() { - return bottomModel.getCards(); - } - - /** - *

- * show. - *

- * - * @param exitCommand - * a {@link forge.Command} object. - */ - public void show(final Command exitCommand) { - final Command exit = new Command() { - private static final long serialVersionUID = 5210924838133689758L; - - public void execute() { - Gui_DeckEditor.this.dispose(); - exitCommand.execute(); - } - }; - - // pm = new ProgressMonitor(this, "Loading Deck Editor", "", 0, 20000); - gPBW.setTitle("Loading Deck Editor"); - gPBW.setVisible(true); - - customMenu = new Gui_DeckEditor_Menu(this, exit); - this.setJMenuBar(customMenu); - - // do not change this!!!! - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent ev) { - customMenu.close(); - } - }); - - setup(); - - // show cards, makes this user friendly - if (Constant.Runtime.GameType[0].equals(Constant.GameType.Constructed)) - customMenu.newConstructed(); - - topModel.sort(1, true); - bottomModel.sort(1, true); - - gPBW.dispose(); - }// show(Command) - - /** - *

- * addListeners. - *

- */ - private void addListeners() { - MouseInputListener l = new MouseInputListener() { - public void mouseReleased(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mousePressed(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseExited(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseEntered(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseClicked(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseMoved(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseDragged(MouseEvent e) { - redispatchMouseEvent(e); - } - - private void redispatchMouseEvent(MouseEvent e) { - Container content = getContentPane(); - Point glassPoint = e.getPoint(); - Point contentPoint = SwingUtilities.convertPoint(glassPane, glassPoint, content); - - Component component = SwingUtilities.getDeepestComponentAt(content, contentPoint.x, contentPoint.y); - if (component == null || !SwingUtilities.isDescendingFrom(component, picture)) { - glassPane.setVisible(false); - } - } - }; - - glassPane.addMouseMotionListener(l); - glassPane.addMouseListener(l); - - picture.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent e) { - Card c = picture.getCard(); - if (c == null) - return; - Image i = ImageCache.getOriginalImage(c); - if (i == null) - return; - if (i.getWidth(null) < 300) - return; - glassPane.setVisible(true); - } - }); - }// addListeners() - - /** - *

- * setup. - *

- */ - private void setup() { - addListeners(); - - // construct topTable, get all cards - topModel = new TableModel(new CardList(), this); - topModel.addListeners(topTable); - - topTable.setModel(topModel); - topModel.resizeCols(topTable); - - // construct bottomModel - bottomModel = new TableModel(this); - bottomModel.addListeners(bottomTable); - - bottomTable.setModel(bottomModel); - topModel.resizeCols(bottomTable); - - // get stats from deck - bottomModel.addTableModelListener(new TableModelListener() { - public void tableChanged(TableModelEvent ev) { - CardList deck = bottomModel.getCards(); - statsLabel.setText(getStats(deck)); - } - }); - - // get stats from all cards - topModel.addTableModelListener(new TableModelListener() { - public void tableChanged(TableModelEvent ev) { - CardList deck = topModel.getCards(); - statsLabel2.setText(getStats(deck)); - } - }); - - // TODO use this as soon the deck editor has resizable GUI - // Use both so that when "un"maximizing, the frame isn't tiny - setSize(1024, 740); - setExtendedState(Frame.MAXIMIZED_BOTH); - - // This was an attempt to limit the width of the deck editor to 1400 - // pixels. - /* - * setSize(1024, 740); Rectangle bounds = getBounds(); Dimension screen - * = getToolkit().getScreenSize(); int maxWidth; - * - * if (screen.width >= 1400) { maxWidth = 1400; } else { maxWidth = - * screen.width; } bounds.width = maxWidth; bounds.height = - * screen.height; - * - * setMaximizedBounds(bounds); - */ - }// setupAndDisplay() - - /** - *

- * getStats. - *

- * - * @param deck - * a {@link forge.CardList} object. - * @return a {@link java.lang.String} object. - */ - private String getStats(CardList deck) { - int total = deck.size(); - int creature = deck.getType("Creature").size(); - int land = deck.getType("Land").size(); - - StringBuffer show = new StringBuffer(); - show.append("Total: ").append(total).append(", Creatures: ").append(creature).append(", Land: ").append(land); - String[] color = Constant.Color.Colors; - for (int i = 0; i < 5; i++) - show.append(", ").append(color[i]).append(": ").append(CardListUtil.getColor(deck, color[i]).size()); - - return show.toString(); - }// getStats() - - /** - *

- * Constructor for Gui_DeckEditor. - *

- */ - public Gui_DeckEditor() { - try { - jbInit(); - } catch (Exception ex) { - ErrorViewer.showError(ex); - } - } - - /** - *

- * getCard. - *

- * - * @return a {@link forge.Card} object. - */ - public Card getCard() { - return detail.getCard(); - } - - /** {@inheritDoc} */ - public void setCard(Card card) { - detail.setCard(card); - picture.setCard(card); - } - - /** - *

- * jbInit. - *

- * - * @throws java.lang.Exception - * if any. - */ - private void jbInit() throws Exception { - border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white, new Color(148, 145, 140)); - titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)), - "All Cards"); - border2 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)); - titledBorder2 = new TitledBorder(border2, "Deck"); - this.getContentPane().setLayout(null); - String tableToolTip = "Click on the column name (like name or color) to sort the cards"; - jScrollPane1.setBorder(titledBorder1); - jScrollPane1.setToolTipText(tableToolTip); - jScrollPane2.setBorder(titledBorder2); - jScrollPane2.setToolTipText(tableToolTip); - // removeButton.setIcon(upIcon); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - removeButton.setFont(new java.awt.Font("Dialog", 0, 13)); - removeButton.setText("Remove from Deck"); - removeButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - removeButton_actionPerformed(e); - } - }); - addButton.setText("Add to Deck"); - addButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - addButton_actionPerformed(e); - } - }); - // addButton.setIcon(downIcon); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - addButton.setFont(new java.awt.Font("Dialog", 0, 13)); - - /* CHOPPIC */ - filterButton.setText("Apply Filter"); - filterButton.setToolTipText("Pressing the \"return\" key will activate this button"); - filterButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - filterButton_actionPerformed(e); - } - }); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - filterButton.setFont(new java.awt.Font("Dialog", 0, 13)); - /* CHOPPIC */ - - clearFilterButton.setText("Clear Filter"); - clearFilterButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - clearFilterButton_actionPerformed(e); - } - }); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - clearFilterButton.setFont(new java.awt.Font("Dialog", 0, 13)); - - analysisButton.setText("Deck Analysis"); - analysisButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - analysisButton_actionPerformed(e); - } - }); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - analysisButton.setFont(new java.awt.Font("Dialog", 0, 13)); - - changePictureButton.setText("Change picture..."); - changePictureButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - changePictureButton_actionPerformed(e); - } - }); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - changePictureButton.setFont(new java.awt.Font("Dialog", 0, 10)); - - removePictureButton.setText("Remove picture..."); - removePictureButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - removePictureButton_actionPerformed(e); - } - }); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - removePictureButton.setFont(new java.awt.Font("Dialog", 0, 10)); - - /** - * Type filtering - */ - Font f = new Font("Tahoma", Font.PLAIN, 10); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - landCheckBox.setFont(f); - landCheckBox.setOpaque(false); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - creatureCheckBox.setFont(f); - creatureCheckBox.setOpaque(false); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - sorceryCheckBox.setFont(f); - sorceryCheckBox.setOpaque(false); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - instantCheckBox.setFont(f); - instantCheckBox.setOpaque(false); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - planeswalkerCheckBox.setFont(f); - planeswalkerCheckBox.setOpaque(false); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - artifactCheckBox.setFont(f); - artifactCheckBox.setOpaque(false); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - enchantmentCheckBox.setFont(f); - enchantmentCheckBox.setOpaque(false); - - /** - * Color filtering - */ - whiteCheckBox.setOpaque(false); - blueCheckBox.setOpaque(false); - blackCheckBox.setOpaque(false); - redCheckBox.setOpaque(false); - greenCheckBox.setOpaque(false); - colorlessCheckBox.setOpaque(false); - - // picture.addMouseListener(new CustomListener()); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - statsLabel.setFont(new java.awt.Font("Dialog", 0, 13)); - statsLabel.setText("Total: 0, Creatures: 0, Land: 0"); - // Do not lower statsLabel any lower, we want this to be visible at 1024 - // x 768 screen size - this.setTitle("Deck Editor"); - jScrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - jPanel3.setLayout(gridLayout1); - gridLayout1.setColumns(1); - gridLayout1.setRows(0); - statsLabel2.setText("Total: 0, Creatures: 0, Land: 0"); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - statsLabel2.setFont(new java.awt.Font("Dialog", 0, 13)); - /* - * jLabel1.setText( - * "Click on the column name (like name or color) to sort the cards"); - */ - - pictureViewPanel.setCardPanel(picture); - - this.getContentPane().setLayout(new MigLayout("fill")); - - // this.getContentPane().add(landCheckBox, - // "cell 0 0, egx checkbox, split 16"); - this.getContentPane().add(landCheckBox, "cell 0 0, egx checkbox, grow, split 15"); - this.getContentPane().add(creatureCheckBox, "grow"); - this.getContentPane().add(sorceryCheckBox, "grow"); - this.getContentPane().add(instantCheckBox, "grow"); - this.getContentPane().add(planeswalkerCheckBox, "grow"); - this.getContentPane().add(artifactCheckBox, "grow"); - this.getContentPane().add(enchantmentCheckBox, "grow"); - - this.getContentPane().add(whiteCheckBox, "grow"); - this.getContentPane().add(blueCheckBox, "grow"); - this.getContentPane().add(blackCheckBox, "grow"); - this.getContentPane().add(redCheckBox, "grow"); - this.getContentPane().add(greenCheckBox, "grow"); - this.getContentPane().add(colorlessCheckBox, "grow"); - - this.getContentPane().add(filterButton, "wmin 100, hmin 25, wmax 140, hmax 25, grow"); - this.getContentPane().add(clearFilterButton, "wmin 100, hmin 25, wmax 140, hmax 25, grow"); - - this.getContentPane().add(jScrollPane1, "cell 0 2 1 2, pushy, grow"); - // this.getContentPane().add(detail, "w 239, h 323, grow, flowy, wrap"); - this.getContentPane().add(detail, "w 239, h 323, cell 1 0 1 3, grow, flowy, wrap"); - // this.getContentPane().add(detail, - // "align 50% 50%, wmin 239, hmin 323, cell 1 0 1 2, flowy"); - this.getContentPane().add(changePictureButton, "align 50% 0%, cell 1 3, split 2, flowx"); - this.getContentPane().add(removePictureButton, "align 50% 0%, wrap"); - - jLabel1.setText("Name:"); - jLabel1.setToolTipText("Card names must include the text in this field"); - this.getContentPane().add(jLabel1, "cell 0 1, split 7"); - this.getContentPane().add(searchTextField, "wmin 100, grow"); - - jLabel2.setText("Type:"); - jLabel2.setToolTipText("Card types must include the text in this field"); - this.getContentPane().add(jLabel2, ""); - this.getContentPane().add(searchTextField2, "wmin 100, grow"); - jLabel3.setText("Text:"); - jLabel3.setToolTipText("Card descriptions must include the text in this field"); - this.getContentPane().add(jLabel3, ""); - this.getContentPane().add(searchTextField3, "wmin 200, grow"); - - searchSetCombo.removeAllItems(); - searchSetCombo.addItem(""); - List allSetsNames = SetInfoUtil.getNameList(); - for (String s : allSetsNames) { - searchSetCombo.addItem(s); - } - - this.getContentPane().add(searchSetCombo, "wmin 150, grow"); - - this.getContentPane().add(statsLabel2, "cell 0 4"); - this.getContentPane().add(pictureViewPanel, "wmin 239, hmin 323, grow, cell 1 4 1 4"); - - this.getContentPane().add(addButton, "w 100, h 49, sg button, cell 0 5, split 4"); - this.getContentPane().add(removeButton, "w 100, h 49, sg button"); - - // jLabel4 is used to push the analysis button to the right - // This will separate this button from the add and remove card buttons - jLabel4.setText(""); - this.getContentPane().add(jLabel4, "wmin 100, grow"); - - this.getContentPane().add(analysisButton, "w 100, h 49, wrap"); - - this.getContentPane().add(jScrollPane2, "cell 0 6, grow"); - this.getContentPane().add(statsLabel, "cell 0 7"); - - jScrollPane2.getViewport().add(bottomTable, null); - jScrollPane1.getViewport().add(topTable, null); - - glassPane = new JPanel() { - private static final long serialVersionUID = 7394924497724994317L; - - @Override - protected void paintComponent(java.awt.Graphics g) { - Image image = ImageCache.getOriginalImage(picture.getCard()); - g.drawImage(image, glassPane.getWidth() - image.getWidth(null), - glassPane.getHeight() - image.getHeight(null), null); - } - }; - setGlassPane(glassPane); - - javax.swing.JRootPane rootPane = this.getRootPane(); - rootPane.setDefaultButton(filterButton); - } - - /** - *

- * addButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void addButton_actionPerformed(ActionEvent e) { - setTitle("Deck Editor : " + customMenu.getDeckName() + " : unsaved"); - - int n = topTable.getSelectedRow(); - if (n != -1) { - Card c = topModel.rowToCard(n); - - if (customMenu.getGameType().equals(Constant.GameType.Constructed)) { - Card newC = new Card(); - newC.setName(c.getName()); - newC.setColor(c.getColor()); - newC.setType(c.getType()); - newC.setManaCost(c.getManaCost()); - newC.setBaseAttack(c.getBaseAttack()); - newC.setBaseDefense(c.getBaseDefense()); - newC.setBaseLoyalty(c.getBaseLoyalty()); - newC.setRarity(c.getRarity()); - newC.setCurSetCode(c.getCurSetCode()); - newC.setImageFilename(c.getImageFilename()); - newC.setSets(c.getSets()); - newC.setText(c.getText()); - - bottomModel.addCard(newC); - bottomModel.resort(); - } else { - // if(!Constant.GameType.Constructed.equals(customMenu.getGameType())) - // { - bottomModel.addCard(c); - bottomModel.resort(); - - top.remove(c); - topModel.removeCard(c); - } - - // 3 conditions" 0 cards left, select the same row, select next row - int size = topModel.getRowCount(); - if (size != 0) { - if (size == n) - n--; - topTable.addRowSelectionInterval(n, n); - } - }// if(valid row) - }// addButton_actionPerformed - - /* CHOPPIC */ - /** - *

- * filterButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void filterButton_actionPerformed(ActionEvent e) { - updateDisplay(); - } - - /* CHOPPIC */ - - /** - *

- * clearFilterButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void clearFilterButton_actionPerformed(ActionEvent e) { - - if (!landCheckBox.isSelected()) - landCheckBox.doClick(); - if (!creatureCheckBox.isSelected()) - creatureCheckBox.doClick(); - if (!sorceryCheckBox.isSelected()) - sorceryCheckBox.doClick(); - if (!instantCheckBox.isSelected()) - instantCheckBox.doClick(); - if (!planeswalkerCheckBox.isSelected()) - planeswalkerCheckBox.doClick(); - if (!artifactCheckBox.isSelected()) - artifactCheckBox.doClick(); - if (!enchantmentCheckBox.isSelected()) - enchantmentCheckBox.doClick(); - - if (!whiteCheckBox.isSelected()) - whiteCheckBox.doClick(); - if (!blueCheckBox.isSelected()) - blueCheckBox.doClick(); - if (!blackCheckBox.isSelected()) - blackCheckBox.doClick(); - if (!redCheckBox.isSelected()) - redCheckBox.doClick(); - if (!greenCheckBox.isSelected()) - greenCheckBox.doClick(); - if (!colorlessCheckBox.isSelected()) - colorlessCheckBox.doClick(); - - searchTextField.setText(""); - searchTextField2.setText(""); - searchTextField3.setText(""); - searchSetCombo.setSelectedIndex(0); - - updateDisplay(); - }// clearFilterButton_actionPerformed - - /** - *

- * analysisButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void analysisButton_actionPerformed(ActionEvent e) { - - if (bottomModel.getRowCount() == 0) { - JOptionPane.showMessageDialog(null, "Cards in deck not found.", "Analysis Deck", - JOptionPane.INFORMATION_MESSAGE); - } else { - Gui_DeckEditor g = Gui_DeckEditor.this; - GUI_DeckAnalysis dAnalysis = new GUI_DeckAnalysis(g, bottomModel); - dAnalysis.setVisible(true); - g.setEnabled(false); - } - } - - /** - *

- * changePictureButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void changePictureButton_actionPerformed(ActionEvent e) { - if (cCardHQ != null) { - File file = getImportFilename(); - if (file != null) { - String fileName = GuiDisplayUtil.cleanString(cCardHQ.getName()) + ".jpg"; - File base = ForgeProps.getFile(IMAGE_BASE); - File f = new File(base, fileName); - f.delete(); - - try { - - f.createNewFile(); - FileOutputStream fos = new FileOutputStream(f); - FileInputStream fis = new FileInputStream(file); - byte[] buff = new byte[32 * 1024]; - int length; - while (fis.available() > 0) { - length = fis.read(buff); - if (length > 0) - fos.write(buff, 0, length); - } - fos.flush(); - fis.close(); - fos.close(); - setCard(cCardHQ); - - } catch (IOException e1) { - e1.printStackTrace(); - } - - } - } - } - - /** - *

- * getImportFilename. - *

- * - * @return a {@link java.io.File} object. - */ - private File getImportFilename() { - JFileChooser chooser = new JFileChooser(previousDirectory); - ImagePreviewPanel preview = new ImagePreviewPanel(); - chooser.setAccessory(preview); - chooser.addPropertyChangeListener(preview); - chooser.addChoosableFileFilter(dckFilter); - int returnVal = chooser.showOpenDialog(null); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = chooser.getSelectedFile(); - previousDirectory = file.getParentFile(); - return file; - } - - return null; - - } - - private FileFilter dckFilter = new FileFilter() { - - @Override - public boolean accept(File f) { - return f.getName().endsWith(".jpg") || f.isDirectory(); - } - - @Override - public String getDescription() { - return "*.jpg"; - } - - }; - - /** - *

- * removePictureButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void removePictureButton_actionPerformed(ActionEvent e) { - if (cCardHQ != null) { - String options[] = { "Yes", "No" }; - int value = JOptionPane.showOptionDialog(null, "Do you want delete " + cCardHQ.getName() + " picture?", - "Delete picture", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, - options[1]); - if (value == 0) { - String fileName = GuiDisplayUtil.cleanString(cCardHQ.getName()) + ".jpg"; - File base = ForgeProps.getFile(IMAGE_BASE); - File f = new File(base, fileName); - f.delete(); - JOptionPane.showMessageDialog(null, "Picture " + cCardHQ.getName() + " deleted.", "Delete picture", - JOptionPane.INFORMATION_MESSAGE); - setCard(cCardHQ); - } - } - - } - - /** - *

- * removeButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void removeButton_actionPerformed(ActionEvent e) { - setTitle("Deck Editor : " + customMenu.getDeckName() + " : unsaved"); - - int n = bottomTable.getSelectedRow(); - if (n != -1) { - Card c = bottomModel.rowToCard(n); - bottomModel.removeCard(c); - - if (!Constant.GameType.Constructed.equals(customMenu.getGameType())) { - topModel.addCard(c); - topModel.resort(); - } - - // 3 conditions" 0 cards left, select the same row, select next row - int size = bottomModel.getRowCount(); - if (size != 0) { - if (size == n) - n--; - bottomTable.addRowSelectionInterval(n, n); - } - }// if(valid row) - }// - - /** - *

- * stats_actionPerformed. - *

- * - * @param list - * a {@link forge.CardList} object. - */ - @SuppressWarnings("unused") - // stats_actionPerformed - private void stats_actionPerformed(CardList list) { - - } - - // refresh Gui from deck, Gui shows the cards in the deck - /** - *

- * refreshGui. - *

- */ - @SuppressWarnings("unused") - // refreshGui - private void refreshGui() { - Deck deck = Constant.Runtime.HumanDeck[0]; - if (deck == null) // this is just a patch, i know - deck = new Deck(Constant.Runtime.GameType[0]); - - topModel.clear(); - bottomModel.clear(); - - Card c; - // ReadBoosterPack pack = new ReadBoosterPack(); - for (int i = 0; i < deck.countMain(); i++) { - c = AllZone.getCardFactory().getCard(deck.getMain(i), AllZone.getHumanPlayer()); - - // add rarity to card if this is a sealed card pool - // if(Constant.Runtime.GameType[0].equals(Constant.GameType.Sealed)) - // c.setRarity(pack.getRarity(c.getName())); - - bottomModel.addCard(c); - }// for - - if (deck.isSealed() || deck.isDraft()) { - // add sideboard to GUI - for (int i = 0; i < deck.countSideboard(); i++) { - c = AllZone.getCardFactory().getCard(deck.getSideboard(i), AllZone.getHumanPlayer()); - // c.setRarity(pack.getRarity(c.getName())); - topModel.addCard(c); - } - } else { - for (Card loopCard : AllZone.getCardFactory()) { - topModel.addCard(loopCard); - c = loopCard; // this might not be necessary - } - } - - topModel.resort(); - bottomModel.resort(); - } // //refreshGui() - - /* CHOPPIC */ - - // public class CustomListener extends MouseAdapter { - // reenable - // public void mouseEntered(MouseEvent e) { - // - // if(picturePanel.getComponentCount() != 0) { - // - // if(GuiDisplayUtil.IsPictureHQExists(cCardHQ)) { - // int cWidth = 0; - // try { - // cWidth = GuiDisplayUtil.getPictureHQwidth(cCardHQ); - // } catch(IOException e2) { - // // TODO Auto-generated catch block - // e2.printStackTrace(); - // } - // int cHeight = 0; - // try { - // cHeight = GuiDisplayUtil.getPictureHQheight(cCardHQ); - // } catch(IOException e2) { - // // Auto-generated catch block - // e2.printStackTrace(); - // } - // - // if(cWidth >= 312 && cHeight >= 445) { - // if(hq == null) { - // hq = new GUI_PictureHQ(Gui_DeckEditor.this, cCardHQ); - // } - // try { - // hq.letsGo(Gui_DeckEditor.this, cCardHQ); - // } catch(IOException e1) { - // e1.printStackTrace(); - // } - // } - // - // } - // } - // - // } - // } - -} diff --git a/src/main/java/forge/Gui_DeckEditorBase.java b/src/main/java/forge/Gui_DeckEditorBase.java deleted file mode 100644 index 58e28e29750..00000000000 --- a/src/main/java/forge/Gui_DeckEditorBase.java +++ /dev/null @@ -1,73 +0,0 @@ -package forge; - -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JCheckBox; -import javax.swing.JFrame; - -import net.slightlymagic.maxmtg.Predicate; - -import forge.card.CardRules; -import forge.card.CardPoolView; - -public class Gui_DeckEditorBase extends JFrame { - private static final long serialVersionUID = -401223933343539977L; - - //public JCheckBox whiteCheckBox = new GuiFilterCheckBox("white", "White"); - public JCheckBox whiteCheckBox = new JCheckBox("W", true); - public JCheckBox blueCheckBox = new JCheckBox("U", true); - public JCheckBox blackCheckBox = new JCheckBox("B", true); - public JCheckBox redCheckBox = new JCheckBox("R", true); - public JCheckBox greenCheckBox = new JCheckBox("G", true); - public JCheckBox colorlessCheckBox = new JCheckBox("C", true); - - public JCheckBox landCheckBox = new JCheckBox("Land", true); - public JCheckBox creatureCheckBox = new JCheckBox("Creature", true); - public JCheckBox sorceryCheckBox = new JCheckBox("Sorcery", true); - public JCheckBox instantCheckBox = new JCheckBox("Instant", true); - public JCheckBox planeswalkerCheckBox = new JCheckBox("Planeswalker", true); - public JCheckBox artifactCheckBox = new JCheckBox("Artifact", true); - public JCheckBox enchantmentCheckBox = new JCheckBox("Enchant", true); - - public static String getStats(CardPoolView deck) { - int total = deck.countAll(); - int creature = CardRules.Predicates.Presets.isCreature.aggregate(deck, CardPoolView.fnToCard, CardPoolView.fnToCount); - int land = CardRules.Predicates.Presets.isLand.aggregate(deck, CardPoolView.fnToCard, CardPoolView.fnToCount); - - StringBuffer show = new StringBuffer(); - show.append("Total - ").append(total).append(", Creatures - ").append(creature).append(", Land - ") - .append(land); - String[] color = Constant.Color.onlyColors; - List> predicates = CardRules.Predicates.Presets.colors; - for (int i = 0; i < color.length; ++i) { - show.append(String.format(", %s - %d", color[i], predicates.get(i).count(deck, CardPoolView.fnToCard))); - } - - return show.toString(); - }// getStats() - - public final Predicate buildFilter() { - List> colors = new ArrayList>(); - if (whiteCheckBox.isSelected()) { colors.add(CardRules.Predicates.Presets.isWhite); } - if (blueCheckBox.isSelected()) { colors.add(CardRules.Predicates.Presets.isBlue); } - if (blackCheckBox.isSelected()) { colors.add(CardRules.Predicates.Presets.isBlack); } - if (redCheckBox.isSelected()) { colors.add(CardRules.Predicates.Presets.isRed); } - if (greenCheckBox.isSelected()) { colors.add(CardRules.Predicates.Presets.isGreen); } - if (colorlessCheckBox.isSelected()) { colors.add(CardRules.Predicates.Presets.isColorless); } - Predicate filterByColor = colors.size() == 6 ? Predicate.getTrue(CardRules.class) : Predicate.or(colors); - - List> types = new ArrayList>(); - if (landCheckBox.isSelected()) { types.add(CardRules.Predicates.Presets.isLand); } - if (creatureCheckBox.isSelected()) { types.add(CardRules.Predicates.Presets.isCreature); } - if (sorceryCheckBox.isSelected()) { types.add(CardRules.Predicates.Presets.isSorcery); } - if (instantCheckBox.isSelected()) { types.add(CardRules.Predicates.Presets.isInstant); } - if (planeswalkerCheckBox.isSelected()) { types.add(CardRules.Predicates.Presets.isPlaneswalker); } - if (artifactCheckBox.isSelected()) { types.add(CardRules.Predicates.Presets.isArtifact); } - if (enchantmentCheckBox.isSelected()) { types.add(CardRules.Predicates.Presets.isEnchantment); } - Predicate filterByType = colors.size() == 7 ? Predicate.getTrue(CardRules.class) : Predicate.or(types); - - return Predicate.and(filterByColor, filterByType); - } - -} diff --git a/src/main/java/forge/Gui_Quest_DeckEditor.java b/src/main/java/forge/Gui_Quest_DeckEditor.java deleted file mode 100644 index 31dabee0c2d..00000000000 --- a/src/main/java/forge/Gui_Quest_DeckEditor.java +++ /dev/null @@ -1,1170 +0,0 @@ -package forge; - -import forge.deck.Deck; -import forge.error.ErrorViewer; -import forge.gui.game.CardDetailPanel; -import forge.gui.game.CardPicturePanel; -import forge.properties.ForgeProps; -import forge.properties.NewConstants; -import forge.view.swing.OldGuiNewGame; - -import javax.swing.*; -import javax.swing.border.Border; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; -import javax.swing.event.MouseInputAdapter; -import javax.swing.event.MouseInputListener; -import javax.swing.event.TableModelEvent; -import javax.swing.event.TableModelListener; -import javax.swing.filechooser.FileFilter; -import java.awt.Color; -import java.awt.*; -import java.awt.event.*; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Random; - -//import forge.quest.data.QuestBoosterPack; - -/** - *

- * Gui_Quest_DeckEditor class. - *

- * - * @author Forge - * @version $Id$ - */ -public class Gui_Quest_DeckEditor extends JFrame implements CardContainer, DeckDisplay, NewConstants { - /** Constant serialVersionUID=152061168634545L */ - private static final long serialVersionUID = 152061168634545L; - - Gui_Quest_DeckEditor_Menu customMenu; - - // private ImageIcon upIcon = Constant.IO.upIcon; - // private ImageIcon downIcon = Constant.IO.downIcon; - - public TableModel topModel; - public TableModel bottomModel; - - private JScrollPane jScrollPane1 = new JScrollPane(); - private JScrollPane jScrollPane2 = new JScrollPane(); - private JButton removeButton = new JButton(); - @SuppressWarnings("unused") - // border1 - private Border border1; - private TitledBorder titledBorder1; - private Border border2; - private TitledBorder titledBorder2; - private JButton addButton = new JButton(); - private JButton analysisButton = new JButton(); - private JButton changePictureButton = new JButton(); - private JButton removePictureButton = new JButton(); - private JLabel statsLabel = new JLabel(); - private JTable topTable = new JTable(); - private JTable bottomTable = new JTable(); - private GridLayout gridLayout1 = new GridLayout(); - private JLabel statsLabel2 = new JLabel(); - private JLabel jLabel1 = new JLabel(); - - public JCheckBox whiteCheckBox = new JCheckBox("W", true); - public JCheckBox blueCheckBox = new JCheckBox("U", true); - public JCheckBox blackCheckBox = new JCheckBox("B", true); - public JCheckBox redCheckBox = new JCheckBox("R", true); - public JCheckBox greenCheckBox = new JCheckBox("G", true); - public JCheckBox colorlessCheckBox = new JCheckBox("C", true); - - public JCheckBox landCheckBox = new JCheckBox("Land", true); - public JCheckBox creatureCheckBox = new JCheckBox("Creature", true); - public JCheckBox sorceryCheckBox = new JCheckBox("Sorcery", true); - public JCheckBox instantCheckBox = new JCheckBox("Instant", true); - public JCheckBox planeswalkerCheckBox = new JCheckBox("Planeswalker", true); - public JCheckBox artifactCheckBox = new JCheckBox("Artifact", true); - public JCheckBox enchantmentCheckBox = new JCheckBox("Enchant", true); - public CardList stCardList; - public boolean filterUsed; - private CardList top; - private CardList bottom; - public Card cCardHQ; - /** Constant previousDirectory */ - private static File previousDirectory = null; - - private CardDetailPanel detail = new CardDetailPanel(null); - private CardPicturePanel picture = new CardPicturePanel(null); - private JPanel glassPane; - - /** {@inheritDoc} */ - @Override - public void setTitle(String message) { - super.setTitle(message); - } - - /** {@inheritDoc} */ - public void updateDisplay(CardList top, CardList bottom) { - - this.top = top; - this.bottom = bottom; - - topModel.clear(); - bottomModel.clear(); - - top = AllZone.getNameChanger().changeCardsIfNeeded(top); - bottom = AllZone.getNameChanger().changeCardsIfNeeded(bottom); - - Card c; - String cardName; - // QuestBoosterPack pack = new QuestBoosterPack(); - - java.util.List addedList = AllZone.getQuestData().getAddedCards(); - - // update top - for (int i = 0; i < top.size(); i++) { - c = top.get(i); - - cardName = c.getName(); - c.setRarity(c.getSVar("Rarity")); - - if (addedList.contains(cardName)) - c.setRarity("new"); - - // String PC = c.getSVar("PicCount"); - Random r = MyRandom.random; - // int n = 0; - // if (!PC.equals("")) { - // if (PC.matches("[0-9][0-9]?")) - // n = Integer.parseInt(PC); - // if (n > 1) - // c.setRandomPicture(r.nextInt(n)); - // } - - if (c.getCurSetCode().equals("")) - c.setCurSetCode(c.getMostRecentSet()); - - if (!c.getCurSetCode().equals("")) { - int n = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()).PicCount; - if (n > 1) - c.setRandomPicture(r.nextInt(n - 1) + 1); - - c.setImageFilename(CardUtil.buildFilename(c)); - } - - topModel.addCard(c); - }// for - - // update bottom - for (int i = 0; i < bottom.size(); i++) { - c = bottom.get(i); - - c.setRarity(c.getSVar("Rarity")); - - // String PC = c.getSVar("PicCount"); - Random r = MyRandom.random; - // int n = 0; - // if (!PC.equals("")){ - // if (PC.matches("[0-9][0-9]?")) - // n = Integer.parseInt(PC); - // if (n > 1) - // c.setRandomPicture(r.nextInt(n)); - // } - - if (c.getCurSetCode().equals("")) - c.setCurSetCode(c.getMostRecentSet()); - - if (!c.getCurSetCode().equals("")) { - int n = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()).PicCount; - if (n > 1) - c.setRandomPicture(r.nextInt(n - 1) + 1); - - c.setImageFilename(CardUtil.buildFilename(c)); - } - - bottomModel.addCard(c); - }// for - - topModel.resort(); - bottomModel.resort(); - }// updateDisplay - - /** - *

- * updateDisplay. - *

- */ - public void updateDisplay() { - // updateDisplay(this.top, this.bottom); - - topModel.clear(); - - top = AllZone.getNameChanger().changeCardsIfNeeded(top); - bottom = AllZone.getNameChanger().changeCardsIfNeeded(bottom); - - Card c; - String cardName; - ReadBoosterPack pack = new ReadBoosterPack(); - - // update top - for (int i = 0; i < top.size(); i++) { - c = top.get(i); - - // add rarity to card if this is a sealed card pool - - cardName = AllZone.getNameChanger().getOriginalName(c.getName()); - if (!pack.getRarity(cardName).equals("error")) { - c.setRarity(pack.getRarity(cardName)); - } - - boolean filteredOut = filterByColor(c); - - if (!filteredOut) { - filteredOut = filterByType(c); - } - - if (!filteredOut) { - topModel.addCard(c); - } - }// for - - topModel.resort(); - } - - /** - *

- * filterByColor. - *

- * - * @param c - * a {@link forge.Card} object. - * @return a boolean. - */ - private boolean filterByColor(Card c) { - boolean filterOut = false; - - if (!whiteCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.White)) { - filterOut = true; - } - } - - if (!blueCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Blue)) { - filterOut = true; - } - } - - if (!blackCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Black)) { - filterOut = true; - } - } - - if (!redCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Red)) { - filterOut = true; - } - } - - if (!greenCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Green)) { - filterOut = true; - } - } - - if (!colorlessCheckBox.isSelected()) { - if (CardUtil.getColors(c).contains(Constant.Color.Colorless)) { - filterOut = true; - } - } - - return filterOut; - } - - /** - *

- * filterByType. - *

- * - * @param c - * a {@link forge.Card} object. - * @return a boolean. - */ - private boolean filterByType(Card c) { - boolean filterOut = false; - - if (!landCheckBox.isSelected() && c.isLand()) { - filterOut = true; - } - - if (!creatureCheckBox.isSelected() && c.isCreature()) { - filterOut = true; - } - - if (!sorceryCheckBox.isSelected() && c.isSorcery()) { - filterOut = true; - } - - if (!instantCheckBox.isSelected() && c.isInstant()) { - filterOut = true; - } - - if (!planeswalkerCheckBox.isSelected() && c.isPlaneswalker()) { - filterOut = true; - } - - if (!artifactCheckBox.isSelected() && c.isArtifact()) { - filterOut = true; - } - - if (!enchantmentCheckBox.isSelected() && c.isEnchantment()) { - filterOut = true; - } - - return filterOut; - } - - /** - *

- * getTopTableModel. - *

- * - * @return a {@link forge.TableModel} object. - */ - public TableModel getTopTableModel() { - return topModel; - } - - // top shows available card pool - /** - *

- * Getter for the field top. - *

- * - * @return a {@link forge.CardList} object. - */ - public CardList getTop() { - return topModel.getCards(); - } - - // bottom shows cards that the user has chosen for his library - /** - *

- * Getter for the field bottom. - *

- * - * @return a {@link forge.CardList} object. - */ - public CardList getBottom() { - return bottomModel.getCards(); - } - - /** - *

- * show. - *

- * - * @param exitCommand - * a {@link forge.Command} object. - */ - public void show(final Command exitCommand) { - final Command exit = new Command() { - private static final long serialVersionUID = -7428793574300520612L; - - public void execute() { - Gui_Quest_DeckEditor.this.dispose(); - exitCommand.execute(); - } - }; - - // do not change this!!!! - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent ev) { - customMenu.close(); - } - }); - - setup(); - - customMenu = new Gui_Quest_DeckEditor_Menu(this, exit); - this.setJMenuBar(customMenu); - - forge.quest.data.QuestData questData = AllZone.getQuestData(); - Deck deck = null; - - // open deck that the player used if QuestData has it - if (Constant.Runtime.HumanDeck[0] != null - && questData.getDeckNames().contains(Constant.Runtime.HumanDeck[0].getName())) { - deck = questData.getDeck(Constant.Runtime.HumanDeck[0].getName()); - } else { - deck = new Deck(Constant.GameType.Sealed); - deck.setName(""); - } - - // tell Gui_Quest_DeckEditor the name of the deck - customMenu.setHumanPlayer(deck.getName()); - - // convert Deck main into CardList to show on the screen - // convert Deck main into CardList to show on the screen - CardList bottom = new CardList(); - for (int i = 0; i < deck.countMain(); i++) { - bottom.add(AllZone.getCardFactory().getCard(deck.getMain(i), null)); - } - - java.util.ArrayList list = (ArrayList) AllZone.getQuestData().getCardpool(); - - CardList cardpool = Gui_Quest_DeckEditor_Menu.covertToCardList(list); - - // remove bottom cards that are in the deck from the card pool - for (int i = 0; i < bottom.size(); i++) { - if (cardpool.containsName(bottom.get(i).getName())) - cardpool.remove(bottom.get(i).getName()); - } - - // show cards, makes this user friendly, lol, well may, ha - updateDisplay(cardpool, bottom); - - // this affects the card pool - topModel.sort(4, true);// sort by type - topModel.sort(3, true);// then sort by color - - bottomModel.sort(1, true); - }// show(Command) - - /** - *

- * addListeners. - *

- */ - private void addListeners() { - MouseInputListener l = new MouseInputListener() { - public void mouseReleased(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mousePressed(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseExited(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseEntered(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseClicked(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseMoved(MouseEvent e) { - redispatchMouseEvent(e); - } - - public void mouseDragged(MouseEvent e) { - redispatchMouseEvent(e); - } - - private void redispatchMouseEvent(MouseEvent e) { - Container content = getContentPane(); - Point glassPoint = e.getPoint(); - Point contentPoint = SwingUtilities.convertPoint(glassPane, glassPoint, content); - - Component component = SwingUtilities.getDeepestComponentAt(content, contentPoint.x, contentPoint.y); - if (component == null || !SwingUtilities.isDescendingFrom(component, picture)) { - glassPane.setVisible(false); - } - } - }; - - glassPane.addMouseMotionListener(l); - glassPane.addMouseListener(l); - - picture.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent e) { - Card c = picture.getCard(); - if (c == null) - return; - Image i = ImageCache.getOriginalImage(c); - if (i == null) - return; - if (i.getWidth(null) < 200) - return; - glassPane.setVisible(true); - } - }); - }// addListeners() - - /** - *

- * setup. - *

- */ - public void setup() { - addListeners(); - - // construct topTable, get all cards - topModel = new TableModel(new CardList(), this); - topModel.addListeners(topTable); - topTable.setModel(topModel); - topModel.resizeCols(topTable); - - // construct bottomModel - bottomModel = new TableModel(this); - bottomModel.addListeners(bottomTable); - bottomTable.setModel(bottomModel); - bottomModel.resizeCols(bottomTable); - - // get stats from deck - bottomModel.addTableModelListener(new TableModelListener() { - public void tableChanged(TableModelEvent ev) { - CardList deck = bottomModel.getCards(); - statsLabel.setText(getStats(deck)); - } - }); - - // get stats from all cards - topModel.addTableModelListener(new TableModelListener() { - public void tableChanged(TableModelEvent ev) { - CardList deck = topModel.getCards(); - statsLabel2.setText(getStats(deck)); - } - }); - - setSize(1024, 768); - this.setResizable(false); - Dimension screen = getToolkit().getScreenSize(); - Rectangle bounds = getBounds(); - bounds.width = 1024; - bounds.height = 768; - bounds.x = (screen.width - bounds.width) / 2; - bounds.y = (screen.height - bounds.height) / 2; - setBounds(bounds); - - // TODO use this as soon the deck editor has resizable GUI - // //Use both so that when "un"maximizing, the frame isn't tiny - // setSize(1024, 740); - // setExtendedState(Frame.MAXIMIZED_BOTH); - }// setupAndDisplay() - - /** - *

- * getStats. - *

- * - * @param deck - * a {@link forge.CardList} object. - * @return a {@link java.lang.String} object. - */ - private String getStats(CardList deck) { - int total = deck.size(); - int creature = deck.getType("Creature").size(); - int land = deck.getType("Land").size(); - - StringBuffer show = new StringBuffer(); - show.append("Total - ").append(total).append(", Creatures - ").append(creature).append(", Land - ") - .append(land); - String[] color = Constant.Color.Colors; - for (int i = 0; i < 5; i++) - show.append(", ").append(color[i]).append(" - ").append(CardListUtil.getColor(deck, color[i]).size()); - - return show.toString(); - }// getStats() - - /** - *

- * Constructor for Gui_Quest_DeckEditor. - *

- */ - public Gui_Quest_DeckEditor() { - try { - filterUsed = false; - jbInit(); - } catch (Exception ex) { - ErrorViewer.showError(ex); - } - } - - /** - *

- * getCard. - *

- * - * @return a {@link forge.Card} object. - */ - public Card getCard() { - return detail.getCard(); - } - - /** {@inheritDoc} */ - public void setCard(Card card) { - detail.setCard(card); - picture.setCard(card); - } - - /** - *

- * jbInit. - *

- * - * @throws java.lang.Exception - * if any. - */ - private void jbInit() throws Exception { - - border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white, new Color(148, 145, 140)); - titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)), - "All Cards"); - border2 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)); - titledBorder2 = new TitledBorder(border2, "Deck"); - this.getContentPane().setLayout(null); - jScrollPane1.setBorder(titledBorder1); - jScrollPane1.setBounds(new Rectangle(19, 20, 726, 346)); - jScrollPane2.setBorder(titledBorder2); - jScrollPane2.setBounds(new Rectangle(19, 458, 726, 218)); - removeButton.setBounds(new Rectangle(180, 403, 146, 49)); - // removeButton.setIcon(upIcon); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - removeButton.setFont(new java.awt.Font("Dialog", 0, 13)); - removeButton.setText("Remove Card"); - removeButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - removeButton_actionPerformed(e); - } - }); - addButton.setText("Add Card"); - addButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - addButton_actionPerformed(e); - } - }); - // addButton.setIcon(downIcon); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - addButton.setFont(new java.awt.Font("Dialog", 0, 13)); - addButton.setBounds(new Rectangle(23, 403, 146, 49)); - - analysisButton.setText("Deck Analysis"); - analysisButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - analysisButton_actionPerformed(e); - } - }); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - analysisButton.setFont(new java.awt.Font("Dialog", 0, 13)); - analysisButton.setBounds(new Rectangle(578, 426, 166, 25)); - - changePictureButton.setText("Change picture..."); - changePictureButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - changePictureButton_actionPerformed(e); - } - }); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - changePictureButton.setFont(new java.awt.Font("Dialog", 0, 10)); - changePictureButton.setBounds(new Rectangle(765, 349, 118, 20)); - - removePictureButton.setText("Remove picture..."); - removePictureButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - removePictureButton_actionPerformed(e); - } - }); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - removePictureButton.setFont(new java.awt.Font("Dialog", 0, 10)); - removePictureButton.setBounds(new Rectangle(885, 349, 118, 20)); - - /** - * Type filtering - */ - Font f = new Font("Tahoma", Font.PLAIN, 10); - landCheckBox.setBounds(340, 400, 48, 20); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - landCheckBox.setFont(f); - landCheckBox.setOpaque(false); - landCheckBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - creatureCheckBox.setBounds(385, 400, 65, 20); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - creatureCheckBox.setFont(f); - creatureCheckBox.setOpaque(false); - creatureCheckBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - sorceryCheckBox.setBounds(447, 400, 62, 20); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - sorceryCheckBox.setFont(f); - sorceryCheckBox.setOpaque(false); - sorceryCheckBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - instantCheckBox.setBounds(505, 400, 60, 20); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - instantCheckBox.setFont(f); - instantCheckBox.setOpaque(false); - instantCheckBox.addItemListener(new ItemListener() { - - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - planeswalkerCheckBox.setBounds(558, 400, 85, 20); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - planeswalkerCheckBox.setFont(f); - planeswalkerCheckBox.setOpaque(false); - planeswalkerCheckBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - artifactCheckBox.setBounds(638, 400, 58, 20); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - artifactCheckBox.setFont(f); - artifactCheckBox.setOpaque(false); - artifactCheckBox.addItemListener(new ItemListener() { - - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - enchantmentCheckBox.setBounds(692, 400, 80, 20); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - enchantmentCheckBox.setFont(f); - enchantmentCheckBox.setOpaque(false); - enchantmentCheckBox.addItemListener(new ItemListener() { - - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - - /** - * Color filtering - */ - whiteCheckBox.setBounds(340, 430, 40, 20); - whiteCheckBox.setOpaque(false); - whiteCheckBox.addItemListener(new ItemListener() { - - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - blueCheckBox.setBounds(380, 430, 40, 20); - blueCheckBox.setOpaque(false); - blueCheckBox.addItemListener(new ItemListener() { - - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - blackCheckBox.setBounds(420, 430, 40, 20); - blackCheckBox.setOpaque(false); - blackCheckBox.addItemListener(new ItemListener() { - - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - redCheckBox.setBounds(460, 430, 40, 20); - redCheckBox.setOpaque(false); - redCheckBox.addItemListener(new ItemListener() { - - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - greenCheckBox.setBounds(500, 430, 40, 20); - greenCheckBox.setOpaque(false); - greenCheckBox.addItemListener(new ItemListener() { - - public void itemStateChanged(ItemEvent e) { - updateDisplay(); - } - }); - colorlessCheckBox.setBounds(540, 430, 40, 20); - colorlessCheckBox.setOpaque(false); - colorlessCheckBox.addItemListener(new ItemListener() { - - public void itemStateChanged(ItemEvent e) { - - updateDisplay(); - } - }); - - /** - * Other - */ - - detail.setBounds(new Rectangle(765, 23, 239, 323)); - picture.setBounds(new Rectangle(765, 372, 239, 338)); - picture.addMouseListener(new MouseInputAdapter() { - - }); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - statsLabel.setFont(new java.awt.Font("Dialog", 0, 14)); - statsLabel.setText("Total - 0, Creatures - 0 Land - 0"); - statsLabel.setBounds(new Rectangle(19, 672, 720, 31)); - // Do not lower statsLabel any lower, we want this to be visible at 1024 - // x 768 screen size - this.setTitle("Deck Editor"); - gridLayout1.setColumns(1); - gridLayout1.setRows(0); - statsLabel2.setBounds(new Rectangle(19, 365, 720, 31)); - statsLabel2.setText("Total - 0, Creatures - 0 Land - 0"); - if (!OldGuiNewGame.useLAFFonts.isSelected()) - statsLabel2.setFont(new java.awt.Font("Dialog", 0, 14)); - jLabel1.setText("Click on the column name (like name or color) to sort the cards"); - jLabel1.setBounds(new Rectangle(20, 1, 400, 19)); - this.getContentPane().add(detail, null); - this.getContentPane().add(picture, null); - this.getContentPane().add(jScrollPane1, null); - this.getContentPane().add(jScrollPane2, null); - this.getContentPane().add(addButton, null); - this.getContentPane().add(removeButton, null); - this.getContentPane().add(analysisButton, null); - this.getContentPane().add(changePictureButton, null); - this.getContentPane().add(removePictureButton, null); - this.getContentPane().add(statsLabel2, null); - this.getContentPane().add(statsLabel, null); - this.getContentPane().add(jLabel1, null); - jScrollPane2.getViewport().add(bottomTable, null); - jScrollPane1.getViewport().add(topTable, null); - - this.getContentPane().add(landCheckBox, null); - this.getContentPane().add(creatureCheckBox, null); - this.getContentPane().add(sorceryCheckBox, null); - this.getContentPane().add(instantCheckBox, null); - this.getContentPane().add(planeswalkerCheckBox, null); - this.getContentPane().add(artifactCheckBox, null); - this.getContentPane().add(enchantmentCheckBox, null); - - this.getContentPane().add(whiteCheckBox, null); - this.getContentPane().add(blueCheckBox, null); - this.getContentPane().add(blackCheckBox, null); - this.getContentPane().add(redCheckBox, null); - this.getContentPane().add(greenCheckBox, null); - this.getContentPane().add(colorlessCheckBox, null); - - glassPane = new JPanel() { - private static final long serialVersionUID = 7394924497724994317L; - - @Override - protected void paintComponent(java.awt.Graphics g) { - Image image = ImageCache.getOriginalImage(picture.getCard()); - g.drawImage(image, glassPane.getWidth() - image.getWidth(null), - glassPane.getHeight() - image.getHeight(null), null); - } - }; - setGlassPane(glassPane); - } - - /** - *

- * addButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void addButton_actionPerformed(ActionEvent e) { - setTitle("Deck Editor : " + customMenu.getDeckName() + " : unsaved"); - - int n = topTable.getSelectedRow(); - if (n != -1) { - Card c = topModel.rowToCard(n); - bottomModel.addCard(c); - bottomModel.resort(); - if (filterUsed == true) { - stCardList.remove(c.getName()); - stCardList.shuffle(); - } - - if (!Constant.GameType.Constructed.equals(customMenu.getGameType())) { - topModel.removeCard(c); - if (filterUsed == false) { - stCardList = this.getTop(); - } - - } - - // 3 conditions" 0 cards left, select the same row, select next row - int size = topModel.getRowCount(); - if (size != 0) { - if (size == n) - n--; - topTable.addRowSelectionInterval(n, n); - } - }// if(valid row) - - }// addButton_actionPerformed - - /** - *

- * analysisButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void analysisButton_actionPerformed(ActionEvent e) { - - if (bottomModel.getRowCount() == 0) { - JOptionPane.showMessageDialog(null, "Cards in deck not found.", "Analysis Deck", - JOptionPane.INFORMATION_MESSAGE); - } else { - Gui_Quest_DeckEditor g = Gui_Quest_DeckEditor.this; - GUI_DeckAnalysis dAnalysis = new GUI_DeckAnalysis(g, bottomModel); - dAnalysis.setVisible(true); - g.setEnabled(false); - } - } - - /** - *

- * changePictureButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void changePictureButton_actionPerformed(ActionEvent e) { - if (cCardHQ != null) { - File file = getImportFilename(); - if (file != null) { - String fileName = GuiDisplayUtil.cleanString(cCardHQ.getName()) + ".jpg"; - File base = ForgeProps.getFile(IMAGE_BASE); - File f = new File(base, fileName); - f.delete(); - - try { - - f.createNewFile(); - FileOutputStream fos = new FileOutputStream(f); - FileInputStream fis = new FileInputStream(file); - byte[] buff = new byte[32 * 1024]; - int length; - while (fis.available() > 0) { - length = fis.read(buff); - if (length > 0) - fos.write(buff, 0, length); - } - fos.flush(); - fis.close(); - fos.close(); - setCard(cCardHQ); - - } catch (IOException e1) { - e1.printStackTrace(); - } - - } - } - } - - /** - *

- * getImportFilename. - *

- * - * @return a {@link java.io.File} object. - */ - private File getImportFilename() { - JFileChooser chooser = new JFileChooser(previousDirectory); - ImagePreviewPanel preview = new ImagePreviewPanel(); - chooser.setAccessory(preview); - chooser.addPropertyChangeListener(preview); - chooser.addChoosableFileFilter(dckFilter); - int returnVal = chooser.showOpenDialog(null); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = chooser.getSelectedFile(); - previousDirectory = file.getParentFile(); - return file; - } - - return null; - - } - - private FileFilter dckFilter = new FileFilter() { - - @Override - public boolean accept(File f) { - return f.getName().endsWith(".jpg") || f.isDirectory(); - } - - @Override - public String getDescription() { - return "*.jpg"; - } - - }; - - /** - *

- * removePictureButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void removePictureButton_actionPerformed(ActionEvent e) { - if (cCardHQ != null) { - String options[] = { "Yes", "No" }; - int value = JOptionPane.showOptionDialog(null, "Do you want delete " + cCardHQ.getName() + " picture?", - "Delete picture", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, - options[1]); - if (value == 0) { - String fileName = GuiDisplayUtil.cleanString(cCardHQ.getName()) + ".jpg"; - File base = ForgeProps.getFile(IMAGE_BASE); - File f = new File(base, fileName); - f.delete(); - JOptionPane.showMessageDialog(null, "Picture " + cCardHQ.getName() + " deleted.", "Delete picture", - JOptionPane.INFORMATION_MESSAGE); - setCard(cCardHQ); - } - } - - } - - /** - *

- * removeButton_actionPerformed. - *

- * - * @param e - * a {@link java.awt.event.ActionEvent} object. - */ - void removeButton_actionPerformed(ActionEvent e) { - setTitle("Deck Editor : " + customMenu.getDeckName() + " : unsaved"); - - int n = bottomTable.getSelectedRow(); - if (n != -1) { - Card c = bottomModel.rowToCard(n); - bottomModel.removeCard(c); - if (filterUsed == true) { - stCardList.add(c); - } - - if (!Constant.GameType.Constructed.equals(customMenu.getGameType())) { - topModel.addCard(c); - topModel.resort(); - if (filterUsed == false) { - stCardList = this.getTop(); - } - } - - // 3 conditions" 0 cards left, select the same row, select next row - int size = bottomModel.getRowCount(); - if (size != 0) { - if (size == n) - n--; - bottomTable.addRowSelectionInterval(n, n); - } - }// if(valid row) - - }// removeButton_actionPerformed - - /** - *

- * stats_actionPerformed. - *

- * - * @param list - * a {@link forge.CardList} object. - */ - @SuppressWarnings("unused") - // stats_actionPerformed - private void stats_actionPerformed(CardList list) { - - } - - /* - * //refresh Gui from deck, Gui shows the cards in the deck - *//** - *

- * refreshGui. - *

- */ - /* - * @SuppressWarnings("unused") // refreshGui private void refreshGui() { - * Deck deck = Constant.Runtime.HumanDeck[0]; if (deck == null) //this is - * just a patch, i know deck = new Deck(Constant.Runtime.GameType[0]); - * - * topModel.clear(); bottomModel.clear(); - * - * Card c; ReadBoosterPack pack = new ReadBoosterPack(); for (int i = 0; i < - * deck.countMain(); i++) { c = - * AllZone.getCardFactory().getCard(deck.getMain(i), - * AllZone.getHumanPlayer()); - * - * c.setRarity(pack.getRarity(c.getName())); - * - * - * bottomModel.addCard(c); }//for - * - * if (deck.isSealed() || deck.isDraft()) { //add sideboard to GUI for (int - * i = 0; i < deck.countSideboard(); i++) { c = - * AllZone.getCardFactory().getCard(deck.getSideboard(i), - * AllZone.getHumanPlayer()); c.setRarity(pack.getRarity(c.getName())); - * topModel.addCard(c); } } else { - * - * - * Braids: "getAllCards copies the entire array, but that does not seem to - * be needed here. Significant performance improvement is possible if this - * code used getCards instead (along with a for each loop instead of using - * get(i), if applicable)." - * - * CardList all = AllZone.getCardFactory().getAllCards(); for (int i = 0; i - * < all.size(); i++) topModel.addCard(all.get(i)); } - * - * topModel.resort(); bottomModel.resort(); }////refreshGui() - */ - // public class CustomListener extends MouseAdapter { - // TODO reenable - // public void mouseEntered(MouseEvent e) { - // - // if(picturePanel.getComponentCount() != 0) { - // - // - // if(GuiDisplayUtil.IsPictureHQExists(cCardHQ)) { - // int cWidth = 0; - // try { - // cWidth = GuiDisplayUtil.getPictureHQwidth(cCardHQ); - // } catch(IOException e2) { - // // TODO Auto-generated catch block - // e2.printStackTrace(); - // } - // int cHeight = 0; - // try { - // cHeight = GuiDisplayUtil.getPictureHQheight(cCardHQ); - // } catch(IOException e2) { - // // TODO Auto-generated catch block - // e2.printStackTrace(); - // } - // - // if(cWidth >= 312 && cHeight >= 445) { - // - // GUI_PictureHQ hq = new GUI_PictureHQ(Gui_Quest_DeckEditor.this, cCardHQ); - // try { - // hq.letsGo(Gui_Quest_DeckEditor.this, cCardHQ); - // } catch(IOException e1) { - // e1.printStackTrace(); - // } - // } - // - // } - // } - // - // } - // } - -} diff --git a/src/main/java/forge/Gui_Quest_DeckEditor_Menu.java b/src/main/java/forge/Gui_Quest_DeckEditor_Menu.java deleted file mode 100644 index 90a7c0e4551..00000000000 --- a/src/main/java/forge/Gui_Quest_DeckEditor_Menu.java +++ /dev/null @@ -1,1230 +0,0 @@ -package forge; - - -import forge.deck.Deck; -import forge.deck.DeckManager; -import forge.error.ErrorViewer; -import forge.gui.GuiUtils; -import forge.quest.data.QuestBattleManager; - -import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.filechooser.FileFilter; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.ObjectOutputStream; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - - -//presumes AllZone.getQuestData() is not null -/** - *

Gui_Quest_DeckEditor_Menu class.

- * - * @author Forge - * @version $Id$ - */ -public class Gui_Quest_DeckEditor_Menu extends JMenuBar { - /** Constant serialVersionUID=-4052319220021158574L */ - private static final long serialVersionUID = -4052319220021158574L; - - //this should be false in the public version - //if true, the Quest Deck editor will let you edit the computer's decks - private final boolean canEditComputerDecks; - - /** Constant deckEditorName="Deck Editor" */ - private static final String deckEditorName = "Deck Editor"; - - //used for import and export, try to made the gui user friendly - /** Constant previousDirectory */ - private static File previousDirectory = null; - - private Command exitCommand; - private forge.quest.data.QuestData questData; - private Deck currentDeck; - - //the class DeckDisplay is in the file "Gui_DeckEditor_Menu.java" - private DeckDisplay deckDisplay; - - - /** - *

Constructor for Gui_Quest_DeckEditor_Menu.

- * - * @param d a {@link forge.DeckDisplay} object. - * @param exit a {@link forge.Command} object. - */ - public Gui_Quest_DeckEditor_Menu(DeckDisplay d, Command exit) { - //is a file named "edit" in this directory - //lame but it works, I don't like 2 versions of MTG Forge floating around - //one that lets you edit the AI decks and one that doesn't - File f = new File("edit"); - if (f.exists()) canEditComputerDecks = true; - else canEditComputerDecks = false; - - - deckDisplay = d; - d.setTitle(deckEditorName); - - questData = AllZone.getQuestData(); - - exitCommand = exit; - - setupMenu(); - setupFilterMenu(); - - if (canEditComputerDecks) setupComputerMenu(); - } - - /** - *

setupFilterMenu.

- */ - private void setupFilterMenu() { - JMenuItem filter = new JMenuItem("New filter"); - JMenuItem clearfilter = new JMenuItem("Clear filter"); - JMenu menu = new JMenu("Filter"); - menu.add(filter); - menu.add(clearfilter); - this.add(menu); - - filter.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - Gui_Quest_DeckEditor g = (Gui_Quest_DeckEditor) deckDisplay; - if (g.stCardList == null) { - g.blackCheckBox.setSelected(true); - g.blackCheckBox.setEnabled(true); - g.blueCheckBox.setSelected(true); - g.blueCheckBox.setEnabled(true); - g.greenCheckBox.setSelected(true); - g.greenCheckBox.setEnabled(true); - g.redCheckBox.setSelected(true); - g.redCheckBox.setEnabled(true); - g.whiteCheckBox.setSelected(true); - g.whiteCheckBox.setEnabled(true); - g.colorlessCheckBox.setSelected(true); - g.colorlessCheckBox.setEnabled(true); - g.artifactCheckBox.setSelected(true); - g.artifactCheckBox.setEnabled(true); - g.creatureCheckBox.setSelected(true); - g.creatureCheckBox.setEnabled(true); - g.enchantmentCheckBox.setSelected(true); - g.enchantmentCheckBox.setEnabled(true); - g.instantCheckBox.setSelected(true); - g.instantCheckBox.setEnabled(true); - g.landCheckBox.setSelected(true); - g.landCheckBox.setEnabled(true); - g.planeswalkerCheckBox.setSelected(true); - g.planeswalkerCheckBox.setEnabled(true); - g.sorceryCheckBox.setSelected(true); - g.sorceryCheckBox.setEnabled(true); - g.stCardList = g.getTop(); - GuiQuestFilter filt = new GuiQuestFilter(g, deckDisplay); - g.setEnabled(false); - g.filterUsed = true; - filt.setVisible(true); - } else { - g.blackCheckBox.setSelected(true); - g.blackCheckBox.setEnabled(true); - g.blueCheckBox.setSelected(true); - g.blueCheckBox.setEnabled(true); - g.greenCheckBox.setSelected(true); - g.greenCheckBox.setEnabled(true); - g.redCheckBox.setSelected(true); - g.redCheckBox.setEnabled(true); - g.whiteCheckBox.setSelected(true); - g.whiteCheckBox.setEnabled(true); - g.colorlessCheckBox.setSelected(true); - g.colorlessCheckBox.setEnabled(true); - g.artifactCheckBox.setSelected(true); - g.artifactCheckBox.setEnabled(true); - g.creatureCheckBox.setSelected(true); - g.creatureCheckBox.setEnabled(true); - g.enchantmentCheckBox.setSelected(true); - g.enchantmentCheckBox.setEnabled(true); - g.instantCheckBox.setSelected(true); - g.instantCheckBox.setEnabled(true); - g.landCheckBox.setSelected(true); - g.landCheckBox.setEnabled(true); - g.planeswalkerCheckBox.setSelected(true); - g.planeswalkerCheckBox.setEnabled(true); - g.sorceryCheckBox.setSelected(true); - g.sorceryCheckBox.setEnabled(true); - GuiQuestFilter filt = new GuiQuestFilter(g, deckDisplay); - g.filterUsed = true; - g.setEnabled(false); - filt.setVisible(true); - } - } - }); - clearfilter.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - - Gui_Quest_DeckEditor g = (Gui_Quest_DeckEditor) deckDisplay; - if (g.stCardList == null) { - g.blackCheckBox.setSelected(true); - g.blackCheckBox.setEnabled(true); - g.blueCheckBox.setSelected(true); - g.blueCheckBox.setEnabled(true); - g.greenCheckBox.setSelected(true); - g.greenCheckBox.setEnabled(true); - g.redCheckBox.setSelected(true); - g.redCheckBox.setEnabled(true); - g.whiteCheckBox.setSelected(true); - g.whiteCheckBox.setEnabled(true); - g.colorlessCheckBox.setSelected(true); - g.colorlessCheckBox.setEnabled(true); - g.artifactCheckBox.setSelected(true); - g.artifactCheckBox.setEnabled(true); - g.creatureCheckBox.setSelected(true); - g.creatureCheckBox.setEnabled(true); - g.enchantmentCheckBox.setSelected(true); - g.enchantmentCheckBox.setEnabled(true); - g.instantCheckBox.setSelected(true); - g.instantCheckBox.setEnabled(true); - g.landCheckBox.setSelected(true); - g.landCheckBox.setEnabled(true); - g.planeswalkerCheckBox.setSelected(true); - g.planeswalkerCheckBox.setEnabled(true); - g.sorceryCheckBox.setSelected(true); - g.sorceryCheckBox.setEnabled(true); - g.filterUsed = false; - } else { - g.blackCheckBox.setSelected(true); - g.blackCheckBox.setEnabled(true); - g.blueCheckBox.setSelected(true); - g.blueCheckBox.setEnabled(true); - g.greenCheckBox.setSelected(true); - g.greenCheckBox.setEnabled(true); - g.redCheckBox.setSelected(true); - g.redCheckBox.setEnabled(true); - g.whiteCheckBox.setSelected(true); - g.whiteCheckBox.setEnabled(true); - g.colorlessCheckBox.setSelected(true); - g.colorlessCheckBox.setEnabled(true); - g.artifactCheckBox.setSelected(true); - g.artifactCheckBox.setEnabled(true); - g.creatureCheckBox.setSelected(true); - g.creatureCheckBox.setEnabled(true); - g.enchantmentCheckBox.setSelected(true); - g.enchantmentCheckBox.setEnabled(true); - g.instantCheckBox.setSelected(true); - g.instantCheckBox.setEnabled(true); - g.landCheckBox.setSelected(true); - g.landCheckBox.setEnabled(true); - g.planeswalkerCheckBox.setSelected(true); - g.planeswalkerCheckBox.setEnabled(true); - g.sorceryCheckBox.setSelected(true); - g.sorceryCheckBox.setEnabled(true); - g.filterUsed = false; - deckDisplay.updateDisplay(g.stCardList, deckDisplay.getBottom()); - } - - - } - }); - - } - - - /** - *

addImportExport.

- * - * @param menu a {@link javax.swing.JMenu} object. - * @param isHumanMenu a boolean. - */ - private void addImportExport(JMenu menu, final boolean isHumanMenu) { - JMenuItem import2 = new JMenuItem("Import"); - JMenuItem export = new JMenuItem("Export"); - - import2.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - importDeck();//importDeck(isHumanMenu); - } - });//import - - export.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - exportDeck(); - } - });//export - - menu.add(import2); - menu.add(export); - - }//addImportExport() - - /** - *

exportDeck.

- */ - private void exportDeck() { - File filename = getExportFilename(); - - if (filename == null) return; - - //write is an Object variable because you might just - //write one Deck object - Deck deck = convertCardListToDeck(deckDisplay.getBottom()); - ; - Object write = deck; - - deck.setName(filename.getName()); - - - try { - ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename)); - out.writeObject(write); - out.flush(); - out.close(); - } catch (Exception ex) { - ErrorViewer.showError(ex); - throw new RuntimeException("Gui_Quest_DeckEditor_Menu : exportDeck() error, " + ex); - } - - exportDeckText(getExportDeckText(deck), filename.getAbsolutePath()); - - }//exportDeck() - - // TableSorter type safety - /** - *

getExportDeckText.

- * - * @param aDeck a {@link forge.deck.Deck} object. - * @return a {@link java.lang.String} object. - */ - private String getExportDeckText(Deck aDeck) { - //convert Deck into CardList - CardList all = new CardList(); - for (int i = 0; i < aDeck.countMain(); i++) { - String cardName = aDeck.getMain(i); - Card c = AllZone.getCardFactory().getCard(cardName, null); - - all.add(c); - } - - //sort by card name - all.sort(new TableSorter(all, 1, true)); - - //remove all copies of cards - //make a singleton - CardList noCopies = new CardList(); - for (int i = 0; i < all.size(); i++) { - Card c = all.get(i); - - if (!noCopies.containsName(c.getName())) noCopies.add(c); - } - - StringBuffer sb = new StringBuffer(); - String newLine = "\r\n"; - int count = 0; - - sb.append(all.size()).append(" Total Cards").append(newLine).append(newLine); - - //creatures - sb.append(all.getType("Creature").size()).append(" Creatures").append(newLine); - sb.append("-------------").append(newLine); - - for (int i = 0; i < noCopies.size(); i++) { - Card c = noCopies.get(i); - if (c.isCreature()) { - count = all.getName(c.getName()).size(); - sb.append(count).append("x ").append(c.getName()).append(newLine); - } - } - - //count spells, arg! this is tough - CardListFilter cf = new CardListFilter() { - public boolean addCard(Card c) { - return !(c.isCreature() || c.isLand()); - } - };//CardListFilter - count = all.filter(cf).size(); - - //spells - sb.append(newLine).append(count).append(" Spells").append(newLine); - sb.append("----------").append(newLine); - - for (int i = 0; i < noCopies.size(); i++) { - Card c = noCopies.get(i); - if (!(c.isCreature() || c.isLand())) { - count = all.getName(c.getName()).size(); - sb.append(count).append("x ").append(c.getName()).append(newLine); - } - } - - //land - sb.append(newLine).append(all.getType("Land").size()).append(" Land").append(newLine); - sb.append("--------").append(newLine); - - for (int i = 0; i < noCopies.size(); i++) { - Card c = noCopies.get(i); - if (c.isLand()) { - count = all.getName(c.getName()).size(); - sb.append(count).append("x ").append(c.getName()).append(newLine); - } - } - - sb.append(newLine); - - return sb.toString(); - }//getExportDeckText - - /** - *

exportDeckText.

- * - * @param deckText a {@link java.lang.String} object. - * @param filename a {@link java.lang.String} object. - */ - private void exportDeckText(String deckText, String filename) { - - //remove ".deck" extension - int cut = filename.indexOf("."); - filename = filename.substring(0, cut); - - try { - FileWriter writer = new FileWriter(filename + ".txt"); - writer.write(deckText); - - writer.flush(); - writer.close(); - } catch (Exception ex) { - ErrorViewer.showError(ex); - throw new RuntimeException("Gui_Quest_DeckEditor_Menu : exportDeckText() error, " + ex.getMessage() - + " : " + Arrays.toString(ex.getStackTrace())); - } - }//exportDeckText() - - - /** - *

getFileFilter.

- * - * @return a {@link javax.swing.filechooser.FileFilter} object. - */ - private FileFilter getFileFilter() { - FileFilter filter = new FileFilter() { - @Override - public boolean accept(File f) { - return f.getName().endsWith(".dck") || f.isDirectory(); - } - - @Override - public String getDescription() { - return "Deck File .dck"; - } - }; - - return filter; - }//getFileFilter() - - /** - *

getExportFilename.

- * - * @return a {@link java.io.File} object. - */ - private File getExportFilename() { - //Object o = null; // unused - - JFileChooser save = new JFileChooser(previousDirectory); - - save.setDialogTitle("Export Deck Filename"); - save.setDialogType(JFileChooser.SAVE_DIALOG); - save.addChoosableFileFilter(getFileFilter()); - save.setSelectedFile(new File(currentDeck.getName() + ".deck")); - - int returnVal = save.showSaveDialog(null); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = save.getSelectedFile(); - String check = file.getAbsolutePath(); - - previousDirectory = file.getParentFile(); - - if (check.endsWith(".deck")) return file; - else return new File(check + ".deck"); - } - - return null; - }//getExportFilename() - - /** - *

importDeck.

- */ - private void importDeck() { - File file = getImportFilename(); - - if (file == null) { - } else if (file.getName().endsWith(".dck")) { - try { - Deck newDeck = DeckManager.readDeck(file); - questData.addDeck(newDeck); - - CardList cardpool = new CardList(); - CardList decklist = new CardList(); - for (String s : newDeck.getMain()) { - Card c = null; - if (s.contains("|")) { - String split[] = s.split("\\|", 2); - c = AllZone.getCardFactory().getCard(split[0], null); - decklist.add(c); - cardpool.add(c); - //setCode = s[1]; - } else { - c = AllZone.getCardFactory().getCard(s, null); - } - - decklist.add(c); - cardpool.add(c); - questData.addCard(c); - } - for (String s : questData.getCardpool()) { - cardpool.add(AllZone.getCardFactory().getCard(s, null)); - } - - deckDisplay.updateDisplay(cardpool, decklist); - - } catch (Exception ex) { - ErrorViewer.showError(ex); - throw new RuntimeException("Gui_DeckEditor_Menu : importDeck() error, " + ex); - } - } - - }//importDeck() - /* - private void importDeck(boolean isHumanDeck) { - File file = getImportFilename(); - - if(file == null) return; - - Object check = null; - - try { - ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); - check = in.readObject(); - - //deck migration - this is a little hard to read, because i can't just plainly reference a class in the - //default package - Class deckConverterClass = Class.forName("DeckConverter"); - //invoke public static Object toForgeDeck(Object o) of DeckConverter - check = deckConverterClass.getDeclaredMethod("toForgeDeck", Object.class).invoke(null, check); - - in.close(); - } catch(Exception ex) { - ErrorViewer.showError(ex); - throw new RuntimeException("Gui_Quest_DeckEditor_Menu : importDeck() error, " + ex); - } - - Deck deck = (Deck) check; - - deckDisplay.setTitle(deckEditorName + " - " + deck.getName()); - - CardList cardpool; - - if(isHumanDeck) { - questData.addDeck(deck); - - //convert ArrayList of card names (Strings), into Card objects - cardpool = new CardList(); - List list = questData.getCardpool(); - - for (String cardName : list) { - //String setCode = ""; - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - //setCode = s[1]; - } - - cardpool.add(AllZone.getCardFactory().getCard(cardName, null)); - } - } else { - QuestBattleManager.addAIDeck(deck); - cardpool = AllZone.getCardFactory().getAllCards(); - } - - //convert Deck main to CardList - CardList deckList = new CardList(); - for(int i = 0; i < deck.countMain(); i++) { - String cardName = deck.getMain(i); - //String setCode = ""; - if (cardName.contains("|")) - { - String s[] = cardName.split("\\|",2); - cardName = s[0]; - //setCode = s[1]; - } - - deckList.add(AllZone.getCardFactory().getCard(cardName, null)); - } - //update gui - deckDisplay.updateDisplay(cardpool, deckList); - - }//importDeck() - */ - - /** - *

getImportFilename.

- * - * @return a {@link java.io.File} object. - */ - private File getImportFilename() { - JFileChooser chooser = new JFileChooser(previousDirectory); - - chooser.addChoosableFileFilter(getFileFilter()); - int returnVal = chooser.showOpenDialog(null); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = chooser.getSelectedFile(); - previousDirectory = file.getParentFile(); - return file; - } - - return null; - }//openFileDialog() - - //edit the AI decks - /** - *

setupComputerMenu.

- */ - private void setupComputerMenu() { - JMenuItem open = new JMenuItem("Open"); - JMenuItem new2 = new JMenuItem("New"); - JMenuItem rename = new JMenuItem("Rename"); - JMenuItem save = new JMenuItem("Save"); - JMenuItem copy = new JMenuItem("Copy"); - JMenuItem delete = new JMenuItem("Delete"); - JMenuItem exit = new JMenuItem("Exit"); - - - JMenuItem viewAllDecks = new JMenuItem("View All Decks"); - - - //AI - viewAllDecks.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - List nameList = QuestBattleManager.getAIDeckNames(); - Collections.sort(nameList); - - Deck deck; - StringBuffer allText = new StringBuffer(); - - for (String aNameList : nameList) { - deck = QuestBattleManager.getAIDeckFromMap(aNameList); - allText.append(deck.getName()).append("\r\n"); - allText.append(getExportDeckText(deck)); - allText.append("++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n \r\n"); - } - - JTextArea area = new JTextArea(allText.toString(), 30, 30); - JOptionPane.showMessageDialog(null, new JScrollPane(area)); - - }//actionPerformed() - });//viewAllDecks - - //AI - open.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - String deckName = getUserInput_OpenDeck(QuestBattleManager.getAIDeckNames()); - - //check if user selected "cancel" - if (deckName.equals("")) return; - - - setComputerPlayer(deckName); - - Deck d = QuestBattleManager.getAIDeckFromMap(deckName); - CardList deck = new CardList(); - - for (int i = 0; i < d.countMain(); i++) { - String cardName = d.getMain(i); - //String setCode = ""; - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - //setCode = s[1]; - } - - deck.add(AllZone.getCardFactory().getCard(cardName, null)); - } - // This is an expensive heap operation. - CardList cardpool = new CardList(AllZone.getCardFactory()); - - deckDisplay.updateDisplay(cardpool, deck); - - } - });//open - - //AI - new2.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - // This is an expensive heap operation. - CardList allCards = new CardList(AllZone.getCardFactory()); - deckDisplay.updateDisplay(allCards, new CardList()); - - setComputerPlayer(""); - } - });//new - - - //AI - rename.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - String name = getUserInput_GetDeckName(QuestBattleManager.getAIDeckNames()); - - //check if user cancels - if (name.equals("")) return; - - //is the current deck already saved and in QuestData? - if (QuestBattleManager.getAIDeckNames().contains(currentDeck.getName())) - QuestBattleManager.removeAIDeck(currentDeck.getName());//remove old deck - - currentDeck.setName(name); - - Deck deck = convertCardListToDeck(deckDisplay.getBottom()); - deck.setName(name); - QuestBattleManager.addAIDeck(deck); - - setComputerPlayer(name); - } - });//rename - - - //AI - save.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - String name = currentDeck.getName(); - - //check to see if name is set - if (name.equals("")) { - name = getUserInput_GetDeckName(QuestBattleManager.getAIDeckNames()); - - //check if user cancels - if (name.equals("")) return; - } - - setComputerPlayer(name); - - Deck deck = convertCardListToDeck(deckDisplay.getBottom()); - deck.setName(name); - - QuestBattleManager.addAIDeck(deck); - } - });//save - - - //AI - copy.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - String name = getUserInput_GetDeckName(QuestBattleManager.getAIDeckNames()); - - //check if user cancels - if (name.equals("")) return; - - setComputerPlayer(name); - - Deck deck = convertCardListToDeck(deckDisplay.getBottom()); - deck.setName(name); - - QuestBattleManager.addAIDeck(deck); - } - });//copy - - - //AI - delete.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - if (currentDeck.getName().equals("")) return; - - int check = JOptionPane.showConfirmDialog(null, "Do you really want to delete this deck?", - "Delete", JOptionPane.YES_NO_OPTION); - if (check == JOptionPane.NO_OPTION) return;//stop here - - QuestBattleManager.removeAIDeck(currentDeck.getName()); - - //show card pool - - // This is an expensive heap operation. - CardList cardpool = new CardList(AllZone.getCardFactory()); - deckDisplay.updateDisplay(cardpool, new CardList()); - - setComputerPlayer(""); - } - });//delete - - - //AI - exit.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - Gui_Quest_DeckEditor_Menu.this.close(); - } - }); - - JMenu deckMenu = new JMenu("AI Deck"); - deckMenu.add(open); - deckMenu.add(rename); - deckMenu.add(new2); - deckMenu.add(save); - deckMenu.add(copy); - - deckMenu.addSeparator(); - addImportExport(deckMenu, false); - - deckMenu.add(viewAllDecks); - - deckMenu.addSeparator(); - deckMenu.add(delete); - deckMenu.addSeparator(); - deckMenu.add(exit); - - this.add(deckMenu); - - }//setupComputerMenu() - - /** - *

openHumanDeck.

- * - * @param deckName a {@link java.lang.String} object. - */ - private void openHumanDeck(String deckName) { - setHumanPlayer(deckName); - - CardList cardpool = covertToCardList(questData.getCardpool()); - - //covert Deck main to CardList - Deck d = questData.getDeck(deckName); - CardList deck = new CardList(); - - for (int i = 0; i < d.countMain(); i++) { - String cardName = d.getMain(i); - //String setCode = ""; - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - //setCode = s[1]; - cardpool.remove(s[0]); - } else { - cardpool.remove(d.getMain(i)); - } - - deck.add(AllZone.getCardFactory().getCard(cardName, null)); - - //remove any cards that are in the deck from the card pool - - } - - deckDisplay.updateDisplay(cardpool, deck); - - }//openHumanDeck - - - //the usual menu options that will be used - /** - *

setupMenu.

- */ - private void setupMenu() { - JMenuItem open = new JMenuItem("Open"); - JMenuItem new2 = new JMenuItem("New"); - JMenuItem rename = new JMenuItem("Rename"); - JMenuItem save = new JMenuItem("Save"); - JMenuItem copy = new JMenuItem("Copy"); - JMenuItem delete = new JMenuItem("Delete"); - JMenuItem exit = new JMenuItem("Exit"); - - //////////////////////////////////////////// - //below is new code - - //adds a card to human player's cardpool - JMenuItem addCard = new JMenuItem("Cheat - Add Card"); - - //add card - addCard.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - //sort cards by card name - // This is an expensive heap operation. - CardList cardList = new CardList(AllZone.getCardFactory()); - TableSorter sorter = new TableSorter(cardList, 1, true); - cardList.sort(sorter); - - //create a new Card object with a different toString() method - //so that that JList only shows the card's name - // - //this is alot of work just to make it a little - //easier and prettier for the user, gui stuff is very complicated - class BetterCard extends Card { - private Card card; - - BetterCard(Card c) { - card = c; - - //this line is very important - //if you omit this, errors will occur - this.setName(c.getName()); - } - - public String toString() { - return card.getName(); - } - }//BetterCard - - Card[] card = cardList.toArray(); - - for (int i = 0; i < card.length; i++) { - card[i] = new BetterCard(card[i]); - } - - final JList list = new JList(card); - list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - - //update the "card detail" on the right with the card info - list.addListSelectionListener(new ListSelectionListener() { - public void valueChanged(ListSelectionEvent e) { - - /* I think that the code that was based in CardDetailUtil - has been changed and moved to a new/different class? - - CardDetail cd = (CardDetail)deckDisplay; - cd.updateCardDetail((Card)list.getSelectedValue()); - - */ - - } - }); - - Object[] o = {"Add Card to Your Cardpool", new JScrollPane(list)}; - JOptionPane pane = new JOptionPane(o, JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION); - - JDialog dialog = pane.createDialog(null, "Cheat - Add Card"); - dialog.setModal(true); - dialog.setVisible(true); - - Object choice = pane.getValue(); - boolean cancel = false; - - //there are a ton of ways to cancel - if ( - choice == null || - choice.equals(JOptionPane.UNINITIALIZED_VALUE) - ) - cancel = true; - else { - int n = ((Integer) choice).intValue(); - if (n == JOptionPane.CANCEL_OPTION) - cancel = true; - } - - if (cancel || list.getSelectedValue() == null) { - //System.out.println("cancelled"); - } else { - //show the choice that the user selected - //System.out.println(list.getSelectedValue()); - - Card c = (Card) list.getSelectedValue(); - - Gui_Quest_DeckEditor g = (Gui_Quest_DeckEditor) deckDisplay; - TableModel table = g.getTopTableModel(); - table.addCard(c); - table.resort(); - } - }//actionPerformed() - });//add card - - - //above is new code - /////////////////////////////////////// - - //human - open.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - String deckName = getUserInput_OpenDeck(questData.getDeckNames()); - - //check if user selected "cancel" - if (deckName.equals("")) return; - - openHumanDeck(deckName); - } - });//open - - //human - new2.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - CardList cardpool = covertToCardList(questData.getCardpool()); - deckDisplay.updateDisplay(cardpool, new CardList()); - - setHumanPlayer(""); - } - });//new - - - //human - rename.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - String name = getUserInput_GetDeckName(questData.getDeckNames()); - - //check if user cancels - if (name.equals("")) return; - - //is the current deck already saved and in QuestData? - if (questData.getDeckNames().contains(currentDeck.getName())) - questData.removeDeck(currentDeck.getName());//remove old deck - - currentDeck.setName(name); - - Deck deck = convertCardListToDeck(deckDisplay.getBottom()); - deck.setName(name); - questData.addDeck(deck); - - setHumanPlayer(name); - } - });//rename - - - //human - save.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - String name = currentDeck.getName(); - - //check to see if name is set - if (name.equals("")) { - name = getUserInput_GetDeckName(questData.getDeckNames()); - - //check if user cancels - if (name.equals("")) return; - } - - setHumanPlayer(name); - - Deck deck = convertCardListToDeck(deckDisplay.getBottom()); - deck.setName(name); - - questData.addDeck(deck); - } - });//save - - - //human - copy.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - String name = getUserInput_GetDeckName(questData.getDeckNames()); - - //check if user cancels - if (name.equals("")) return; - - setHumanPlayer(name); - - Deck deck = convertCardListToDeck(deckDisplay.getBottom()); - deck.setName(name); - - questData.addDeck(deck); - } - });//copy - - - //human - delete.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - if (currentDeck.getName().equals("")) return; - - int check = JOptionPane.showConfirmDialog(null, "Do you really want to delete this deck?", - "Delete", JOptionPane.YES_NO_OPTION); - if (check == JOptionPane.NO_OPTION) return;//stop here - - questData.removeDeck(currentDeck.getName()); - - //show card pool - CardList cardpool = covertToCardList(questData.getCardpool()); - deckDisplay.updateDisplay(cardpool, new CardList()); - - setHumanPlayer(""); - } - });//delete - - - //human - exit.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent a) { - Gui_Quest_DeckEditor_Menu.this.close(); - } - }); - - JMenu deckMenu = new JMenu("Deck"); - deckMenu.add(open); - deckMenu.add(new2); - deckMenu.add(rename); - deckMenu.add(save); - deckMenu.add(copy); - - // The "Cheat - Add Card" menu item is buggy. - // There are other, safer and less buggy ways for people to cheat. - - // deckMenu.addSeparator();//new code - // deckMenu.add(addCard); //new code - - deckMenu.addSeparator(); - addImportExport(deckMenu, true); - - deckMenu.addSeparator(); - deckMenu.add(delete); - deckMenu.addSeparator(); - deckMenu.add(exit); - - this.add(deckMenu); - - }//setupMenu() - - /** - *

convertCardListToDeck.

- * - * @param list a {@link forge.CardList} object. - * @return a {@link forge.deck.Deck} object. - */ - private Deck convertCardListToDeck(CardList list) { - //put CardList into Deck main - Deck deck = new Deck(Constant.GameType.Sealed); - - for (int i = 0; i < list.size(); i++) - deck.addMain(list.get(i).getName()); - - return deck; - } - - //needs to be public because Gui_Quest_DeckEditor.show(Command) uses it - /** - *

setHumanPlayer.

- * - * @param deckName a {@link java.lang.String} object. - */ - public void setHumanPlayer(String deckName) { - //the gui uses this, Gui_Quest_DeckEditor - currentDeck = new Deck(Constant.GameType.Sealed); - currentDeck.setName(deckName); - - deckDisplay.setTitle(deckEditorName + " - " + deckName); - } - - /** - *

setComputerPlayer.

- * - * @param deckName a {@link java.lang.String} object. - */ - private void setComputerPlayer(String deckName) { - //the gui uses this, Gui_Quest_DeckEditor - currentDeck = new Deck(Constant.GameType.Constructed); - currentDeck.setName(deckName); - - deckDisplay.setTitle(deckEditorName + " - " + deckName); - } - - //only accepts numbers, letters or dashes up to 20 characters in length - /** - *

cleanString.

- * - * @param in a {@link java.lang.String} object. - * @return a {@link java.lang.String} object. - */ - private String cleanString(String in) { - StringBuffer out = new StringBuffer(); - char[] c = in.toCharArray(); - - for (int i = 0; i < c.length && i < 20; i++) - if (Character.isLetterOrDigit(c[i]) || c[i] == '-' || c[i] == '_' || c[i] == ' ') out.append(c[i]); - - return out.toString(); - } - - //if user cancels, returns "" - /** - *

getUserInput_GetDeckName.

- * - * @param nameList a {@link java.util.List} object. - * @return a {@link java.lang.String} object. - */ - private String getUserInput_GetDeckName(List nameList) { - Object o = JOptionPane.showInputDialog(null, "", "Deck Name", JOptionPane.OK_CANCEL_OPTION); - - if (o == null) return ""; - - String deckName = cleanString(o.toString()); - - if (nameList.contains(deckName) || deckName.equals("")) { - JOptionPane.showMessageDialog(null, "Please pick another deck name, a deck currently has that name."); - return getUserInput_GetDeckName(nameList); - } - - return deckName; - }//getUserInput_GetDeckName() - - - //if user cancels, it will return "" - /** - *

getUserInput_OpenDeck.

- * - * @param deckNameList a {@link java.util.List} object. - * @return a {@link java.lang.String} object. - */ - private String getUserInput_OpenDeck(List deckNameList) { - List choices = deckNameList; - if (choices.size() == 0) { - JOptionPane.showMessageDialog(null, "No decks found", "Open Deck", JOptionPane.PLAIN_MESSAGE); - return ""; - } - - //Object o = JOptionPane.showInputDialog(null, "Deck Name", "Open Deck", JOptionPane.OK_CANCEL_OPTION, null, - // choices.toArray(), choices.toArray()[0]); - Object o = GuiUtils.getChoiceOptional("Select Deck", choices.toArray()); - - if (o == null) return ""; - - return o.toString(); - }//getUserInput_OpenDeck() - - //used by Gui_Quest_DeckEditor - /** - *

close.

- */ - public void close() { - exitCommand.execute(); - } - - //used by Gui_Quest_DeckEditor - /** - *

getDeckName.

- * - * @return a {@link java.lang.String} object. - */ - public String getDeckName() { - return currentDeck.getName(); - } - - //used by Gui_Quest_DeckEditor - /** - *

getGameType.

- * - * @return a {@link java.lang.String} object. - */ - public String getGameType() { - return currentDeck.getDeckType(); - } - - - //returns CardList of Card objects, - //argument ArrayList holds String card names - /** - *

covertToCardList.

- * - * @param list a {@link java.util.List} object. - * @return a {@link forge.CardList} object. - */ - public static CardList covertToCardList(List list) { - CardList c = new CardList(); - Card card; - for (String aList : list) { - - card = AllZone.getCardFactory().getCard(aList, null); - c.add(card); - } - - return c; - } -} diff --git a/src/main/java/forge/Gui_WinLose.java b/src/main/java/forge/Gui_WinLose.java index 8f78b51b0f4..2d8aa42040f 100644 --- a/src/main/java/forge/Gui_WinLose.java +++ b/src/main/java/forge/Gui_WinLose.java @@ -1,5 +1,6 @@ package forge; +import forge.card.CardPrinted; import forge.error.ErrorViewer; import forge.game.GameEndReason; import forge.game.GameLossReason; @@ -301,19 +302,6 @@ public class Gui_WinLose extends JFrame implements NewConstants { return sb.toString(); } - /** - *

getCardIcon.

- * - * @param fileName a {@link java.lang.String} object. - * @return a {@link javax.swing.ImageIcon} object. - */ - private ImageIcon getCardIcon(String fileName) { - File base = ForgeProps.getFile(IMAGE_BASE); - File file = new File(base, fileName); - ImageIcon icon = new ImageIcon(file.toString()); - return icon; - } - /** *

getIcon.

* @@ -352,9 +340,8 @@ public class Gui_WinLose extends JFrame implements NewConstants { } //System.out.println("QuestData cardpoolsize:" + AllZone.getQuestData().getCardpool().size()); - if (model.quest.getShopList() != null) { - model.quest.clearShopList(); - } + model.quest.clearShopList(); + if (model.quest.getAvailableQuests() != null) { model.quest.clearAvailableQuests(); @@ -401,7 +388,7 @@ public class Gui_WinLose extends JFrame implements NewConstants { setsToGive.addAll(Arrays.asList(new String[]{"M12","NPH","MBS","M11","ROE","WWK","ZEN","M10","ARB","CFX","ALA","MOR","SHM","EVE","LRW"})); } - ArrayList cardsWon = model.quest.addCards(setsToGive); + ArrayList cardsWon = model.quest.addCards(setsToGive); ImageIcon icon = getIcon("BookIcon.png"); CardListViewer c = new CardListViewer("Booster", "You have won the following new cards", cardsWon, icon); c.show(); @@ -431,7 +418,7 @@ public class Gui_WinLose extends JFrame implements NewConstants { int wins = model.quest.getWin(); if (wins > 0 && wins % 80 == 0) // at every 80 wins, give 10 random rares { - ArrayList randomRares = model.quest.addRandomRare(10); + ArrayList randomRares = model.quest.addRandomRare(10); ImageIcon icon = getIcon("BoxIcon.png"); String title = "You just won 10 random rares!"; @@ -444,7 +431,7 @@ public class Gui_WinLose extends JFrame implements NewConstants { if (wonMatch && model.qa != null) { model.quest.addQuestsPlayed(); - ArrayList questRewardCards = model.qa.getCardRewardList(); + ArrayList questRewardCards = model.qa.getCardRewardList(); long questRewardCredits = model.qa.getCreditsReward(); StringBuilder sb = new StringBuilder(); @@ -452,13 +439,11 @@ public class Gui_WinLose extends JFrame implements NewConstants { if (questRewardCards != null) { sb.append("You won the following cards:\r\n\r\n"); - for (String cardName : questRewardCards) { - sb.append(cardName); + for (CardPrinted cardName : questRewardCards) { + sb.append(cardName.getName()); sb.append("\r\n"); - - model.quest.addCard(cardName); } - model.quest.addToNewList(questRewardCards); + model.quest.addAllCards(questRewardCards); sb.append("\r\n"); } sb.append("Quest Bounty: "); @@ -492,12 +477,16 @@ public class Gui_WinLose extends JFrame implements NewConstants { // Random rare given at 50% chance (65% with luck upgrade) if (model.quest.shouldAddAdditionalCards(wonMatch)) { - Card c = AllZone.getCardFactory().getCard(model.quest.addRandomRare(), AllZone.getHumanPlayer()); - c.setCurSetCode(c.getMostRecentSet()); - String fileName = CardUtil.buildFilename(c) + ".jpg"; - ImageIcon icon = getCardIcon(fileName); + + CardPrinted card = model.quest.addRandomRare(); + ArrayList rares = new ArrayList(); + rares.add(card); + String title = "You have won a random rare."; - JOptionPane.showMessageDialog(null, "", title, JOptionPane.INFORMATION_MESSAGE, icon); + ImageIcon icon = getIcon("BoxIcon.png"); + + CardListViewer c = new CardListViewer("Random rares", title, rares, icon); + c.show(); } } } diff --git a/src/main/java/forge/ImageCache.java b/src/main/java/forge/ImageCache.java index 67731853f6c..9804cd4dab0 100644 --- a/src/main/java/forge/ImageCache.java +++ b/src/main/java/forge/ImageCache.java @@ -6,6 +6,8 @@ import com.google.common.base.Function; import com.google.common.collect.ComputationException; import com.google.common.collect.MapMaker; import com.mortennobel.imagescaling.ResampleOp; + +import forge.card.CardPrinted; import forge.properties.ForgeProps; import forge.properties.NewConstants; @@ -139,6 +141,19 @@ public class ImageCache implements NewConstants { return getImage(key + "#" + scale); } + public static BufferedImage getImage(CardPrinted card, int width, int height) { + String key = card.getImageFilename(); + BufferedImage original = getImage(key); + if (original == null) return null; + + double scale = min((double) width / original.getWidth(), (double) height / original.getHeight()); + //here would be the place to limit the scaling, scaling option in menu ? + if (scale > 1 && !scaleLargerThanOriginal) scale = 1; + + return getImage(key + "#" + scale); + } + + /** *

getOriginalImage.

* @@ -206,70 +221,7 @@ public class ImageCache implements NewConstants { * @return a {@link java.lang.String} object. */ private static String getKey(Card card) { -/* String key = GuiDisplayUtil.cleanString(card.getImageName()); - //if(card.isBasicLand() && card.getRandomPicture() != 0) key += card.getRandomPicture(); - File path = null; - String tkn = ""; - if (card.isToken() && !card.isCopiedToken()) - { - path = ForgeProps.getFile(IMAGE_TOKEN); - tkn = TOKEN; - } - else - path = ForgeProps.getFile(IMAGE_BASE); - - File f = null; - if (!card.getCurSetCode().equals("")) - { - String nn = ""; - if (card.getRandomPicture() > 0) - nn = Integer.toString(card.getRandomPicture() + 1); - - StringBuilder sbKey = new StringBuilder(); - - //First try 3 letter set code with MWS filename format - sbKey.append(card.getCurSetCode() + "/"); - sbKey.append(GuiDisplayUtil.cleanStringMWS(card.getName()) + nn + ".full"); - - f = new File(path, sbKey.toString() + ".jpg"); - if (f.exists()) - return sbKey.toString(); - - sbKey = new StringBuilder(); - - //Second, try 2 letter set code with MWS filename format - sbKey.append(SetInfoUtil.getSetCode2_SetCode3(card.getCurSetCode()) + "/"); - sbKey.append(GuiDisplayUtil.cleanStringMWS(card.getName()) + nn + ".full"); - - f = new File(path, sbKey.toString() + ".jpg"); - if (f.exists()) - return sbKey.toString(); - - sbKey = new StringBuilder(); - - //Third, try 3 letter set code with Forge filename format - sbKey.append(card.getCurSetCode() + "/"); - sbKey.append(GuiDisplayUtil.cleanString(card.getName()) + nn); - - f = new File(path, sbKey.toString() + ".jpg"); - if (f.exists()) - return sbKey.toString(); - - //Last, give up with set images, go with the old picture type - f = new File(path, key + nn + ".jpg"); - if (f.exists()) - return key; - - //if still no file, download if option enabled - } - - int n = card.getRandomPicture(); - if (n > 0) - key += n; - - key += tkn; -// key = GuiDisplayUtil.cleanString(key); -*/ + if (card.isToken() && !card.isCopiedToken()) return GuiDisplayUtil.cleanString(card.getImageName()) + TOKEN; diff --git a/src/main/java/forge/Quest_Assignment.java b/src/main/java/forge/Quest_Assignment.java index 2a3bc2c79f4..0757dd50d86 100644 --- a/src/main/java/forge/Quest_Assignment.java +++ b/src/main/java/forge/Quest_Assignment.java @@ -2,6 +2,8 @@ package forge; import java.util.ArrayList; +import forge.card.CardPrinted; + /** *

Quest_Assignment class.

* @@ -23,7 +25,7 @@ public class Quest_Assignment { private boolean repeatable; - private ArrayList cardRewardList = new ArrayList(); + private ArrayList cardRewardList = new ArrayList(); private CardList human = new CardList(); private ArrayList compy = new ArrayList(); @@ -257,7 +259,7 @@ public class Quest_Assignment { * * @param cardRewardList a {@link java.util.ArrayList} object. */ - public void setCardRewardList(ArrayList cardRewardList) { + public void setCardRewardList(ArrayList cardRewardList) { this.cardRewardList = cardRewardList; } @@ -266,7 +268,7 @@ public class Quest_Assignment { * * @return a {@link java.util.ArrayList} object. */ - public ArrayList getCardRewardList() { + public ArrayList getCardRewardList() { return cardRewardList; } } diff --git a/src/main/java/forge/ReadBoosterPack.java b/src/main/java/forge/ReadBoosterPack.java index c1d3f8fca95..75f546c8695 100644 --- a/src/main/java/forge/ReadBoosterPack.java +++ b/src/main/java/forge/ReadBoosterPack.java @@ -5,9 +5,20 @@ package forge; //import java.io.File; //import java.io.FileReader; +import forge.card.CardRules; +import forge.card.CardDb; +import forge.card.CardRules.Predicates; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardRarity; +import forge.card.CardPrinted; import forge.properties.NewConstants; import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import net.slightlymagic.maxmtg.Predicate; /** @@ -18,72 +29,26 @@ import java.util.ArrayList; */ public class ReadBoosterPack implements NewConstants { -// final private static String comment = "//"; - - private CardList commonCreatureList = new CardList(); - private CardList commonNonCreatureList = new CardList(); - - private CardList commonList = new CardList(); - private CardList uncommonList = new CardList(); - private CardList rareList = new CardList(); - - /* - //average creature versus noncreature - - ReadBoosterPack r = new ReadBoosterPack(); - double n = 0; //total - int nCreature = 0; - int nSpell = 0; - - for(int i = 0; i < 1000; i++) - { - CardList list = r.getBoosterPack(); - - int c = list.getType("Creature").size(); - nCreature += c; - nSpell += (15 -c); - - n += 15; - } - System.out.println(nCreature / n +" - " +nSpell / n); - - System.exit(0); - */ - + + private List mythics; + private List rares; + private List uncommons; + private List commons; + + private List commonCreatures; + private List commonNonCreatures; /** *

Constructor for ReadBoosterPack.

*/ public ReadBoosterPack() { - setup(); - } + mythics = CardPrinted.Predicates.Presets.isMythicRare.select(CardDb.instance().getAllUniqueCards()); + rares = CardPrinted.Predicates.Presets.isRare.select(CardDb.instance().getAllUniqueCards()); + commons = CardPrinted.Predicates.Presets.isCommon.select(CardDb.instance().getAllUniqueCards()); + uncommons = CardPrinted.Predicates.Presets.isUncommon.select(CardDb.instance().getAllUniqueCards()); - //returns "common", "uncommon", or "rare" - /** - *

getRarity.

- * - * @param cardName a {@link java.lang.String} object. - * @return a {@link java.lang.String} object. - */ - public String getRarity(String cardName) { - if (commonList.containsName(cardName)) return "Common"; - if (uncommonList.containsName(cardName)) return "Uncommon"; - if (rareList.containsName(cardName)) return "Rare"; - - ArrayList land = new ArrayList(); - land.add("Forest"); - land.add("Plains"); - land.add("Swamp"); - land.add("Mountain"); - land.add("Island"); - land.add("Terramorphic Expanse"); - land.add("Snow-Covered Forest"); - land.add("Snow-Covered Plains"); - land.add("Snow-Covered Swamp"); - land.add("Snow-Covered Mountain"); - land.add("Snow-Covered Island"); - if (land.contains(cardName)) return "Land"; - - return "error"; + commonCreatures = new ArrayList(); + commonNonCreatures = new ArrayList(); + CardRules.Predicates.Presets.isCreature.split(commons, CardPrinted.fnGetRules, commonCreatures, commonNonCreatures); } /** @@ -91,58 +56,66 @@ public class ReadBoosterPack implements NewConstants { * * @return a {@link forge.CardList} object. */ - public CardList getBoosterPack5() { - CardList list = new CardList(); - for (int i = 0; i < 5; i++) - list.addAll(getBoosterPack()); + public CardPoolView getBoosterPack5() { + CardPool list = new CardPool(); + for (int i = 0; i < 5; i++) { list.addAll(getBoosterPack()); } - for (int i = 0; i < 20; i++) { - list.add(AllZone.getCardFactory().getCard("Forest", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Island", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Plains", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Mountain", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Swamp", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Forest", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Island", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Plains", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Mountain", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Swamp", AllZone.getHumanPlayer())); - } + addBasicLands(list, 20); + addBasicSnowLands(list, 20); for (int i = 0; i < 4; i++) - list.add(AllZone.getCardFactory().getCard("Terramorphic Expanse", AllZone.getHumanPlayer())); + list.add(CardDb.instance().getCard("Terramorphic Expanse", "M10")); return list; }//getBoosterPack5() + public static final void addBasicLands(final CardPool pool, final int count) { + for (int i = 0; i < count; i++) { + pool.add(CardDb.instance().getCard("Forest", "M10")); + pool.add(CardDb.instance().getCard("Island", "M10")); + pool.add(CardDb.instance().getCard("Plains", "M10")); + pool.add(CardDb.instance().getCard("Mountain", "M10")); + pool.add(CardDb.instance().getCard("Swamp", "M10")); + } + } + public static final void addBasicSnowLands(final CardPool pool, final int count) { + for (int i = 0; i < count; i++) { + pool.add(CardDb.instance().getCard("Snow-Covered Forest", "ICE")); + pool.add(CardDb.instance().getCard("Snow-Covered Island", "ICE")); + pool.add(CardDb.instance().getCard("Snow-Covered Plains", "ICE")); + pool.add(CardDb.instance().getCard("Snow-Covered Mountain", "ICE")); + pool.add(CardDb.instance().getCard("Snow-Covered Swamp", "ICE")); + } + } + /** *

getBoosterPack.

* * @return a {@link forge.CardList} object. */ - public CardList getBoosterPack() { - CardList pack = new CardList(); + public CardPoolView getBoosterPack() { + CardPool pack = new CardPool(); - pack.add(getRandomCard(rareList)); + pack.add(getRandomCard(rares)); for (int i = 0; i < 3; i++) - pack.add(getRandomCard(uncommonList)); + pack.add(getRandomCard(uncommons)); //11 commons, 7 creature 4 noncreature - CardList variety; + List variety; for (int i = 0; i < 7; i++) { - variety = getVariety(commonCreatureList); + variety = getVariety(commonCreatures); pack.add(getRandomCard(variety)); } for (int i = 0; i < 4; i++) { - variety = getVariety(commonNonCreatureList); + variety = getVariety(commonNonCreatures); pack.add(getRandomCard(variety)); } - if (pack.size() != 15) + if (pack.countAll() != 15) throw new RuntimeException("ReadBoosterPack : getBoosterPack() error, pack is not 15 card - " - + pack.size()); + + pack.countAll()); return pack; } @@ -154,8 +127,8 @@ public class ReadBoosterPack implements NewConstants { * @param questLevel a int. * @return a {@link forge.CardList} object. */ - public CardList getShopCards(int numberWins, int questLevel) { - CardList list = new CardList(); + public CardPoolView getShopCards(int numberWins, int questLevel) { + CardPool list = new CardPool(); // Number of Packs granted int levelPacks = questLevel > 0 ? 8 / questLevel / 2 : 4; @@ -166,30 +139,17 @@ public class ReadBoosterPack implements NewConstants { for (int i = 0; i < totalPacks; i++) { // TODO: Balance CardPool Availability // Each "Pack" yields 1 Rare, 3 Uncommon, 7 Commons - list.add(getRandomCard(rareList)); + list.add(getRandomCard(rares)); for (int j = 0; j < 7; j++) { if (j < 3) - list.add(getRandomCard(uncommonList)); + list.add(getRandomCard(uncommons)); - list.add(getRandomCard(commonList)); + list.add(getRandomCard(commons)); } } - for (int i = 0; i < 10; i++) { - // Add basic land availability - list.add(AllZone.getCardFactory().getCard("Forest", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Island", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Plains", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Mountain", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Swamp", AllZone.getHumanPlayer())); - if (i < 5) { - list.add(AllZone.getCardFactory().getCard("Snow-Covered Forest", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Island", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Plains", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Mountain", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Swamp", AllZone.getHumanPlayer())); - } - } + addBasicLands(list, 10); + addBasicSnowLands(list, 5); return list; } @@ -201,16 +161,13 @@ public class ReadBoosterPack implements NewConstants { * @param in a {@link forge.CardList} object. * @return a {@link forge.CardList} object. */ - private CardList getVariety(CardList in) { - CardList out = new CardList(); + private List getVariety(List in) { + List out = new ArrayList(); + Collections.shuffle(in, MyRandom.random); - String color[] = Constant.Color.Colors; - Card check; - in.shuffle(); - - for (int i = 0; i < color.length; i++) { - check = findColor(in, color[i]); - if (check != null) out.add(check); + for (int i = 0; i < Constant.Color.Colors.length; i++) { + CardPrinted check = findColor(in, i); + if (check != null) { out.add(check); } } return out; @@ -223,11 +180,19 @@ public class ReadBoosterPack implements NewConstants { * @param color a {@link java.lang.String} object. * @return a {@link forge.Card} object. */ - private Card findColor(CardList in, String color) { - for (int i = 0; i < in.size(); i++) - if (CardUtil.getColors(in.get(i)).contains(color)) return in.get(i); - - return null; + private CardPrinted findColor(final List in, final int color) { + Predicate filter = null; + switch (color) { + case 0: filter = CardRules.Predicates.Presets.isWhite; break; + case 1: filter = CardRules.Predicates.Presets.isBlue; break; + case 2: filter = CardRules.Predicates.Presets.isBlack; break; + case 3: filter = CardRules.Predicates.Presets.isRed; break; + case 4: filter = CardRules.Predicates.Presets.isGreen; break; + case 5: filter = CardRules.Predicates.Presets.isColorless; break; + default: break; + } + if (null == filter) { return null; } + return filter.first(in, CardPrinted.fnGetRules); } @@ -237,236 +202,12 @@ public class ReadBoosterPack implements NewConstants { * @param list a {@link forge.CardList} object. * @return a {@link forge.Card} object. */ - private Card getRandomCard(CardList list) { + private CardPrinted getRandomCard(List list) { for (int i = 0; i < 10; i++) - list.shuffle(); - + Collections.shuffle(list, MyRandom.random); int index = MyRandom.random.nextInt(list.size()); - - Card c = AllZone.getCardFactory().copyCard(list.get(index)); - c.setRarity("rare"); - return c; + return list.get(index); }//getRandomCard() - /** - *

setup.

- */ - private void setup() { - //commonList = readFile(ForgeProps.getFile(REGULAR.COMMON)); - //uncommonList = readFile(ForgeProps.getFile(REGULAR.UNCOMMON)); - //rareList = readFile(ForgeProps.getFile(REGULAR.RARE)); - - //commonCreatureList = commonList.getType("Creature"); - //commonNonCreatureList = commonList.filter(new CardListFilter() { - // public boolean addCard(Card c) { - // return !c.isCreature(); - // } - //}); - - for (Card aCard : AllZone.getCardFactory()) { - String rr = aCard.getSVar("Rarity"); - - if (rr.equals("Common")) { - commonList.add(aCard); - if (aCard.isCreature()) - commonCreatureList.add(aCard); - else - commonNonCreatureList.add(aCard); - } else if (rr.equals("Uncommon")) { - uncommonList.add(aCard); - } else if (rr.equals("Rare")) { - rareList.add(aCard); - } else if (rr.equals("Mythic")) { - rareList.add(aCard); - } - - } - - }//setup() - - -/* private CardList readFile(File file) { - CardList cardList = new CardList(); - - BufferedReader in; - try { - in = new BufferedReader(new FileReader(file)); - String line = in.readLine(); - - //stop reading if end of file or blank line is read - while(line != null && (line.trim().length() != 0)) { - Card c; - if(!line.startsWith(comment)) { - c = AllZone.getCardFactory().getCard(line.trim(), AllZone.getHumanPlayer()); - cardList.add(c); - } - - line = in.readLine(); - }//if - - } catch(Exception ex) { - ErrorViewer.showError(ex); - throw new RuntimeException("ReadBoosterPack : readFile error, " + ex); - } - - return cardList; - }//readFile() -*/ } -/* -import java.util.*; -import java.io.*; - -public class ReadBoosterPack -{ -// final private String commonFilename = Constant.IO.baseDir +"data/common.txt"; -// final private String uncommonFilename = Constant.IO.baseDir +"data/uncommon.txt"; -// final private String rareFilename = Constant.IO.baseDir +"data/rare.txt"; - - final private String commonFilename = "common.txt"; - final private String uncommonFilename = "uncommon.txt"; - final private String rareFilename = "rare.txt"; - - final private String comment = "//"; - - private ArrayList commonList; - private ArrayList uncommonList; - private ArrayList rareList; - - - public static void main(String[] args) - { - ReadBoosterPack r = new ReadBoosterPack(); - CardList list = r.getBoosterPack(); - double n = 0; //total - int nCreature = 0; - int nSpell = 0; - - for(int i = 0; i < 2; i++) - { - int c = list.getType("Creature").size(); - nCreature += c; - nSpell += (15 -c); - - n += 15; - } - System.out.println(nCreature / n +" - " +nSpell / n); - - System.exit(0); - }//main() - - public ReadBoosterPack() {setup();} - - //returns "common", "uncommon", or "rare" - public String getRarity(String cardName) - { - if(commonList.contains(cardName)) - return "Common"; - if(uncommonList.contains(cardName)) - return "Uncommon"; - if(rareList.contains(cardName)) - return "Rare"; - - ArrayList land = new ArrayList(); - land.add("Forest"); - land.add("Plains"); - land.add("Swamp"); - land.add("Mountain"); - land.add("Island"); - land.add("Terramorphic Expanse"); - if(land.contains(cardName)) - return "Land"; - - return "error"; - } - - public CardList getBoosterPack5() - { - CardList list = new CardList(); - for(int i = 0; i < 5; i++) - list.addAll(getBoosterPack()); - - for(int i = 0; i < 40; i++) - { - list.add(AllZone.getCardFactory().getCard("Forest", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Island", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Plains", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Mountain", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Swamp", AllZone.getHumanPlayer())); - } - - for(int i = 0; i < 4; i++) - list.add(AllZone.getCardFactory().getCard("Terramorphic Expanse", AllZone.getHumanPlayer())); - - return list; - }//getBoosterPack5() - - public CardList getBoosterPack() - { - CardList pack = new CardList(); - - pack.add(getRandomCard(rareList)); - - for(int i = 0; i < 3; i++) - pack.add(getRandomCard(uncommonList)); - - for(int i = 0; i < 11; i++) - pack.add(getRandomCard(commonList)); - - return pack; - } - private Card getRandomCard(ArrayList list) - { - for(int i = 0; i < 10; i++) - Collections.shuffle(list, MyRandom.random); - - int index = MyRandom.random.nextInt(list.size()); - String name = list.get(index).toString(); - - Card c = AllZone.getCardFactory().getCard(name, AllZone.getHumanPlayer()); - c.setRarity("rare"); - return c; - }//getRandomCard() - - private void setup() - { - commonList = readFile(commonFilename); - uncommonList = readFile(uncommonFilename); - rareList = readFile(rareFilename); - - checkName(commonList); - checkName(uncommonList); - checkName(rareList); - } - private void checkName(ArrayList name) - { - for(int i = 0; i < name.size(); i++) - AllZone.getCardFactory().getCard(name.get(i).toString(), AllZone.getHumanPlayer()); - } - - //returns an ArrayList of Strings, the names of the cards read - private ArrayList readFile(String filename) - { - ArrayList cardName = new ArrayList(); - - BufferedReader in; - try{ - in = new BufferedReader(new FileReader(filename)); - String line = in.readLine(); - - //stop reading if end of file or blank line is read - while(line != null && (line.trim().length() != 0)) - { - if(! line.startsWith(comment)) - cardName.add(line.trim()); - - line = in.readLine(); - }//if - - }catch(Exception ex){throw new RuntimeException("ReadBoosterPack : readFile error, " + ex);} - - return cardName; - }//readFile() -} -*/ diff --git a/src/main/java/forge/ReadDraftBoosterPack.java b/src/main/java/forge/ReadDraftBoosterPack.java index 43e6de19ed1..162179d2458 100644 --- a/src/main/java/forge/ReadDraftBoosterPack.java +++ b/src/main/java/forge/ReadDraftBoosterPack.java @@ -1,6 +1,12 @@ package forge; +import forge.card.CardRules; +import forge.card.CardRules.Predicates; +import forge.card.CardDb; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; import forge.error.ErrorViewer; import forge.properties.ForgeProps; import forge.properties.NewConstants; @@ -9,6 +15,10 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import net.slightlymagic.maxmtg.Predicate; /** @@ -22,12 +32,12 @@ public class ReadDraftBoosterPack implements NewConstants { /** Constant comment="//" */ final private static String comment = "//"; - private CardList commonCreatureList = new CardList(); - private CardList commonNonCreatureList = new CardList(); + private List commonCreatureList = new ArrayList(); + private List commonNonCreatureList = new ArrayList(); - private CardList commonList = new CardList(); - private CardList uncommonList = new CardList(); - private CardList rareList = new CardList(); + private List commonList = new ArrayList(); + private List uncommonList = new ArrayList(); + private List rareList = new ArrayList(); /** *

Constructor for ReadDraftBoosterPack.

@@ -36,71 +46,43 @@ public class ReadDraftBoosterPack implements NewConstants { setup(); } - //returns "common", "uncommon", or "rare" - /** - *

getRarity.

- * - * @param cardName a {@link java.lang.String} object. - * @return a {@link java.lang.String} object. - */ - public String getRarity(String cardName) { - if (commonList.containsName(cardName)) return "Common"; - if (uncommonList.containsName(cardName)) return "Uncommon"; - if (rareList.containsName(cardName)) return "Rare"; + public CardPoolView getBoosterPack5() { + CardPool list = new CardPool(); + for (int i = 0; i < 5; i++) { list.addAll(getBoosterPack()); } - ArrayList land = new ArrayList(); - land.add("Forest"); - land.add("Plains"); - land.add("Swamp"); - land.add("Mountain"); - land.add("Island"); - land.add("Terramorphic Expanse"); - land.add("Snow-Covered Forest"); - land.add("Snow-Covered Plains"); - land.add("Snow-Covered Swamp"); - land.add("Snow-Covered Mountain"); - land.add("Snow-Covered Island"); - if (land.contains(cardName)) return "Land"; - - return "error"; - } - - /** - *

getBoosterPack5.

- * - * @return a {@link forge.CardList} object. - */ - public CardList getBoosterPack5() { - CardList list = new CardList(); - for (int i = 0; i < 5; i++) - list.addAll(getBoosterPack()); - - for (int i = 0; i < 20; i++) { - list.add(AllZone.getCardFactory().getCard("Forest", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Island", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Plains", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Mountain", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Swamp", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Forest", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Island", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Plains", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Mountain", AllZone.getHumanPlayer())); - list.add(AllZone.getCardFactory().getCard("Snow-Covered Swamp", AllZone.getHumanPlayer())); - } + addBasicLands(list, 20); + addBasicSnowLands(list, 20); for (int i = 0; i < 4; i++) - list.add(AllZone.getCardFactory().getCard("Terramorphic Expanse", AllZone.getHumanPlayer())); + list.add(CardDb.instance().getCard("Terramorphic Expanse", "M10")); return list; }//getBoosterPack5() + public static final void addBasicLands(final CardPool pool, final int count) { + CardDb db = CardDb.instance(); + pool.add(db.getCard("Forest", "M10"), count); + pool.add(db.getCard("Island", "M10"), count); + pool.add(db.getCard("Plains", "M10"), count); + pool.add(db.getCard("Mountain", "M10"), count); + pool.add(db.getCard("Swamp", "M10"), count); + + } + public static final void addBasicSnowLands(final CardPool pool, final int count) { + CardDb db = CardDb.instance(); + pool.add(db.getCard("Snow-Covered Forest", "ICE"), count); + pool.add(db.getCard("Snow-Covered Island", "ICE"), count); + pool.add(db.getCard("Snow-Covered Plains", "ICE"), count); + pool.add(db.getCard("Snow-Covered Mountain", "ICE"), count); + pool.add(db.getCard("Snow-Covered Swamp", "ICE"), count); + } /** *

getBoosterPack.

* * @return a {@link forge.CardList} object. */ - public CardList getBoosterPack() { - CardList pack = new CardList(); + public CardPoolView getBoosterPack() { + CardPool pack = new CardPool(); pack.add(getRandomCard(rareList)); @@ -108,7 +90,7 @@ public class ReadDraftBoosterPack implements NewConstants { pack.add(getRandomCard(uncommonList)); //11 commons, 7 creature 4 noncreature - CardList variety; + List variety; for (int i = 0; i < 7; i++) { variety = getVariety(commonCreatureList); pack.add(getRandomCard(variety)); @@ -119,159 +101,72 @@ public class ReadDraftBoosterPack implements NewConstants { pack.add(getRandomCard(variety)); } - if (pack.size() != 15) + if (pack.countAll() != 15) throw new RuntimeException("ReadDraftBoosterPack : getBoosterPack() error, pack is not 15 cards - " - + pack.size()); + + pack.countAll()); return pack; } - /** - *

getShopCards.

- * - * @param numberWins a int. - * @return a {@link forge.CardList} object. - */ - public CardList getShopCards(int numberWins) { - CardList list = new CardList(); - - int numberRares = 1 + numberWins / 15; - if (numberRares > 10) - numberRares = 10; - - for (int i = 0; i < numberRares; i++) - list.add(getRandomCard(rareList)); - - int numberUncommons = 3 + numberWins / 10; - if (numberUncommons > 20) - numberUncommons = 20; - - for (int i = 0; i < numberUncommons; i++) - list.add(getRandomCard(uncommonList)); - - int numberCommons = 5 + numberWins / 5; - if (numberCommons > 35) - numberCommons = 35; - - for (int i = 0; i < numberCommons; i++) - list.add(getRandomCard(commonList)); - - return list; - } - //return CardList of 5 or 6 cards, one for each color and maybe an artifact - /** - *

getVariety.

- * - * @param in a {@link forge.CardList} object. - * @return a {@link forge.CardList} object. - */ - private CardList getVariety(CardList in) { - CardList out = new CardList(); + private List getVariety(List in) { + List out = new ArrayList(); + Collections.shuffle(in, MyRandom.random); - String color[] = Constant.Color.Colors; - Card check; - in.shuffle(); - - for (int i = 0; i < color.length; i++) { - check = findColor(in, color[i]); - if (check != null) out.add(check); + for (int i = 0; i < Constant.Color.Colors.length; i++) { + CardPrinted check = findColor(in, i); + if (check != null) { out.add(check); } } return out; }//getVariety() - /** - *

findColor.

- * - * @param in a {@link forge.CardList} object. - * @param color a {@link java.lang.String} object. - * @return a {@link forge.Card} object. - */ - private Card findColor(CardList in, String color) { - for (int i = 0; i < in.size(); i++) - if (CardUtil.getColors(in.get(i)).contains(color)) return in.get(i); - - return null; + private static CardPrinted findColor(final List in, final int color) { + Predicate filter = null; + switch (color) { + case 0: filter = CardRules.Predicates.Presets.isWhite; break; + case 1: filter = CardRules.Predicates.Presets.isBlue; break; + case 2: filter = CardRules.Predicates.Presets.isBlack; break; + case 3: filter = CardRules.Predicates.Presets.isRed; break; + case 4: filter = CardRules.Predicates.Presets.isGreen; break; + case 5: filter = CardRules.Predicates.Presets.isColorless; break; + default: break; + } + if (null == filter) { return null; } + return filter.first(in, CardPrinted.fnGetRules); } - /** - *

getRandomCard.

- * - * @param list a {@link forge.CardList} object. - * @return a {@link forge.Card} object. - */ - private Card getRandomCard(CardList list) { - for (int i = 0; i < 10; i++) - list.shuffle(); + private static CardPrinted getRandomCard(final List list) { + for (int i = 0; i < 10; i++) { + Collections.shuffle(list, MyRandom.random); + } int index = MyRandom.random.nextInt(list.size()); - - Card c = AllZone.getCardFactory().copyCard(list.get(index)); - c.setRarity("rare"); - return c; + return list.get(index); }//getRandomCard() + /** *

setup.

*/ private void setup() { - commonList = readFile(ForgeProps.getFile(DRAFT.COMMON)); - uncommonList = readFile(ForgeProps.getFile(DRAFT.UNCOMMON)); - rareList = readFile(ForgeProps.getFile(DRAFT.RARE)); + CardDb db = CardDb.instance(); + commonList = db.getCards(readFile(ForgeProps.getFile(DRAFT.COMMON))); + uncommonList = db.getCards(readFile(ForgeProps.getFile(DRAFT.UNCOMMON))); + rareList = db.getCards(readFile(ForgeProps.getFile(DRAFT.RARE))); System.out.println("commonList size:" + commonList.size()); System.out.println("ucommonList size:" + uncommonList.size()); System.out.println("rareList size:" + rareList.size()); - commonCreatureList = commonList.getType("Creature"); - commonNonCreatureList = commonList.filter(new CardListFilter() { - public boolean addCard(Card c) { - return !c.isCreature(); - } - }); + CardRules.Predicates.Presets.isCreature.split(commonList, CardPrinted.fnGetRules, + commonCreatureList, commonNonCreatureList); -/* CardList AllCards = AllZone.getCardFactory().getAllCards(); - -for (int i=0; ireadFile.

- * - * @param file a {@link java.io.File} object. - * @return a {@link forge.CardList} object. - */ - private CardList readFile(File file) { - CardList cardList = new CardList(); + private List readFile(final File file) { + List cardList = new ArrayList(); BufferedReader in; try { @@ -280,14 +175,12 @@ for (int i=0; icomment="//" */ final private static String comment = "//"; - private HashMap priceMap; + private HashMap priceMap; /** *

Constructor for ReadPriceList.

@@ -47,9 +47,9 @@ public class ReadPriceList implements NewConstants { * @param file a {@link java.io.File} object. * @return a {@link java.util.HashMap} object. */ - private HashMap readFile(File file) { + private HashMap readFile(File file) { BufferedReader in; - HashMap map = new HashMap(); + HashMap map = new HashMap(); Random r = MyRandom.random; try { @@ -66,7 +66,7 @@ public class ReadPriceList implements NewConstants { //System.out.println("Name: " + name + ", Price: " + price); try { - long val = Long.parseLong(price.trim()); + int val = Integer.parseInt(price.trim()); if (!(name.equals("Plains") || name.equals("Island") || name.equals("Swamp") || name.equals("Mountain") || name.equals("Forest") || name.equals("Snow-Covered Plains") || name.equals("Snow-Covered Island") || name.equals("Snow-Covered Swamp") || name.equals("Snow-Covered Mountain") || name.equals("Snow-Covered Forest"))) { @@ -77,9 +77,9 @@ public class ReadPriceList implements NewConstants { ff = (float) r.nextInt(50) * (float) .01; if (r.nextInt(100) < 50) // -ff% - val = (long) ((float) val * ((float) 1 - ff)); + val = (int) ((float) val * ((float) 1 - ff)); else // +ff% - val = (long) ((float) val * ((float) 1 + ff)); + val = (int) ((float) val * ((float) 1 + ff)); } map.put(name, val); @@ -103,7 +103,7 @@ public class ReadPriceList implements NewConstants { * * @return a {@link java.util.Map} object. */ - public Map getPriceList() { + public Map getPriceList() { return priceMap; } } diff --git a/src/main/java/forge/SealedDeck.java b/src/main/java/forge/SealedDeck.java index 33b133417e2..89fa6c950db 100644 --- a/src/main/java/forge/SealedDeck.java +++ b/src/main/java/forge/SealedDeck.java @@ -1,5 +1,6 @@ package forge; +import forge.card.CardPool; import forge.card.spellability.Ability_Mana; import forge.deck.Deck; import forge.gui.GuiUtils; @@ -169,11 +170,11 @@ public class SealedDeck { * * @return a {@link forge.CardList} object. */ - public CardList getCardpool() { - CardList pool = new CardList(); + public CardPool getCardpool() { + CardPool pool = new CardPool(); for (int i = 0; i < packs.size(); i++) - pool.addAll(packs.get(i).getBoosterPack()); + pool.addAllCards(packs.get(i).getBoosterPack()); return pool; } diff --git a/src/main/java/forge/TableModel.java b/src/main/java/forge/TableModel.java deleted file mode 100644 index 96186c668f1..00000000000 --- a/src/main/java/forge/TableModel.java +++ /dev/null @@ -1,442 +0,0 @@ -package forge; - - -import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; -import java.awt.event.*; -import java.util.Arrays; - - -/** - *

TableModel class.

- * - * @author Forge - * @version $Id$ - */ -class TableModel extends AbstractTableModel { - /** - * - */ - private static final long serialVersionUID = 1L; - - //holds 1 copy of each card, DOES NOT HOLD multiple cards with the same name - private CardList dataNoCopies = new CardList(); - - //holds multiple card - //example: if there are 4 Elvish Pipers, dataNoCopies has 1 copy, and dataCopies has 3 - private CardList dataCopies = new CardList(); - - //used by sort(), holds old data to compare with sorted data, to see if any change was made - //private CardList oldList = new CardList(); - - private CardContainer cardDetail; - //private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "R", "AI"}; - private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "R", "Set", "AI"}; - - //used to resort(), used when addCard(Card) is called - private int recentSortedColumn; - private boolean recentAscending; - - /** - *

Constructor for TableModel.

- * - * @param cd a {@link forge.CardContainer} object. - */ - public TableModel(CardContainer cd) { - this(new CardList(), cd); - } - - /** - *

Constructor for TableModel.

- * - * @param inData a {@link forge.CardList} object. - * @param in_cardDetail a {@link forge.CardContainer} object. - */ - public TableModel(CardList inData, CardContainer in_cardDetail) { - cardDetail = in_cardDetail; - //intialize dataNoCopies and dataCopies - addCard(inData); - } - - - /** - *

resizeCols.

- * - * @param table a {@link javax.swing.JTable} object. - */ - public void resizeCols(final JTable table) { - TableColumn column = null; - for (int i = 0; i < table.getColumnCount(); i++) { - column = table.getColumnModel().getColumn(i); - - if (i == 0) { - column.setPreferredWidth(35); // Qty - column.setMaxWidth(35); - column.setMinWidth(35); - } else if (i == 1) { - column.setPreferredWidth(190); // Name - column.setMinWidth(170); - column.setMaxWidth(200); - } else if (i == 2) { - column.setPreferredWidth(80); // Cost - column.setMinWidth(70); - column.setMaxWidth(90); - } else if (i == 3) { - column.setPreferredWidth(70); // Color - column.setMaxWidth(70); - column.setMinWidth(70); - } else if (i == 4) { - column.setPreferredWidth(130); // Type - } else if (i == 5) { - column.setPreferredWidth(50); // Stats - column.setMaxWidth(50); - column.setMinWidth(50); - } else if (i == 6) { - column.setPreferredWidth(25); // R - column.setMaxWidth(25); - column.setMinWidth(25); - } else if (i == 7) { - column.setPreferredWidth(45); // Set - column.setMaxWidth(45); - column.setMinWidth(45); - } else if (i == 8) { - column.setPreferredWidth(30); // AI - column.setMaxWidth(30); - column.setMinWidth(30); - } - }//for - - /*for(int j = 0; j < table.getColumnCount(); j++) { - column = table.getColumnModel().getColumn(j); - //System.out.println("col Width:" + column.getPreferredWidth()); - }*/ - } - - /** - *

clear.

- */ - public void clear() { - dataNoCopies.clear(); - dataCopies.clear(); - //fireTableDataChanged(); - } - - /** - *

getCards.

- * - * @return a {@link forge.CardList} object. - */ - public CardList getCards() { - CardList all = new CardList(); - all.addAll(dataCopies); - all.addAll(dataNoCopies); - - return all; - } - - /** - *

removeCard.

- * - * @param c a {@link forge.Card} object. - */ - public void removeCard(Card c) { - //remove card from "dataCopies", - //if not found there, remove card from "dataNoCopies" - int index = findCardName(c.getName(), dataCopies); - - if (index != -1) //found card name - dataCopies.remove(index); - else { - index = findCardName(c.getName(), dataNoCopies); - dataNoCopies.remove(index); - } - - fireTableDataChanged(); - } - - /** - *

findCardName.

- * - * @param name a {@link java.lang.String} object. - * @param list a {@link forge.CardList} object. - * @return a int. - */ - private int findCardName(String name, CardList list) { - for (int i = 0; i < list.size(); i++) - if (list.get(i).getName().equals(name)) return i; - - return -1; - } - - /** - *

addCard.

- * - * @param c a {@link forge.Card} object. - */ - public void addCard(Card c) { - if (0 == countQuantity(c, dataNoCopies)) dataNoCopies.add(c); - else dataCopies.add(c); - } - - /** - *

addCard.

- * - * @param c a {@link forge.CardList} object. - */ - public void addCard(CardList c) { - for (int i = 0; i < c.size(); i++) - addCard(c.get(i)); - - fireTableDataChanged(); - } - - /** - *

rowToCard.

- * - * @param row a int. - * @return a {@link forge.Card} object. - */ - public Card rowToCard(int row) { - return dataNoCopies.get(row); - } - - /** - *

countQuantity.

- * - * @param c a {@link forge.Card} object. - * @return a int. - */ - private int countQuantity(Card c) { - return countQuantity(c, dataNoCopies) + countQuantity(c, dataCopies); - } - - //CardList data is either class members "dataNoCopies" or "dataCopies" - /** - *

countQuantity.

- * - * @param c a {@link forge.Card} object. - * @param data a {@link forge.CardList} object. - * @return a int. - */ - private int countQuantity(Card c, CardList data) { - int count = 0; - for (int i = 0; i < data.size(); i++) { - //are the card names and set code the same? - Card dc = data.get(i); - if (dc.getName().equals(c.getName()) && - dc.getCurSetCode().equals(c.getCurSetCode())) count++; - } - - return count; - } - - /** - *

getRowCount.

- * - * @return a int. - */ - public int getRowCount() { - return dataNoCopies.size(); - } - - /** - *

getColumnCount.

- * - * @return a int. - */ - public int getColumnCount() { - return column.length; - } - - /** {@inheritDoc} */ - @Override - public String getColumnName(int n) { - return column[n]; - } - - /** {@inheritDoc} */ - public Object getValueAt(int row, int column) { - return getColumn(dataNoCopies.get(row), column); - } - - /** - *

Getter for the field column.

- * - * @param c a {@link forge.Card} object. - * @param column a int. - * @param column a int. - * @return a {@link java.lang.Object} object. - */ - private Object getColumn(Card c, int column) { - switch (column) { - case 0: - return Integer.valueOf(countQuantity(c)); - case 1: - return c.getName(); - case 2: - return c.getManaCost(); - case 3: - return TableSorter.getColor(c); - case 4: - return GuiDisplayUtil.formatCardType(c); - case 5: - //return c.isCreature()? c.getBaseAttackString() + "/" + c.getBaseDefenseString():""; - if (c.isCreature()) { - return c.getBaseAttackString() + "/" + c.getBaseDefenseString(); - } else if (c.isPlaneswalker()) { - return Integer.toString(c.getBaseLoyalty()); - } - return ""; - case 6: - String rarity = c.getRarity(); - - if (rarity.equals("new")) - return "n"; - else { - if (rarity.length() > 0) - rarity = rarity.substring(0, 1); - } - - if (!c.getCurSetCode().equals("")) { - SetInfo si = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()); - if (si != null) - return si.Rarity.substring(0, 1); - } - return rarity; - case 7: - String SC = c.getCurSetCode(); - if (!SC.equals("")) - return SC; - case 8: - if (c.getSVar("RemAIDeck").equals("True") - && c.getSVar("RemRandomDeck").equals("True")) - return "No ?"; - else if (c.getSVar("RemAIDeck").equals("True")) - return "No"; - else if (c.getSVar("RemRandomDeck").equals("True")) - return "?"; - else - return ""; - - default: - return "error"; - } - } - - /** - *

addListeners.

- * - * @param table a {@link javax.swing.JTable} object. - */ - public void addListeners(final JTable table) { - //updates card detail, listens to any key strokes - table.getSelectionModel().addListSelectionListener( new ListSelectionListener() { - - @Override - public void valueChanged(ListSelectionEvent arg0) { - int row = table.getSelectedRow(); - if (row != -1) { - cardDetail.setCard(dataNoCopies.get(row)); - } - } - - }); - - //sorts - MouseListener mouse = new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - TableColumnModel columnModel = table.getColumnModel(); - int viewColumn = columnModel.getColumnIndexAtX(e.getX()); - int column = table.convertColumnIndexToModel(viewColumn); - - - if (column != -1) { - //sort ascending - @SuppressWarnings("unused") - boolean change = sort(column, true); - - //if(! change) - // sort(column, false);//sort descending - - //fireTableDataChanged(); - } - }//mousePressed() - };//MouseListener - table.getTableHeader().addMouseListener(mouse); - }//addCardListener() - - //called by the GUI when a card is added to re-sort - /** - *

resort.

- */ - public void resort() { - sort(recentSortedColumn, recentAscending); - //this.fireTableDataChanged(); - } - - //returns true if any data changed positions - // @SuppressWarnings("unchecked") - // Arrays.sort - /** - *

sort.

- * - * @param column a int. - * @param ascending a boolean. - * @return a boolean. - */ - public boolean sort(int column, boolean ascending) { - //used by addCard() to resort the cards - recentSortedColumn = column; - recentAscending = ascending; - - CardList all = new CardList(); - all.addAll(dataNoCopies); - all.addAll(dataCopies); - - TableSorter sorter = new TableSorter(all, column, ascending, true); - Card[] array = all.toArray(); - Arrays.sort(array, sorter); - - /* - //determine if any data changed position - boolean hasChanged = false; - CardList check = removeDuplicateNames(array); - for(int i = 0; i < check.size(); i++) - //do the card names match? - if(! check.get(i).getName().equals(dataNoCopies.get(i).getName())) - hasChanged = true; - */ - - //clear everything, and add sorted data back into the model - dataNoCopies.clear(); - dataCopies.clear(); - addCard(new CardList(array)); - - //this value doesn't seem to matter: - //return hasChanged; - return true; - }//sort() - /* - private CardList removeDuplicateNames(Card[] c) - { - TreeSet check = new TreeSet(); - CardList list = new CardList(); - - for(int i = 0; i < c.length; i++) - { - if(! check.contains(c[i].getName())) - { - check.add(c[i].getName()); - list.add(c[i]); - } - } - - return list; - } - */ -}//CardTableModel diff --git a/src/main/java/forge/TableSorter.java b/src/main/java/forge/TableSorter.java deleted file mode 100644 index 20ef64d58c9..00000000000 --- a/src/main/java/forge/TableSorter.java +++ /dev/null @@ -1,258 +0,0 @@ -package forge; - - -import forge.properties.NewConstants; - -import java.util.ArrayList; -import java.util.Comparator; - -/** - *

TableSorter class.

- * - * @author Forge - * @version $Id$ - */ -@SuppressWarnings("unchecked") // Comparable needs -public class TableSorter implements Comparator, NewConstants { - private final int column; - private boolean ascending; - private boolean col7mod; - - private CardList all; - - //used by compare() - @SuppressWarnings("rawtypes") - private Comparable aCom = null; - @SuppressWarnings("rawtypes") - private Comparable bCom = null; - - //used if in_column is 7, new cards first - the order is based on cards.txt - //static because this should only be read once - //static to try to reduce file io operations - //private static HashMap cardsTxt = null; - - // 0 1 2 3 4 5 6 7 - //private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "Rarity"}; New cards first - the order is based on cards.txt - - /** - *

Constructor for TableSorter.

- * - * @param in_all a {@link forge.CardList} object. - * @param in_column a int. - * @param in_ascending a boolean. - */ - public TableSorter(CardList in_all, int in_column, boolean in_ascending) { - all = new CardList(in_all.toArray()); - column = in_column; - ascending = in_ascending; - } - - /** - *

Constructor for TableSorter.

- * - * @param in_all a {@link forge.CardList} object. - * @param in_column a int. - * @param in_ascending a boolean. - * @param in_col7mod a boolean. - */ - public TableSorter(CardList in_all, int in_column, boolean in_ascending, boolean in_col7mod) { - all = new CardList(in_all.toArray()); - column = in_column; - ascending = in_ascending; - col7mod = in_col7mod; - } - - /** - *

compare.

- * - * @param a a {@link forge.Card} object. - * @param b a {@link forge.Card} object. - * @return a int. - */ - final public int compare(Card a, Card b) { - - if (column == 0)//Qty - { - aCom = Integer.valueOf(countCardName(a.getName(), all)); - bCom = Integer.valueOf(countCardName(b.getName(), all)); - } else if (column == 1)//Name - { - aCom = a.getName(); - bCom = b.getName(); - } else if (column == 2)//Cost - { - aCom = Double.valueOf(CardUtil.getWeightedManaCost(a.getManaCost())); - bCom = Double.valueOf(CardUtil.getWeightedManaCost(b.getManaCost())); - - if (a.isLand()) - aCom = Double.valueOf(-1); - if (b.isLand()) - bCom = Double.valueOf(-1); - } else if (column == 3)//Color - { - aCom = getColor(a); - bCom = getColor(b); - } else if (column == 4)//Type - { - aCom = getType(a); - bCom = getType(b); - } else if (column == 5)//Stats, attack and defense - { - if (a.isCreature()) { - aCom = a.getBaseAttackString() + "." + a.getBaseDefenseString(); - } else { - aCom = ""; - } - - if (b.isCreature()) { - bCom = b.getBaseAttackString() + "." + b.getBaseDefenseString(); - } else { - bCom = ""; - } - } else if (column == 6)//Rarity - { - aCom = getRarity(a); - bCom = getRarity(b); - } else if (column == 7 && col7mod == false)//Value - { - aCom = getValue(a); - bCom = getValue(b); - } else if (column == 7 && col7mod == true)//Set - { - aCom = SetInfoUtil.getIndexByCode(a.getCurSetCode()); - bCom = SetInfoUtil.getIndexByCode(b.getCurSetCode()); - } else if (column == 8)//AI - { - aCom = getAI(a); - bCom = getAI(b); - } - /*else if (column == 99)//New First - { - aCom = sortNewFirst(a); - bCom = sortNewFirst(b); - }*/ - - if (ascending) - return aCom.compareTo(bCom); - else - return bCom.compareTo(aCom); - }//compare() - - /** - *

countCardName.

- * - * @param name a {@link java.lang.String} object. - * @param c a {@link forge.CardList} object. - * @return a int. - */ - final private int countCardName(String name, CardList c) { - int count = 0; - for (int i = 0; i < c.size(); i++) - if (name.equals(c.get(i).getName())) - count++; - - return count; - } - - /** - *

getRarity.

- * - * @param c a {@link forge.Card} object. - * @return a {@link java.lang.Integer} object. - */ - final private Integer getRarity(Card c) { - String rarity = c.getRarity(); - - if (rarity.equals("new")) - return 1; - - if (!c.getCurSetCode().equals("")) { - SetInfo si = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()); - if (si != null) - rarity = si.Rarity; - } - - if (rarity.equals("Common")) - return 2; - else if (rarity.equals("Uncommon")) - return 3; - else if (rarity.equals("Rare")) - return 4; - else if (rarity.equals("Mythic")) - return 5; - else if (rarity.equals("Special")) - return 6; - else if (rarity.equals("Land")) - return 7; - else - return 8; - - // This older form of the method no longer works as it is not compatible with set info. - /* - if(c.getRarity().equals("Common")) - return Integer.valueOf(1); - else if(c.getRarity().equals("Uncommon")) - return Integer.valueOf(2); - else if(c.getRarity().equals("Rare")) - return Integer.valueOf(3); - else if(c.getRarity().equals("Land")) - return Integer.valueOf(4); - else - return Integer.valueOf(5); - */ - } - - /** - *

getValue.

- * - * @param c a {@link forge.Card} object. - * @return a {@link java.lang.Long} object. - */ - final private Long getValue(Card c) { - return c.getValue(); - } - - /** - *

getColor.

- * - * @param c a {@link forge.Card} object. - * @return a {@link java.lang.String} object. - */ - final public static String getColor(Card c) { - ArrayList list = CardUtil.getColors(c); - - if (list.size() == 1) - return list.get(0).toString(); - - return "multi"; - } - - /** - *

getAI.

- * - * @param c a {@link forge.Card} object. - * @return a {@link java.lang.Integer} object. - */ - final private Integer getAI(Card c) { - if (c.getSVar("RemAIDeck").equals("True") - && c.getSVar("RemRandomDeck").equals("True")) - return Integer.valueOf(3); - else if (c.getSVar("RemAIDeck").equals("True")) - return Integer.valueOf(4); - else if (c.getSVar("RemRandomDeck").equals("True")) - return Integer.valueOf(2); - else - return Integer.valueOf(1); - } - - /** - *

getType.

- * - * @param c a {@link forge.Card} object. - * @return a {@link java.lang.Comparable} object. - */ - final private Comparable getType(Card c) { - return c.getType().toString(); - } - -} diff --git a/src/main/java/forge/card/CardColor.java b/src/main/java/forge/card/CardColor.java index 67f2e1dec46..ec8a8b55b18 100644 --- a/src/main/java/forge/card/CardColor.java +++ b/src/main/java/forge/card/CardColor.java @@ -50,13 +50,13 @@ public final class CardColor implements Comparable { @Override public String toString() { switch (myColor) { - case 0: return ""; - case WHITE: return "White"; // Constant.Color.White; - case BLUE: return "Blue"; // Constant.Color.Blue; - case BLACK: return "Black"; // Constant.Color.Black; - case RED: return "Red"; // Constant.Color.Red; - case GREEN: return "Green"; // Constant.Color.Green; - default: return "Multi"; + case 0: return "colorless"; + case WHITE: return "white"; // Constant.Color.White; + case BLUE: return "blue"; // Constant.Color.Blue; + case BLACK: return "black"; // Constant.Color.Black; + case RED: return "red"; // Constant.Color.Red; + case GREEN: return "green"; // Constant.Color.Green; + default: return "multi"; } } } diff --git a/src/main/java/forge/card/CardDb.java b/src/main/java/forge/card/CardDb.java index 8fbe2795803..7b9c070fc32 100644 --- a/src/main/java/forge/card/CardDb.java +++ b/src/main/java/forge/card/CardDb.java @@ -1,6 +1,7 @@ package forge.card; import java.util.ArrayList; +import java.util.Collections; import java.util.Hashtable; import java.util.Iterator; import java.util.List; @@ -23,12 +24,12 @@ public final class CardDb { private static volatile CardDb onlyInstance = null; // 'volatile' keyword makes this working public static CardDb instance() { if (onlyInstance == null) { - throw new NullPointerException("CardDb has not yet been initialized, run setup() first"); + throw new NullPointerException("CardDb has not yet been initialized, run setup() first"); } return onlyInstance; } public static void setup(final Iterator list) { - if (onlyInstance != null) { + if (onlyInstance != null) { throw new RuntimeException("CardDb has already been initialized, don't do it twice please"); } synchronized (CardDb.class) { @@ -57,6 +58,7 @@ public final class CardDb { while (parser.hasNext()) { addNewCard(parser.next()); } + // TODO: consider using Collections.unmodifiableList wherever possible } public void addNewCard(final CardRules card) { @@ -94,12 +96,12 @@ public final class CardDb { // Single fetch public CardPrinted getCard(final String name) { // Sometimes they read from decks things like "CardName|Set" - but we can handle it - int pipePos = name.indexOf('|'); - if (pipePos >= 0) { return getCard(name.substring(0, pipePos), name.substring(pipePos+1)); } + int pipePos = name.indexOf('|'); + if (pipePos >= 0) { return getCard(name.substring(0, pipePos), name.substring(pipePos + 1)); } // OK, plain name here CardPrinted card = uniqueCards.get(name); if (card != null) { return card; } - throw new NoSuchElementException(String.format("Card '%s' not found in our database.", name)); + throw new NoSuchElementException(String.format("Card '%s' not found in our database.", name)); } // Advanced fetch by name+set public CardPrinted getCard(final String name, final String set) { return getCard(name, set, 0); } @@ -111,13 +113,13 @@ public final class CardDb { throw new NoSuchElementException(err); } // 2. Find the card itself - CardPrinted[] cards = cardsFromset.get(name); - if (null == cards) { + CardPrinted[] cardCopies = cardsFromset.get(name); + if (null == cardCopies) { String err = String.format("Asked for card '%s' from '%s': set found, but the card wasn't. :(", name, set); throw new NoSuchElementException(err); } // 3. Get the proper copy - if (artIndex >= 0 && artIndex <= cards.length) { return cards[artIndex]; } + if (artIndex >= 0 && artIndex <= cardCopies.length) { return cardCopies[artIndex]; } String err = String.format("Asked for '%s' from '%s' #%d: db didn't find that copy.", name, set, artIndex); throw new NoSuchElementException(err); } diff --git a/src/main/java/forge/card/CardPool.java b/src/main/java/forge/card/CardPool.java index 4a106420737..74f423afaa5 100644 --- a/src/main/java/forge/card/CardPool.java +++ b/src/main/java/forge/card/CardPool.java @@ -7,9 +7,7 @@ import java.util.Map.Entry; /** *

CardPool class.

- * - * @author Forge - * @version $Id: CardReference.java 9708 2011-08-09 19:34:12Z jendave $ + * Represents a list of cards with amount of each */ public final class CardPool extends CardPoolView { @@ -21,13 +19,12 @@ public final class CardPool extends CardPoolView { @SuppressWarnings("unchecked") public CardPool(final CardPoolView from) { super(); - cards = (Hashtable) ((Hashtable) (from.cards)).clone(); + cards = new Hashtable(); + cards.putAll(from.cards); } public CardPool(final Iterable list) { this(); addAllCards(list); } - - // get public CardPoolView getView() { return new CardPoolView(Collections.unmodifiableMap(cards)); } @@ -54,6 +51,7 @@ public final class CardPool extends CardPoolView { public void remove(final CardPrinted card) { remove(card, 1); } public void remove(final CardPrinted card, final int amount) { int count = count(card); + if (count == 0) { return; } if (count <= amount) { cards.remove(card); } else { cards.put(card, count - amount); } isListInSync = false; diff --git a/src/main/java/forge/card/CardPoolView.java b/src/main/java/forge/card/CardPoolView.java index a57daacf9a6..4d9abcc0b3b 100644 --- a/src/main/java/forge/card/CardPoolView.java +++ b/src/main/java/forge/card/CardPoolView.java @@ -60,6 +60,7 @@ public class CardPoolView implements Iterable> { return result; } public final int countDistinct() { return cards.size(); } + public final boolean isEmpty() { return cards.isEmpty(); } public final List> getOrderedList() { if (!isListInSync) { diff --git a/src/main/java/forge/card/CardPrinted.java b/src/main/java/forge/card/CardPrinted.java index c0a18d3be90..a4a10417f8c 100644 --- a/src/main/java/forge/card/CardPrinted.java +++ b/src/main/java/forge/card/CardPrinted.java @@ -98,7 +98,9 @@ public final class CardPrinted implements Comparable { @Override public String toString() { - return String.format("%s|%s", name, cardSet); + return name; + // cannot still decide, if this "name|set" format is needed anymore + //return String.format("%s|%s", name, cardSet); } public Card toForgeCard() { diff --git a/src/main/java/forge/card/CardRules.java b/src/main/java/forge/card/CardRules.java index e61afd82fc4..921be89ae55 100644 --- a/src/main/java/forge/card/CardRules.java +++ b/src/main/java/forge/card/CardRules.java @@ -46,13 +46,13 @@ public final class CardRules { public String[] getRules() { return rules; } public Set> getSetsPrinted() { return setsPrinted.entrySet(); } - public final String getPower() { return power; } - public final int getIntPower() { return iPower; } - public final String getToughness() { return toughness; } - public final int getIntToughness() { return iToughness; } - public final String getLoyalty() { return loyalty; } - public final boolean getRemAIDecks() { return isRemovedFromAIDecks; } - public final boolean getRemRandomDecks() { return isRemovedFromRandomDecks; } + public String getPower() { return power; } + public int getIntPower() { return iPower; } + public String getToughness() { return toughness; } + public int getIntToughness() { return iToughness; } + public String getLoyalty() { return loyalty; } + public boolean getRemAIDecks() { return isRemovedFromAIDecks; } + public boolean getRemRandomDecks() { return isRemovedFromRandomDecks; } public String getPTorLoyalty() { if (getType().isCreature()) { return power + "/" + toughness; } @@ -73,7 +73,7 @@ public final class CardRules { this.isRemovedFromRandomDecks = removedFromRandomDecks; //System.out.println(cardName); - + if (cardType.isCreature()) { int slashPos = ptLine.indexOf('/'); if (slashPos == -1) { @@ -90,7 +90,8 @@ public final class CardRules { } public boolean rulesContain(final String text) { - for (String r : rules) { if (r.contains(text)) { return true; } } + if (rules == null) { return false; } + for (String r : rules) { if (StringUtils.containsIgnoreCase(r, text)) { return true; } } return false; } public String getLatestSetPrinted() { @@ -113,7 +114,7 @@ public final class CardRules { } public String getAiStatus() { - return isRemovedFromAIDecks ? (isRemovedFromRandomDecks ? "AI ?" : "AI") : (isRemovedFromRandomDecks ? "?" :""); + return isRemovedFromAIDecks ? (isRemovedFromRandomDecks ? "AI ?" : "AI") : (isRemovedFromRandomDecks ? "?" : ""); } public Integer getAiStatusComparable() { if (isRemovedFromAIDecks && isRemovedFromRandomDecks) { return Integer.valueOf(3); } @@ -122,6 +123,9 @@ public final class CardRules { else { return Integer.valueOf(1); } } + /** + * Filtering conditions specific for CardRules class, defined here along with some presets. + */ public abstract static class Predicates { // Static builder methods - they choose concrete implementation by themselves @@ -131,18 +135,23 @@ public final class CardRules { } // Power // Toughness - public static Predicate rules(final StringOp op, final String what) - { + public static Predicate rules(final StringOp op, final String what) { return new LeafString(LeafString.CardField.RULES, op, what); } - public static Predicate name(final StringOp op, final String what) - { + public static Predicate name(final StringOp op, final String what) { return new LeafString(LeafString.CardField.NAME, op, what); } - public static Predicate subType(final StringOp op, final String what) - { + public static Predicate subType(final StringOp op, final String what) { return new LeafString(LeafString.CardField.SUBTYPE, op, what); } + public static Predicate joinedType(final StringOp op, final String what) { + return new LeafString(LeafString.CardField.JOINED_TYPE, op, what); + } + + public static Predicate wasPrintedInSet(final String setCode) { + return new PredicateExitsInSet(setCode); + } + public static Predicate coreType(final boolean isEqual, final String what) { try { return coreType(isEqual, CardCoreType.valueOf(CardCoreType.class, what)); } @@ -182,7 +191,8 @@ public final class CardRules { public enum CardField { RULES, NAME, - SUBTYPE + SUBTYPE, + JOINED_TYPE } private final String operand; @@ -201,15 +211,17 @@ public final class CardRules { case RULES: shouldConatin = operator == StringOp.CONTAINS || operator == StringOp.EQUALS; return shouldConatin == card.rulesContain(operand); + case JOINED_TYPE: + return op(card.getType().toString(), operand); default: return false; } } private boolean op(final String op1, final String op2) { - if (operator == StringOp.CONTAINS) { return op1.contains(op2); } - if (operator == StringOp.NOT_CONTAINS) { return op1.contains(op2); } - if (operator == StringOp.EQUALS) { return op1.equals(op2); } + if (operator == StringOp.CONTAINS) { return StringUtils.containsIgnoreCase(op1, op2); } + if (operator == StringOp.NOT_CONTAINS) { return !StringUtils.containsIgnoreCase(op1, op2); } + if (operator == StringOp.EQUALS) { return op1.equalsIgnoreCase(op2); } return false; } @@ -335,6 +347,18 @@ public final class CardRules { } } + private static class PredicateExitsInSet extends Predicate { + private final String setCode; + public PredicateExitsInSet(final String setsCode) { + setCode = setsCode; + } + + @Override + public boolean isTrue(final CardRules subject) { + return subject.setsPrinted.containsKey(setCode); + } + } + public static class Presets { public static final Predicate isCreature = coreType(true, CardCoreType.Creature); public static final Predicate isArtifact = coreType(true, CardCoreType.Artifact); @@ -353,10 +377,9 @@ public final class CardRules { public static final Predicate isRed = isColor(CardColor.RED); public static final Predicate isGreen = isColor(CardColor.GREEN); - public static final Predicate isColorless = hasCntColors((byte) 0); public static final Predicate isMulticolor = hasAtLeastCntColors((byte) 2); - + public static final List> colors = new ArrayList>(); static { colors.add(isWhite); diff --git a/src/main/java/forge/card/CardType.java b/src/main/java/forge/card/CardType.java index 865261ceea1..1555fa57765 100644 --- a/src/main/java/forge/card/CardType.java +++ b/src/main/java/forge/card/CardType.java @@ -40,11 +40,11 @@ public final class CardType implements Comparable { boolean hasMoreTypes = typeText.length() > 0; while (hasMoreTypes) { String type = typeText.substring(iTypeStart, iSpace == -1 ? typeText.length() : iSpace ); - if (!isMultiwordType(type)) { + hasMoreTypes = iSpace != -1; + if (!isMultiwordType(type) || !hasMoreTypes) { iTypeStart = iSpace + 1; result.parseAndAdd(type); } - hasMoreTypes = iSpace != -1; iSpace = typeText.indexOf(space, iSpace + 1); } return result; diff --git a/src/main/java/forge/deck/Deck.java b/src/main/java/forge/deck/Deck.java index cd80df04053..120f795601b 100644 --- a/src/main/java/forge/deck/Deck.java +++ b/src/main/java/forge/deck/Deck.java @@ -1,7 +1,10 @@ package forge.deck; -import forge.Card; import forge.Constant; +import forge.card.CardDb; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; import java.io.Serializable; import java.util.*; @@ -22,8 +25,8 @@ public class Deck implements Comparable, Serializable { private Map metadata = new HashMap(); - private List main; - private List sideboard; + private CardPool main; + private CardPool sideboard; /** Constant NAME="Name" */ public static final String NAME = "Name"; @@ -42,8 +45,8 @@ public class Deck implements Comparable, Serializable { *

Constructor for Deck.

*/ public Deck() { - main = new ArrayList(); - sideboard = new ArrayList(); + main = new CardPool(); + sideboard = new CardPool(); } /** @@ -58,8 +61,8 @@ public class Deck implements Comparable, Serializable { setDeckType(deckType); setName(name); - this.main = main; - this.sideboard = sideboard; + this.main = new CardPool(main); + this.sideboard = new CardPool(sideboard); } /** @@ -77,8 +80,8 @@ public class Deck implements Comparable, Serializable { * * @return a {@link java.util.List} object. */ - public List getMain() { - return Collections.unmodifiableList(main); + public CardPoolView getMain() { + return main.getView(); } /** @@ -86,8 +89,8 @@ public class Deck implements Comparable, Serializable { * * @return a {@link java.util.List} object. */ - public List getSideboard() { - return Collections.unmodifiableList(sideboard); + public CardPoolView getSideboard() { + return sideboard.getView(); } /** @@ -161,9 +164,10 @@ public class Deck implements Comparable, Serializable { * * @param cardName a {@link java.lang.String} object. */ - public void addMain(String cardName) { - main.add(cardName); - } + public void addMain(String cardName) { addMain( CardDb.instance().getCard(cardName) ); } + public void addMain(CardPrinted card) { main.add(card); } + public void addMain(CardPoolView list) { main.addAll(list); } + /** *

countMain.

@@ -171,27 +175,7 @@ public class Deck implements Comparable, Serializable { * @return a int. */ public int countMain() { - return main.size(); - } - - /** - *

Getter for the field main.

- * - * @param index a int. - * @return a {@link java.lang.String} object. - */ - public String getMain(int index) { - return main.get(index); - } - - /** - *

removeMain.

- * - * @param index a int. - * @return a {@link java.lang.String} object. - */ - public String removeMain(int index) { - return main.remove(index); + return main.countAll(); } /** @@ -199,11 +183,8 @@ public class Deck implements Comparable, Serializable { * * @param c a {@link forge.Card} object. */ - public void removeMain(Card c) { - if (main.contains(c.getName())) { - int i = main.indexOf(c.getName()); - main.remove(i); - } + public void removeMain(CardPrinted card) { + main.remove(card); } /** @@ -211,9 +192,10 @@ public class Deck implements Comparable, Serializable { * * @param cardName a {@link java.lang.String} object. */ - public void addSideboard(String cardName) { - sideboard.add(cardName); - } + public final void addSideboard(final String cardName) { addSideboard(CardDb.instance().getCard(cardName)); } + public final void addSideboard(final CardPrinted card) { sideboard.add(card); } + public final void addSideboard(final CardPoolView cards) { sideboard.addAll(cards); } + /** *

countSideboard.

@@ -221,17 +203,7 @@ public class Deck implements Comparable, Serializable { * @return a int. */ public int countSideboard() { - return sideboard.size(); - } - - /** - *

Getter for the field sideboard.

- * - * @param index a int. - * @return a {@link java.lang.String} object. - */ - public String getSideboard(int index) { - return sideboard.get(index); + return sideboard.countAll(); } /** @@ -240,8 +212,8 @@ public class Deck implements Comparable, Serializable { * @param index a int. * @return a {@link java.lang.String} object. */ - public String removeSideboard(int index) { - return sideboard.remove(index); + public void removeFromSideboard(CardPrinted card) { + sideboard.remove(card); } /** @@ -377,4 +349,14 @@ public class Deck implements Comparable, Serializable { public void addMetaData(String key, String value) { metadata.put(key, value); } + + public void clearSideboard() { + sideboard.clear(); + } + + public void clearMain() { + main.clear(); + + } + } diff --git a/src/main/java/forge/deck/DeckManager.java b/src/main/java/forge/deck/DeckManager.java index c09cd66e47b..fd2de901ca1 100644 --- a/src/main/java/forge/deck/DeckManager.java +++ b/src/main/java/forge/deck/DeckManager.java @@ -2,6 +2,7 @@ package forge.deck; import forge.Constant; +import forge.card.CardPrinted; import forge.error.ErrorViewer; import java.io.*; @@ -10,6 +11,8 @@ import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.commons.lang3.StringUtils; + import static java.lang.Integer.parseInt; import static java.lang.String.format; import static java.util.Arrays.asList; @@ -348,9 +351,12 @@ public class DeckManager { Matcher m = p.matcher(line); m.matches(); String s = m.group(2); + String cardName = m.group(3); + if (StringUtils.isBlank(cardName)) { continue; } + int count = s == null ? 1 : parseInt(s); for (int i = 0; i < count; i++) { - d.addSideboard(m.group(3)); + d.addSideboard(cardName); } } } @@ -432,12 +438,12 @@ public class DeckManager { } out.write(format("%s%n", "[main]")); - for (Entry e : count(d.getMain()).entrySet()) { - out.write(format("%d %s%n", e.getValue(), e.getKey())); + for (Entry e : d.getMain()) { + out.write(format("%d %s%n", e.getValue(), e.getKey().getName())); } out.write(format("%s%n", "[sideboard]")); - for (Entry e : count(d.getSideboard()).entrySet()) { - out.write(format("%d %s%n", e.getValue(), e.getKey())); + for (Entry e : d.getSideboard()) { + out.write(format("%d %s%n", e.getValue(), e.getKey().getName())); } } diff --git a/src/main/java/forge/deck/DownloadDeck.java b/src/main/java/forge/deck/DownloadDeck.java index 3f2f73cc2fb..6f29c17889e 100644 --- a/src/main/java/forge/deck/DownloadDeck.java +++ b/src/main/java/forge/deck/DownloadDeck.java @@ -152,25 +152,6 @@ public class DownloadDeck { return false; } - /** - *

getCardDownload.

- * - * @param c a {@link forge.Card} object. - * @param CardName a {@link java.lang.String} object. - * @return a {@link forge.Card} object. - */ - public Card getCardDownload(Card c, String CardName) { - // TODO: using AllZone.getCardFactory().getCard() would probably be much faster. - - for (Card newCard : AllZone.getCardFactory()) { - if (CardName.equalsIgnoreCase(newCard.getName())) { - return newCard; - } - } - - return null; - - } } diff --git a/src/main/java/forge/gui/CardListViewer.java b/src/main/java/forge/gui/CardListViewer.java index ba6a966b67c..16f08d11496 100644 --- a/src/main/java/forge/gui/CardListViewer.java +++ b/src/main/java/forge/gui/CardListViewer.java @@ -14,6 +14,7 @@ import javax.swing.event.ListSelectionListener; import forge.AllZone; import forge.Card; import forge.CardUtil; +import forge.card.CardPrinted; import forge.gui.game.CardDetailPanel; import forge.gui.game.CardPicturePanel; @@ -36,7 +37,7 @@ import static javax.swing.JOptionPane.*; public class CardListViewer { //Data and number of choices for the list - private List list; + private List list; //Decoration private String title; @@ -53,15 +54,15 @@ public class CardListViewer { private JOptionPane optionPane; private Action ok; - public CardListViewer(String title, List list) { + public CardListViewer(String title, List list) { this(title, "", list, null); } - public CardListViewer(String title, String message, List list) { + public CardListViewer(String title, String message, List list) { this(title, message, list, null); } - public CardListViewer(String title, String message, List list, Icon dialogIcon) { + public CardListViewer(String title, String message, List list, Icon dialogIcon) { this.title = title; this.list = unmodifiableList(list); jList = new JList(new ChooserListModel()); @@ -128,7 +129,7 @@ public class CardListViewer { optionPane.setValue(value); } } - + private class CardListFocuser implements WindowFocusListener { @Override @@ -146,7 +147,7 @@ public class CardListViewer { int row = jList.getSelectedIndex(); // (String) jList.getSelectedValue(); if (row >= 0 && row < list.size()) { - Card card = AllZone.getCardFactory().getCard(list.get(row) , null); + Card card = AllZone.getCardFactory().getCard(list.get(row).getName(), null); card.setRandomSetCode(); card.setImageFilename(CardUtil.buildFilename(card)); detail.setCard(card); diff --git a/src/main/java/forge/gui/ListChooser.java b/src/main/java/forge/gui/ListChooser.java index 78247887b25..97908ec7ebe 100644 --- a/src/main/java/forge/gui/ListChooser.java +++ b/src/main/java/forge/gui/ListChooser.java @@ -204,6 +204,7 @@ public class ListChooser { Object[] options; if (minChoices == 0) options = new Object[]{new JButton(ok), new JButton(cancel)}; else options = new Object[]{new JButton(ok)}; + if (maxChoices == 1) { jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } p = new JOptionPane(new Object[]{message, new JScrollPane(jList)}, QUESTION_MESSAGE, DEFAULT_OPTION, null, options, options[0]); diff --git a/src/main/java/forge/gui/deckeditor/CardColumnPresets.java b/src/main/java/forge/gui/deckeditor/CardColumnPresets.java new file mode 100644 index 00000000000..cf1bcc976d0 --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/CardColumnPresets.java @@ -0,0 +1,86 @@ +package forge.gui.deckeditor; + +import java.util.Map.Entry; + +import net.slightlymagic.braids.util.lambda.Lambda1; +import forge.SetInfoUtil; +import forge.card.CardPrinted; + +/** + * TODO: Write javadoc for this type. + * + */ +public abstract class CardColumnPresets { + + @SuppressWarnings("rawtypes") + public static final Lambda1> fnQtyCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return from.getValue(); } }; + public static final Lambda1> fnQtyGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return from.getValue(); } }; + + @SuppressWarnings("rawtypes") + public static final Lambda1> fnNameCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return from.getKey().getName(); } }; + public static final Lambda1> fnNameGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return from.getKey().getName(); } }; + + @SuppressWarnings("rawtypes") + public static final Lambda1> fnCostCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return from.getKey().getCard().getManaCost(); } }; + public static final Lambda1> fnCostGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return from.getKey().getCard().getManaCost().toString(); } }; + + @SuppressWarnings("rawtypes") + public static final Lambda1> fnColorCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return from.getKey().getCard().getColor(); } }; + public static final Lambda1> fnColorGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return from.getKey().getCard().getColor().toString(); } }; + + @SuppressWarnings("rawtypes") + public static final Lambda1> fnTypeCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return from.getKey().getCard().getType(); } }; + public static final Lambda1> fnTypeGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return from.getKey().getCard().getType().toString(); } }; + + @SuppressWarnings("rawtypes") + public static final Lambda1> fnStatsCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return from.getKey().getCard().getPTorLoyalty(); } }; + public static final Lambda1> fnStatsGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return from.getKey().getCard().getPTorLoyalty(); } }; + + @SuppressWarnings("rawtypes") + public static final Lambda1> fnRarityCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return from.getKey().getRarity(); } }; + public static final Lambda1> fnRarityGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return from.getKey().getRarity(); } }; + + @SuppressWarnings("rawtypes") + public static final Lambda1> fnSetCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return SetInfoUtil.getSetByCode(from.getKey().getSet()); } }; + public static final Lambda1> fnSetGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return from.getKey().getSet(); } }; + + @SuppressWarnings("rawtypes") + public static final Lambda1> fnAiStatusCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return from.getKey().getCard().getAiStatusComparable(); } }; + public static final Lambda1> fnAiStatusGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return from.getKey().getCard().getAiStatus(); } }; +} diff --git a/src/main/java/forge/gui/deckeditor/CardDisplay.java b/src/main/java/forge/gui/deckeditor/CardDisplay.java new file mode 100644 index 00000000000..b1ba87cbb4c --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/CardDisplay.java @@ -0,0 +1,14 @@ +package forge.gui.deckeditor; + +import forge.card.CardPrinted; + +/** + * TODO: Write javadoc for this type. + * + */ +public interface CardDisplay { + void showCard(CardPrinted card); + + // Sorry, this is for JPanel initialization + void jbInit(); +} diff --git a/src/main/java/forge/gui/deckeditor/CardShop.java b/src/main/java/forge/gui/deckeditor/CardShop.java new file mode 100644 index 00000000000..4d5bd622894 --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/CardShop.java @@ -0,0 +1,367 @@ +package forge.gui.deckeditor; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.Image; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Random; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.border.Border; +import javax.swing.border.EtchedBorder; +import javax.swing.border.TitledBorder; +import javax.swing.event.MouseInputAdapter; +import javax.swing.event.MouseInputListener; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.TableCellRenderer; + +import net.slightlymagic.braids.util.lambda.Lambda1; + +import forge.Card; +import forge.CardList; +import forge.Command; +import forge.ImageCache; +import forge.ReadBoosterPack; +import forge.ReadPriceList; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardRarity; +import forge.card.CardPrinted; +import forge.deck.Deck; +import forge.error.ErrorViewer; +import forge.gui.game.CardDetailPanel; +import forge.gui.game.CardPicturePanel; +import forge.properties.NewConstants; +import forge.view.swing.OldGuiNewGame; + +/** + *

+ * Gui_CardShop class. + *

+ * + * @author Forge + * @version $Id$ + */ +public class CardShop extends DeckEditorBase { + + /** Constant serialVersionUID=3988857075791576483L */ + private static final long serialVersionUID = 3988857075791576483L; + + private JButton buyButton = new JButton(); + private JButton sellButton = new JButton(); + + private JScrollPane jScrollPane3 = new JScrollPane(); + private JPanel jPanel3 = new JPanel(); + private GridLayout gridLayout1 = new GridLayout(); + private JLabel creditsLabel = new JLabel(); + private JLabel jLabel1 = new JLabel(); + private JLabel sellPercentageLabel = new JLabel(); + + private double multiplier; + + private forge.quest.data.QuestData questData; + + // get pricelist: + private ReadPriceList r = new ReadPriceList(); + private Map mapPrices = r.getPriceList(); + + + /** {@inheritDoc} */ + public void setDecks(CardPoolView topParam, CardPoolView bottomParam) { + this.top = new CardPool(topParam); + this.bottom = bottomParam; + + topModel.clear(); + bottomModel.clear(); + + // update top + topModel.addCards(topParam); + bottomModel.addCards(bottomParam); + + topModel.resort(); + bottomModel.resort(); + }// updateDisplay + + /** + *

+ * show. + *

+ * + * @param exitCommand + * a {@link forge.Command} object. + */ + public void show(final Command exitCommand) { + final Command exit = new Command() { + private static final long serialVersionUID = -7428793574300520612L; + + public void execute() { + CardShop.this.dispose(); + exitCommand.execute(); + } + }; + + // do not change this!!!! + this.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent ev) { + exit.execute(); + } + }); + + setup(); + + multiplier = questData.getSellMutliplier(); + + CardPoolView forSale = questData.getShopList(); + if (forSale.isEmpty()) { + questData.generateCardsInShop(); + forSale = questData.getShopList(); + } + CardPoolView owned = questData.getCardpool().getView(); + + setDecks(forSale, owned); + + double multiPercent = multiplier * 100; + NumberFormat formatter = new DecimalFormat("#0.00"); + String maxSellingPrice = ""; + int maxSellPrice = questData.getSellPriceLimit(); + + if (maxSellPrice < Integer.MAX_VALUE) { maxSellingPrice = String.format(" Max selling price: %d", maxSellPrice); } + sellPercentageLabel.setText("(Sell percentage: " + formatter.format(multiPercent) + "% of value)" + maxSellingPrice); + + topModel.sort(1, true); + bottomModel.sort(1, true); + }// show(Command) + + /** + *

+ * setup. + *

+ */ + private void setup() { + List> columns = new ArrayList>(); + columns.add(new TableColumnInfo("Qty", 30, CardColumnPresets.fnQtyCompare, CardColumnPresets.fnQtyGet)); + columns.add(new TableColumnInfo("Name", 180, CardColumnPresets.fnNameCompare, CardColumnPresets.fnNameGet)); + columns.add(new TableColumnInfo("Cost", 70, CardColumnPresets.fnCostCompare, CardColumnPresets.fnCostGet)); + columns.add(new TableColumnInfo("Color", 50, CardColumnPresets.fnColorCompare, CardColumnPresets.fnColorGet)); + columns.add(new TableColumnInfo("Type", 100, CardColumnPresets.fnTypeCompare, CardColumnPresets.fnTypeGet)); + columns.add(new TableColumnInfo("Stats", 40, CardColumnPresets.fnStatsCompare, CardColumnPresets.fnStatsGet)); + columns.add(new TableColumnInfo("R", 35, CardColumnPresets.fnRarityCompare, CardColumnPresets.fnRarityGet)); + columns.add(new TableColumnInfo("Set", 40, CardColumnPresets.fnSetCompare, CardColumnPresets.fnSetGet)); + columns.add(new TableColumnInfo("Price", 40, fnPriceCompare, fnPriceGet)); + + setupTables(columns, false); + + setSize(1024, 768); + this.setResizable(false); + Dimension screen = getToolkit().getScreenSize(); + Rectangle bounds = getBounds(); + bounds.width = 1024; + bounds.height = 768; + bounds.x = (screen.width - bounds.width) / 2; + bounds.y = (screen.height - bounds.height) / 2; + setBounds(bounds); + // TODO use this as soon the deck editor has resizable GUI + // //Use both so that when "un"maximizing, the frame isn't tiny + // setSize(1024, 740); + // setExtendedState(Frame.MAXIMIZED_BOTH); + }// setupAndDisplay() + + /** + *

+ * Constructor for Gui_CardShop. + *

+ * + * @param qd + * a {@link forge.quest.data.QuestData} object. + */ + public CardShop(forge.quest.data.QuestData qd) { + super(false, false); + questData = qd; + try { + jbInit(); + } catch (Exception ex) { + ErrorViewer.showError(ex); + } + } + + + /** + *

+ * jbInit. + *

+ * + * @throws java.lang.Exception + * if any. + */ + private void jbInit() throws Exception { + + jbInitTables("Cards for sale", "Owned Cards"); + + jScrollPane1.setBounds(new Rectangle(19, 20, 726, 346)); + jScrollPane2.setBounds(new Rectangle(19, 458, 726, 276)); + + sellButton.setBounds(new Rectangle(180, 403, 146, 49)); + // removeButton.setIcon(upIcon); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + sellButton.setFont(new java.awt.Font("Dialog", 0, 13)); + sellButton.setText("Sell Card"); + sellButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + sellButton_actionPerformed(e); + } + }); + buyButton.setText("Buy Card"); + buyButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + buyButton_actionPerformed(e); + } + }); + + if (!OldGuiNewGame.useLAFFonts.isSelected()) + buyButton.setFont(new java.awt.Font("Dialog", 0, 13)); + buyButton.setBounds(new Rectangle(23, 403, 146, 49)); + + cardView.jbInit(); + cardView.setBounds(new Rectangle(765, 23, 239, 710)); + // Do not lower statsLabel any lower, we want this to be visible at 1024 + // x 768 screen size + this.setTitle("Card Shop"); + jScrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + jScrollPane3.setBounds(new Rectangle(6, 168, 225, 143)); + jPanel3.setBounds(new Rectangle(7, 21, 224, 141)); + jPanel3.setLayout(gridLayout1); + gridLayout1.setColumns(1); + gridLayout1.setRows(0); + creditsLabel.setBounds(new Rectangle(19, 365, 720, 31)); + creditsLabel.setText("Total credits: " + questData.getCredits()); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + creditsLabel.setFont(new java.awt.Font("Dialog", 0, 14)); + sellPercentageLabel.setBounds(new Rectangle(350, 403, 450, 31)); + sellPercentageLabel.setText("(Sell percentage: " + multiplier + ")"); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + sellPercentageLabel.setFont(new java.awt.Font("Dialog", 0, 14)); + jLabel1.setText("Click on the column name (like name or color) to sort the cards"); + jLabel1.setBounds(new Rectangle(20, 1, 400, 19)); + this.getContentPane().add(cardView, null); + this.getContentPane().add(jScrollPane1, null); + this.getContentPane().add(jScrollPane2, null); + this.getContentPane().add(creditsLabel, null); + this.getContentPane().add(buyButton, null); + this.getContentPane().add(sellButton, null); + this.getContentPane().add(sellPercentageLabel, null); + this.getContentPane().add(jLabel1, null); + } + + // TODO: move to cardshop + private Integer getCardValue(final CardPrinted card) { + if (mapPrices.containsKey(card.getName())) { + return mapPrices.get(card.getName()); + } else { + switch (card.getRarity()) { + case BasicLand: return Integer.valueOf(4); + case Common: return Integer.valueOf(6); + case Uncommon: return Integer.valueOf(40); + case Rare: return Integer.valueOf(120); + case MythicRare: return Integer.valueOf(600); + default: return Integer.valueOf(15); + } + } + } + + private void buyButton_actionPerformed(ActionEvent e) { + int n = topTable.getSelectedRow(); + if (n != -1) { + CardPrinted c = topModel.rowToCard(n).getKey(); + int value = getCardValue(c); + + if (value <= questData.getCredits()) { + bottomModel.addCard(c); + bottomModel.resort(); + + topModel.removeCard(c); + + questData.buyCard(c, value); + + creditsLabel.setText("Total credits: " + questData.getCredits()); + fixSelection(topModel, topTable, n); + + } else { + JOptionPane.showMessageDialog(null, "Not enough credits!"); + } + }// if(valid row) + }// buyButton_actionPerformed + + /** + *

+ * sellButton_actionPerformed. + *

+ * + * @param e + * a {@link java.awt.event.ActionEvent} object. + */ + void sellButton_actionPerformed(ActionEvent e) { + + int n = bottomTable.getSelectedRow(); + if (n != -1) { + CardPrinted c = bottomModel.rowToCard(n).getKey(); + bottomModel.removeCard(c); + + topModel.addCard(c); + topModel.resort(); + + // bottomModel.removeCard(c); + questData.addCardToShopList(c); + + int price = Math.min((int) (multiplier * getCardValue(c)), questData.getSellPriceLimit()); + + questData.sellCard(c, price); + creditsLabel.setText("Total credits: " + questData.getCredits()); + + int leftInPool = questData.getCardpool().count(c); + // remove sold cards from all decks: + for (String deckName : questData.getDeckNames()) { + Deck deck = questData.getDeck(deckName); + for (int cntInDeck = deck.getMain().count(c); cntInDeck > leftInPool; cntInDeck--) { + deck.removeMain(c); + } + } + + fixSelection(bottomModel, bottomTable, n); + + }// if(valid row) + }// sellButton_actionPerformed + + @SuppressWarnings("rawtypes") + protected final Lambda1> fnPriceCompare = + new Lambda1>() { @Override + public Comparable apply(final Entry from) { return getCardValue(from.getKey()); } }; + protected final Lambda1> fnPriceGet = + new Lambda1>() { @Override + public Object apply(final Entry from) { return getCardValue(from.getKey()); } }; + + +} diff --git a/src/main/java/forge/gui/deckeditor/CardViewPanel.java b/src/main/java/forge/gui/deckeditor/CardViewPanel.java new file mode 100644 index 00000000000..2554929f67a --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/CardViewPanel.java @@ -0,0 +1,178 @@ +package forge.gui.deckeditor; + +import java.awt.Color; +import java.awt.Container; +import java.awt.LayoutManager2; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.io.File; +import java.io.IOException; + +import javax.swing.JButton; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.filechooser.FileFilter; + +import net.miginfocom.swing.MigLayout; + +import arcane.ui.CardPanel; +import arcane.ui.ViewPanel; + +import forge.Card; +import forge.GuiDisplayUtil; +import forge.ImagePreviewPanel; +import forge.card.CardPrinted; +import forge.gui.game.CardDetailPanel; +import forge.properties.ForgeProps; +import forge.properties.NewConstants; +import forge.view.swing.OldGuiNewGame; + +/** + * This panel is to be placed in the right part of a deck editor + * + */ +public class CardViewPanel extends JPanel implements CardDisplay { + + private static final long serialVersionUID = -7134546689397508597L; + + private JButton changePictureButton = new JButton(); + private JButton removePictureButton = new JButton(); + + // Controls to show card details + protected CardDetailPanel detail = new CardDetailPanel(null); + protected CardPanel picture = new CardPanel(null); + protected ViewPanel pictureViewPanel = new ViewPanel(); + + // fake card to allow picture changes + public Card cCardHQ; + /** Constant previousDirectory */ + protected static File previousDirectory = null; + + + public void jbInit() { + changePictureButton.setText("Change picture..."); + changePictureButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + changePictureButton_actionPerformed(e); + } + }); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + changePictureButton.setFont(new java.awt.Font("Dialog", 0, 10)); + + removePictureButton.setText("Remove picture..."); + removePictureButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + removePictureButton_actionPerformed(e); + } + }); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + removePictureButton.setFont(new java.awt.Font("Dialog", 0, 10)); + + pictureViewPanel.setCardPanel(picture); + + this.setLayout(new MigLayout("fill, ins 0")); + this.add(detail, "w 239, h 323, grow, flowy, wrap"); + this.add(changePictureButton, "align 50% 0%, split 2, flowx"); + this.add(removePictureButton, "align 50% 0%, wrap"); + this.add(pictureViewPanel, "wmin 239, hmin 323, grow"); + } + + public void showCard(CardPrinted card) { + Card card2 = card.toForgeCard(); + detail.setCard(card2); + setCard(card2); + } + public void setCard(Card c) { + picture.setCard(c); + } + + /** + *

+ * changePictureButton_actionPerformed. + *

+ * + * @param e + * a {@link java.awt.event.ActionEvent} object. + */ + void changePictureButton_actionPerformed(ActionEvent e) { + if (cCardHQ != null) { + File file = getImportFilename(); + if (file != null) { + String fileName = GuiDisplayUtil.cleanString(cCardHQ.getName()) + ".jpg"; + File base = ForgeProps.getFile(NewConstants.IMAGE_BASE); + File f = new File(base, fileName); + f.delete(); + + try { + org.apache.commons.io.FileUtils.copyFile(file, f); + } catch (IOException e1) { + // TODO Auto-generated catch block ignores the exception, but sends it to System.err and probably forge.log. + e1.printStackTrace(); + } + setCard(cCardHQ); + } + } + } + + /** + *

+ * getImportFilename. + *

+ * + * @return a {@link java.io.File} object. + */ + private File getImportFilename() { + JFileChooser chooser = new JFileChooser(previousDirectory); + ImagePreviewPanel preview = new ImagePreviewPanel(); + chooser.setAccessory(preview); + chooser.addPropertyChangeListener(preview); + chooser.addChoosableFileFilter(dckFilter); + int returnVal = chooser.showOpenDialog(null); + + if (returnVal == JFileChooser.APPROVE_OPTION) { + File file = chooser.getSelectedFile(); + previousDirectory = file.getParentFile(); + return file; + } + + return null; + + } + + protected FileFilter dckFilter = new FileFilter() { + + @Override + public boolean accept(File f) { + return f.getName().endsWith(".jpg") || f.isDirectory(); + } + + @Override + public String getDescription() { + return "*.jpg"; + } + + }; + + + void removePictureButton_actionPerformed(ActionEvent e) { + if (cCardHQ != null) { + String options[] = { "Yes", "No" }; + int value = JOptionPane.showOptionDialog(null, "Do you want delete " + cCardHQ.getName() + " picture?", + "Delete picture", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, + options[1]); + if (value == 0) { + String fileName = GuiDisplayUtil.cleanString(cCardHQ.getName()) + ".jpg"; + File base = ForgeProps.getFile(NewConstants.IMAGE_BASE); + File f = new File(base, fileName); + f.delete(); + JOptionPane.showMessageDialog(null, "Picture " + cCardHQ.getName() + " deleted.", "Delete picture", + JOptionPane.INFORMATION_MESSAGE); + setCard(cCardHQ); + } + } + } + + public Card getCard() { return detail.getCard(); } + +} diff --git a/src/main/java/forge/gui/deckeditor/CardViewPanelLite.java b/src/main/java/forge/gui/deckeditor/CardViewPanelLite.java new file mode 100644 index 00000000000..d76ab603345 --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/CardViewPanelLite.java @@ -0,0 +1,62 @@ +package forge.gui.deckeditor; + +import java.awt.Color; +import java.awt.Container; +import java.awt.LayoutManager2; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.io.File; +import java.io.IOException; + +import javax.swing.JButton; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.filechooser.FileFilter; + +import net.miginfocom.swing.MigLayout; + +import arcane.ui.CardPanel; +import arcane.ui.ViewPanel; + +import forge.Card; +import forge.GuiDisplayUtil; +import forge.ImagePreviewPanel; +import forge.card.CardPrinted; +import forge.gui.game.CardDetailPanel; +import forge.gui.game.CardPicturePanel; +import forge.properties.ForgeProps; +import forge.properties.NewConstants; +import forge.view.swing.OldGuiNewGame; + +/** + * This panel is to be placed in the right part of a deck editor + * + */ +public class CardViewPanelLite extends JPanel implements CardDisplay { + + private static final long serialVersionUID = -7134546689397508597L; + + // Controls to show card details + protected CardDetailPanel detail = new CardDetailPanel(null); + private CardPicturePanel picture = new CardPicturePanel(null); + + /** Constant previousDirectory */ + protected static File previousDirectory = null; + + + public void jbInit() { + this.setLayout(new MigLayout("fill, ins 0")); + this.add(detail, "w 239, h 323, grow, flowy, wrap"); + this.add(picture, "wmin 239, hmin 323, grow"); + } + + public void showCard(CardPrinted card) { + picture.setCard(card); + Card card2 = card.toForgeCard(); + detail.setCard(card2); + } + + public Card getCard() { return detail.getCard(); } + +} diff --git a/src/main/java/forge/DeckDisplay.java b/src/main/java/forge/gui/deckeditor/DeckDisplay.java similarity index 72% rename from src/main/java/forge/DeckDisplay.java rename to src/main/java/forge/gui/deckeditor/DeckDisplay.java index 4a153069644..aa9dc5ed70d 100644 --- a/src/main/java/forge/DeckDisplay.java +++ b/src/main/java/forge/gui/deckeditor/DeckDisplay.java @@ -1,4 +1,9 @@ -package forge; +package forge.gui.deckeditor; + +import forge.CardList; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; /** * Created by IntelliJ IDEA. @@ -8,14 +13,14 @@ package forge; * @author Forge * @version $Id$ */ -interface DeckDisplay { +public interface DeckDisplay { /** *

updateDisplay.

* * @param top a {@link forge.CardList} object. * @param bottom a {@link forge.CardList} object. */ - public void updateDisplay(CardList top, CardList bottom); + public void setDecks(CardPoolView top, CardPoolView bottom); //top shows available card pool //if constructed, top shows all cards @@ -26,7 +31,7 @@ interface DeckDisplay { * * @return a {@link forge.CardList} object. */ - public CardList getTop(); + public CardPoolView getTop(); //bottom shows cards that the user has chosen for his library /** @@ -34,7 +39,7 @@ interface DeckDisplay { * * @return a {@link forge.CardList} object. */ - public CardList getBottom(); + public CardPoolView getBottom(); /** *

setTitle.

diff --git a/src/main/java/forge/gui/deckeditor/DeckEditor.java b/src/main/java/forge/gui/deckeditor/DeckEditor.java new file mode 100644 index 00000000000..0b3e081e16b --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/DeckEditor.java @@ -0,0 +1,550 @@ +package forge.gui.deckeditor; + +import java.awt.Container; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.UndoableEditEvent; +import javax.swing.event.UndoableEditListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; + +import org.apache.commons.lang3.StringUtils; +import org.eclipse.swt.widgets.Combo; + +import net.miginfocom.swing.MigLayout; +import net.slightlymagic.maxmtg.Predicate; +import net.slightlymagic.maxmtg.Predicate.StringOp; +import forge.Command; +import forge.Constant; +import forge.Gui_ProgressBarWindow; +import forge.SetInfoUtil; +import forge.card.CardRules; +import forge.card.CardDb; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; +import forge.deck.Deck; +import forge.error.ErrorViewer; +import forge.properties.NewConstants; +import forge.view.swing.OldGuiNewGame; + +/** + *

+ * Gui_DeckEditor class. + *

+ * + * @author Forge + * @version $Id$ + */ +public class DeckEditor extends DeckEditorBase implements NewConstants { + /** Constant serialVersionUID=130339644136746796L */ + private static final long serialVersionUID = 130339644136746796L; + + public DeckEditorMenu customMenu; + public Gui_ProgressBarWindow gPBW = new Gui_ProgressBarWindow(); + + // private ImageIcon upIcon = Constant.IO.upIcon; + // private ImageIcon downIcon = Constant.IO.downIcon; + + private JButton removeButton = new JButton(); + private JButton addButton = new JButton(); + private JButton analysisButton = new JButton(); + private JScrollPane jScrollPane3 = new JScrollPane(); + private JPanel jPanel3 = new JPanel(); + private GridLayout gridLayout1 = new GridLayout(); + + private JLabel labelFilterName = new JLabel(); + private JLabel labelFilterType = new JLabel(); + private JLabel labelFilterRules = new JLabel(); + private JLabel jLabel4 = new JLabel(); + + //public JButton filterButton = new JButton(); + private JTextField txtCardName = new JTextField(); + + private JTextField txtCardType = new JTextField(); + private JTextField txtCardRules = new JTextField(); + private JComboBox searchSetCombo = new JComboBox(); + private JButton clearFilterButton = new JButton(); + + /** {@inheritDoc} */ + @Override + public void setTitle(String message) { + super.setTitle(message); + } + + /** {@inheritDoc} */ + public void setDecks(CardPoolView topPool, CardPoolView bottomPool) { + top = new CardPool(topPool); + bottom = bottomPool; + + topModel.clear(); + bottomModel.clear(); + + + if (gPBW.isVisible()) + gPBW.setProgressRange(0, top.countDistinct() + bottom.countDistinct()); + + // this should have been called each step :) + if (gPBW.isVisible()) { gPBW.increment(); } + + Predicate filter = buildFilter(); + topModel.addCards(filter.select(top, CardPoolView.fnToCard)); + + // update bottom + bottomModel.addCards(bottom); + + if (gPBW.isVisible()) + gPBW.setTitle("Sorting Deck Editor"); + + topModel.resort(); + topTable.repaint(); + bottomModel.resort(); + bottomTable.repaint(); + }// updateDisplay + + /** + *

+ * updateDisplay. + *

+ */ + + + /** + *

+ * show. + *

+ * + * @param exitCommand + * a {@link forge.Command} object. + */ + public void show(final Command exitCommand) { + final Command exit = new Command() { + private static final long serialVersionUID = 5210924838133689758L; + + public void execute() { + DeckEditor.this.dispose(); + exitCommand.execute(); + } + }; + + // pm = new ProgressMonitor(this, "Loading Deck Editor", "", 0, 20000); + gPBW.setTitle("Loading Deck Editor"); + gPBW.setVisible(true); + + customMenu = new DeckEditorMenu(this, exit); + this.setJMenuBar(customMenu); + + // do not change this!!!! + this.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent ev) { + customMenu.close(); + } + }); + + setup(); + + // show cards, makes this user friendly + if (Constant.Runtime.GameType[0].equals(Constant.GameType.Constructed)) + customMenu.newConstructed(); + + topModel.sort(1, true); + bottomModel.sort(1, true); + + gPBW.dispose(); + }// show(Command) + + + private void setup() { + List> columns = new ArrayList>(); + columns.add(new TableColumnInfo("Qty", 30, CardColumnPresets.fnQtyCompare, CardColumnPresets.fnQtyGet)); + columns.add(new TableColumnInfo("Name", 180, CardColumnPresets.fnNameCompare, CardColumnPresets.fnNameGet)); + columns.add(new TableColumnInfo("Cost", 70, CardColumnPresets.fnCostCompare, CardColumnPresets.fnCostGet)); + columns.add(new TableColumnInfo("Color", 50, CardColumnPresets.fnColorCompare, CardColumnPresets.fnColorGet)); + columns.add(new TableColumnInfo("Type", 100, CardColumnPresets.fnTypeCompare, CardColumnPresets.fnTypeGet)); + columns.add(new TableColumnInfo("Stats", 40, CardColumnPresets.fnStatsCompare, CardColumnPresets.fnStatsGet)); + columns.add(new TableColumnInfo("R", 35, CardColumnPresets.fnRarityCompare, CardColumnPresets.fnRarityGet)); + columns.add(new TableColumnInfo("Set", 40, CardColumnPresets.fnSetCompare, CardColumnPresets.fnSetGet)); + columns.add(new TableColumnInfo("AI", 30, CardColumnPresets.fnAiStatusCompare, CardColumnPresets.fnAiStatusGet)); + setupTables(columns, true); + + // TODO use this as soon the deck editor has resizable GUI + // Use both so that when "un"maximizing, the frame isn't tiny + setSize(1024, 740); + setExtendedState(Frame.MAXIMIZED_BOTH); + + // This was an attempt to limit the width of the deck editor to 1400 + // pixels. + /* + * setSize(1024, 740); Rectangle bounds = getBounds(); Dimension screen + * = getToolkit().getScreenSize(); int maxWidth; + * + * if (screen.width >= 1400) { maxWidth = 1400; } else { maxWidth = + * screen.width; } bounds.width = maxWidth; bounds.height = + * screen.height; + * + * setMaximizedBounds(bounds); + */ + }// setupAndDisplay() + + + /** + *

+ * Constructor for Gui_DeckEditor. + *

+ */ + public DeckEditor() { + super(true, true); + try { + jbInit(); + } catch (Exception ex) { + ErrorViewer.showError(ex); + } + } + + /** + *

+ * jbInit. + *

+ * + * @throws java.lang.Exception + * if any. + */ + private void jbInit() throws Exception { + jbInitTables("All Cards", "Deck"); + + // removeButton.setIcon(upIcon); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + removeButton.setFont(new java.awt.Font("Dialog", 0, 13)); + removeButton.setText("Remove from Deck"); + removeButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + removeButton_actionPerformed(e); + } + }); + addButton.setText("Add to Deck"); + addButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + addButton_actionPerformed(e); + } + }); + // addButton.setIcon(downIcon); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + addButton.setFont(new java.awt.Font("Dialog", 0, 13)); + + clearFilterButton.setText("Clear Filter"); + clearFilterButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + clearFilterButton_actionPerformed(e); + } + }); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + clearFilterButton.setFont(new java.awt.Font("Dialog", 0, 13)); + + analysisButton.setText("Deck Analysis"); + analysisButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + analysisButton_actionPerformed(e); + } + }); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + analysisButton.setFont(new java.awt.Font("Dialog", 0, 13)); + + /** + * Type filtering + */ + Font f = new Font("Tahoma", Font.PLAIN, 10); + for (JCheckBox box : filterBoxes.allTypes) { + if (!OldGuiNewGame.useLAFFonts.isSelected()) { box.setFont(f); } + box.setOpaque(false); + } + + /** + * Color filtering + */ + for (JCheckBox box : filterBoxes.allColors) { + box.setOpaque(false); + } + + + // picture.addMouseListener(new CustomListener()); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + statsLabel.setFont(new java.awt.Font("Dialog", 0, 13)); + statsLabel.setText("Total: 0, Creatures: 0, Land: 0"); + // Do not lower statsLabel any lower, we want this to be visible at 1024 + // x 768 screen size + this.setTitle("Deck Editor"); + jScrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + jPanel3.setLayout(gridLayout1); + gridLayout1.setColumns(1); + gridLayout1.setRows(0); + statsLabel2.setText("Total: 0, Creatures: 0, Land: 0"); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + statsLabel2.setFont(new java.awt.Font("Dialog", 0, 13)); + /* + * jLabel1.setText( + * "Click on the column name (like name or color) to sort the cards"); + */ + + Container pane = this.getContentPane(); + MigLayout layout = new MigLayout("fill"); + pane.setLayout(layout); + + // this.getContentPane().add(landCheckBox, + // "cell 0 0, egx checkbox, split 16"); + boolean isFirst = true; + + for (JCheckBox box : filterBoxes.allTypes) { + String growParameter = "grow"; + if (isFirst) { + growParameter = "cell 0 0, egx checkbox, grow, split 14"; + isFirst = false; + } + this.getContentPane().add(box, growParameter); + box.addItemListener(itemListenerUpdatesDisplay); + } + + for (JCheckBox box : filterBoxes.allColors) { + this.getContentPane().add(box, "grow"); + box.addItemListener(itemListenerUpdatesDisplay); + } + + //this.getContentPane().add(filterButton, "wmin 100, hmin 25, wmax 140, hmax 25, grow"); + this.getContentPane().add(clearFilterButton, "wmin 100, hmin 25, wmax 140, hmax 25, grow"); + + this.getContentPane().add(jScrollPane1, "cell 0 2 1 2, pushy, grow"); + + cardView.jbInit(); + this.getContentPane().add(cardView, "cell 1 0 1 8, flowy, grow"); + + + labelFilterName.setText("Name:"); + labelFilterName.setToolTipText("Card names must include the text in this field"); + this.getContentPane().add(labelFilterName, "cell 0 1, split 7"); + this.getContentPane().add(txtCardName, "wmin 100, grow"); + txtCardName.getDocument().addDocumentListener(new OnChangeTextUpdateDisplay()); + +/* txtCardName.getDocument().addDocumentListener(new DocumentListener() { + @Override public void removeUpdate(final DocumentEvent e) { } + @Override public void insertUpdate(final DocumentEvent e) { } + @Override public void changedUpdate(final DocumentEvent e) { updateDisplay(); } + }); + */ + + labelFilterType.setText("Type:"); + labelFilterType.setToolTipText("Card types must include the text in this field"); + this.getContentPane().add(labelFilterType, ""); + this.getContentPane().add(txtCardType, "wmin 100, grow"); + txtCardType.getDocument().addDocumentListener(new OnChangeTextUpdateDisplay()); + labelFilterRules.setText("Text:"); + labelFilterRules.setToolTipText("Card descriptions must include the text in this field"); + this.getContentPane().add(labelFilterRules, ""); + this.getContentPane().add(txtCardRules, "wmin 200, grow"); + txtCardRules.getDocument().addDocumentListener(new OnChangeTextUpdateDisplay()); + + searchSetCombo.removeAllItems(); + searchSetCombo.addItem(""); + for (int i = 0; i < SetInfoUtil.getNameList().size(); i++) + searchSetCombo.addItem(SetInfoUtil.getNameList().get(i)); + searchSetCombo.addItemListener(itemListenerUpdatesDisplay); + + this.getContentPane().add(searchSetCombo, "wmin 150, grow"); + + this.getContentPane().add(statsLabel2, "cell 0 4"); + + this.getContentPane().add(addButton, "w 100, h 49, sg button, cell 0 5, split 4"); + this.getContentPane().add(removeButton, "w 100, h 49, sg button"); + + // jLabel4 is used to push the analysis button to the right + // This will separate this button from the add and remove card buttons + jLabel4.setText(""); + this.getContentPane().add(jLabel4, "wmin 100, grow"); + + this.getContentPane().add(analysisButton, "w 100, h 49, wrap"); + + this.getContentPane().add(jScrollPane2, "cell 0 6, grow"); + this.getContentPane().add(statsLabel, "cell 0 7"); + + topTable.addMouseListener(new MouseAdapter() { + @Override public void mouseClicked(final MouseEvent e) { + if (e.getClickCount() == 2) { addCardFromTopTableToBottom(); } + } + }); + + //javax.swing.JRootPane rootPane = this.getRootPane(); + //rootPane.setDefaultButton(filterButton); + } + + @Override + protected Predicate buildFilter() { + List> rules = new ArrayList>(5); + rules.add(super.buildFilter()); + if (StringUtils.isNotBlank(txtCardName.getText())) { + rules.add(CardRules.Predicates.name(StringOp.CONTAINS, txtCardName.getText())); + } + + if (StringUtils.isNotBlank(txtCardType.getText())) { + rules.add(CardRules.Predicates.joinedType(StringOp.CONTAINS, txtCardType.getText())); + } + + if (StringUtils.isNotBlank(txtCardRules.getText())) { + rules.add(CardRules.Predicates.rules(StringOp.CONTAINS, txtCardRules.getText())); + } + + if (searchSetCombo.getSelectedIndex() != 0) { + String setCode = SetInfoUtil.getCode3ByName(searchSetCombo.getSelectedItem().toString()); + rules.add(CardRules.Predicates.wasPrintedInSet(setCode)); + } + + return rules.size() == 1 ? rules.get(0) : Predicate.and(rules); + } + + void clearFilterButton_actionPerformed(ActionEvent e) { + // disable automatic update triggered by listeners + isFiltersChangeFiringUpdate = false; + + for (JCheckBox box : filterBoxes.allTypes) { if (!box.isSelected()) { box.doClick(); } } + for (JCheckBox box : filterBoxes.allColors) { if (!box.isSelected()) { box.doClick(); } } + + txtCardName.setText(""); + txtCardType.setText(""); + txtCardRules.setText(""); + searchSetCombo.setSelectedIndex(0); + + // restore automatics ... + isFiltersChangeFiringUpdate = true; + // ... and force update + updateDisplay(); + } // clearFilterButton_actionPerformed + + /** + *

+ * addButton_actionPerformed. + *

+ * + * @param e + * a {@link java.awt.event.ActionEvent} object. + */ + void addButton_actionPerformed(ActionEvent e) { + addCardFromTopTableToBottom(); + }// addButton_actionPerformed + + + void addCardFromTopTableToBottom() { + setTitle("Deck Editor : " + customMenu.getDeckName() + " : unsaved"); + + int n = topTable.getSelectedRow(); + if (n != -1) { + CardPrinted c = topModel.rowToCard(n).getKey(); + bottomModel.addCard(c); + bottomModel.resort(); + + if (!customMenu.getGameType().equals(Constant.GameType.Constructed)) { + top.remove(c); + topModel.removeCard(c); + } + fixSelection(topModel, topTable, n); + }// if(valid row) + } + + + /** + *

+ * removeButton_actionPerformed. + *

+ * + * @param e + * a {@link java.awt.event.ActionEvent} object. + */ + void removeButton_actionPerformed(ActionEvent e) { + setTitle("Deck Editor : " + customMenu.getDeckName() + " : unsaved"); + + int n = bottomTable.getSelectedRow(); + if (n != -1) { + CardPrinted c = bottomModel.rowToCard(n).getKey(); + bottomModel.removeCard(c); + + if (!Constant.GameType.Constructed.equals(customMenu.getGameType())) { + topModel.addCard(c); + topModel.resort(); + } + + fixSelection(bottomModel, bottomTable, n); + }// if(valid row) + }// + + // refresh Gui from deck, Gui shows the cards in the deck + /** + *

+ * refreshGui. + *

+ */ + @SuppressWarnings("unused") + // refreshGui + private void refreshGui() { + Deck deck = Constant.Runtime.HumanDeck[0]; + if (deck == null) // this is just a patch, i know + deck = new Deck(Constant.Runtime.GameType[0]); + + topModel.clear(); + bottomModel.clear(); + + bottomModel.addCards(deck.getMain()); + + if (deck.isSealed() || deck.isDraft()) { + topModel.addCards(deck.getSideboard()); // add sideboard to GUI + } else { + topModel.addAllCards(CardDb.instance().getAllUniqueCards()); + } + + topModel.resort(); + bottomModel.resort(); + } // //refreshGui() + + protected class OnChangeTextUpdateDisplay implements DocumentListener { + //private String lastText = ""; + private void onChange() { + //String newValue = getTextFromDocument(e.getDocument(); + //System.out.println(String.format("%s --> %s", lastText, nowText)); + if (isFiltersChangeFiringUpdate) { updateDisplay(); } + } + + private String getTextFromDocument(final Document doc) { + try { + return doc.getText(0, doc.getLength()); + } catch (BadLocationException ex) { + return null; + } + } + + @Override public void insertUpdate(DocumentEvent e) { onChange(); } + @Override public void removeUpdate(DocumentEvent e) { onChange(); } + + // Happend only on ENTER pressed + @Override public void changedUpdate(DocumentEvent e) { } + } + + +} diff --git a/src/main/java/forge/gui/deckeditor/DeckEditorBase.java b/src/main/java/forge/gui/deckeditor/DeckEditorBase.java new file mode 100644 index 00000000000..eeee291d006 --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/DeckEditorBase.java @@ -0,0 +1,210 @@ +package forge.gui.deckeditor; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Image; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.BorderFactory; +import javax.swing.JCheckBox; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.border.Border; +import javax.swing.border.EtchedBorder; +import javax.swing.border.TitledBorder; +import javax.swing.event.MouseInputListener; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; +import javax.swing.filechooser.FileFilter; + +import arcane.ui.CardPanel; + +import net.slightlymagic.maxmtg.Predicate; + +import forge.Card; +import forge.Constant; +import forge.GUI_DeckAnalysis; +import forge.GuiDisplayUtil; +import forge.ImageCache; +import forge.ImagePreviewPanel; +import forge.card.CardPool; +import forge.card.CardPrinted; +import forge.card.CardRules; +import forge.card.CardPoolView; +import forge.gui.game.CardDetailPanel; +import forge.gui.game.CardPicturePanel; +import forge.properties.ForgeProps; +import forge.properties.NewConstants; + +public abstract class DeckEditorBase extends JFrame implements DeckDisplay { + private static final long serialVersionUID = -401223933343539977L; + + //public JCheckBox whiteCheckBox = new GuiFilterCheckBox("white", "White"); + + public final FilterCheckBoxes filterBoxes; + // set this to false when resetting filter from code (like "clearFiltersPressed"), reset when done. + protected boolean isFiltersChangeFiringUpdate = true; + public final CardViewPanel cardView = new CardViewPanel(); + + // CardPools and Table data for top and bottom lists + protected CardPool top; + protected TableModel topModel; + protected JTable topTable = new JTable(); + protected JScrollPane jScrollPane1 = new JScrollPane(); + protected JLabel statsLabel = new JLabel(); + + + protected CardPoolView bottom; + protected TableModel bottomModel; + protected JTable bottomTable = new JTable(); + protected JScrollPane jScrollPane2 = new JScrollPane(); + protected JLabel statsLabel2 = new JLabel(); + + // top shows available card pool + // if constructed, top shows all cards + // if sealed, top shows N booster packs + // if draft, top shows cards that were chosen + public final TableModel getTopTableModel() { return topModel; } + public final CardPool getTop() { return top; } + + // bottom shows cards that the user has chosen for his library + public final CardPoolView getBottom() { return bottomModel.getCards(); } + + protected DeckEditorBase(final boolean useFilters, final boolean areGraphicalFilters) { + filterBoxes = useFilters ? new FilterCheckBoxes(areGraphicalFilters) : null; + } + + protected final void setupTables(List> columns, boolean trackStats ) { + // construct topTable, get all cards + + topModel = new TableModel(cardView, columns); + topModel.addListeners(topTable); + topTable.setModel(topModel); + topModel.resizeCols(topTable); + + // construct bottomModel + bottomModel = new TableModel(cardView, columns); + bottomModel.addListeners(bottomTable); + bottomTable.setModel(bottomModel); + bottomModel.resizeCols(bottomTable); + + if (trackStats) + { + // get stats from deck + bottomModel.addTableModelListener(new TableModelListener() { + public void tableChanged(final TableModelEvent ev) { + CardPoolView deck = bottomModel.getCards(); + statsLabel.setText(getStats(deck)); + } + }); + + // get stats from all cards + topModel.addTableModelListener(new TableModelListener() { + public void tableChanged(final TableModelEvent ev) { + CardPoolView deck = topModel.getCards(); + statsLabel2.setText(getStats(deck)); + } + }); + } + } + + protected final void jbInitTables(String topTitle, String bottomTitle) + { + Color gray = new Color(148, 145, 140); + TitledBorder titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white, gray), topTitle); + TitledBorder titledBorder2 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white, gray), bottomTitle); + this.getContentPane().setLayout(null); + String tableToolTip = "Click on the column name (like name or color) to sort the cards"; + jScrollPane1.setBorder(titledBorder1); + jScrollPane1.setToolTipText(tableToolTip); + jScrollPane2.setBorder(titledBorder2); + jScrollPane2.setToolTipText(tableToolTip); + + jScrollPane2.getViewport().add(bottomTable, null); + jScrollPane1.getViewport().add(topTable, null); + } + + + // This should not be here, but still found no better place + public static String getStats(CardPoolView deck) { + int total = deck.countAll(); + int creature = CardRules.Predicates.Presets.isCreature.aggregate(deck, CardPoolView.fnToCard, CardPoolView.fnToCount); + int land = CardRules.Predicates.Presets.isLand.aggregate(deck, CardPoolView.fnToCard, CardPoolView.fnToCount); + + StringBuffer show = new StringBuffer(); + show.append("Total - ").append(total).append(", Creatures - ").append(creature).append(", Land - ").append(land); + String[] color = Constant.Color.onlyColors; + List> predicates = CardRules.Predicates.Presets.colors; + for (int i = 0; i < color.length; ++i) { + show.append(String.format(", %s - %d", color[i], predicates.get(i).count(deck, CardPoolView.fnToCard))); + } + + return show.toString(); + }// getStats() + + // THIS IS HERE FOR OVERLOADING!!!1 + // or may be return abstract getFilter from derived class + this filter ... virtual protected member, but later + protected Predicate buildFilter() { + if (null == filterBoxes) { + return Predicate.getTrue(CardRules.class); + } + return filterBoxes.buildFilter(); + } + + + void analysisButton_actionPerformed(ActionEvent e) { + if (bottomModel.getRowCount() == 0) { + JOptionPane.showMessageDialog(null, "Cards in deck not found.", "Analysis Deck", + JOptionPane.INFORMATION_MESSAGE); + } else { + DeckEditorBase g = DeckEditorBase.this; + GUI_DeckAnalysis dAnalysis = new GUI_DeckAnalysis(g, bottomModel); + dAnalysis.setVisible(true); + g.setEnabled(false); + } + } + + protected ItemListener itemListenerUpdatesDisplay = new ItemListener() { + public void itemStateChanged(ItemEvent e) { + if (isFiltersChangeFiringUpdate) { updateDisplay(); } + } + }; + + public void updateDisplay() { + topModel.clear(); + Predicate currentFilter = buildFilter(); + topModel.addCards(currentFilter.select(top, CardPoolView.fnToCard)); + topModel.resort(); + } + + + + + + // Call this after deleting an item from table + protected void fixSelection(TableModel model, JTable table, int rowLastSelected) { + // 3 cases: 0 cards left, select the same row, select prev row + int cntRowsAbove = model.getRowCount(); + if (cntRowsAbove != 0) { + if (cntRowsAbove == rowLastSelected) { rowLastSelected--; } // move selection away from the last, already missing, option + table.setRowSelectionInterval(rowLastSelected, rowLastSelected); + } + } + +} diff --git a/src/main/java/forge/Gui_DeckEditor_Menu.java b/src/main/java/forge/gui/deckeditor/DeckEditorMenu.java similarity index 74% rename from src/main/java/forge/Gui_DeckEditor_Menu.java rename to src/main/java/forge/gui/deckeditor/DeckEditorMenu.java index 89ce5886ebf..7e29153b3e4 100644 --- a/src/main/java/forge/Gui_DeckEditor_Menu.java +++ b/src/main/java/forge/gui/deckeditor/DeckEditorMenu.java @@ -1,6 +1,17 @@ -package forge; +package forge.gui.deckeditor; +import forge.AllZone; +import forge.Card; +import forge.CardList; +import forge.Command; +import forge.Constant; +import forge.Constant.GameType; +import forge.card.CardRules; +import forge.card.CardDb; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; import forge.deck.Deck; import forge.deck.DeckManager; import forge.deck.DownloadDeck; @@ -14,6 +25,7 @@ import forge.properties.NewConstants.LANG.Gui_DownloadPictures.ERRORS; import javax.swing.*; import javax.swing.filechooser.FileFilter; + import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; @@ -26,6 +38,7 @@ import java.util.Collection; import java.util.Collections; //import java.util.HashMap; //import java.util.Map; +import java.util.Map.Entry; /** *

Gui_DeckEditor_Menu class.

@@ -33,7 +46,7 @@ import java.util.Collections; * @author Forge * @version $Id$ */ -public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { +public class DeckEditorMenu extends JMenuBar implements NewConstants { /** Constant serialVersionUID=-4037993759604768755L */ private static final long serialVersionUID = -4037993759604768755L; @@ -63,7 +76,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * @param gameType a {@link java.lang.String} object. * @since 1.0.15 */ - public void setCurrentGameType(String gameType) { + public final void setCurrentGameType(final String gameType) { currentGameType = gameType; } @@ -76,10 +89,10 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { /** *

Constructor for Gui_DeckEditor_Menu.

* - * @param in_display a {@link forge.DeckDisplay} object. + * @param in_display a {@link forge.gui.deckeditor.DeckDisplay} object. * @param exit a {@link forge.Command} object. */ - public Gui_DeckEditor_Menu(DeckDisplay in_display, Command exit) { + public DeckEditorMenu(final DeckDisplay in_display, final Command exit) { deckDisplay = in_display; exitCommand = exit; @@ -89,13 +102,12 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { setDeckData("", false); setupMenu(); - setupFilterMenu(); setupSortMenu(); JMenu bugMenu = new JMenu("Report Bug"); JMenuItem bugReport = new JMenuItem("Report Bug"); bugReport.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { BugzReporter br = new BugzReporter(); br.setVisible(true); } @@ -104,64 +116,6 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { this.add(bugMenu); } - /** - *

setupFilterMenu.

- */ - private void setupFilterMenu() { - JMenuItem filter = new JMenuItem("New filter"); - JMenuItem clearfilter = new JMenuItem("Clear filter"); - JMenu menu = new JMenu("Filter"); - menu.add(filter); - menu.add(clearfilter); - this.add(menu); - - filter.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; - GuiFilter filt = new GuiFilter(g, deckDisplay); - g.setEnabled(false); - filt.setVisible(true); - } - }); - clearfilter.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - - //CardList all = AllZone.getCardFactory().getAllCards(); - //deckDisplay.updateDisplay(all, deckDisplay.getBottom()); - deckDisplay.updateDisplay(deckDisplay.getTop(), deckDisplay.getBottom()); - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; - g.blackCheckBox.setSelected(true); - g.blackCheckBox.setEnabled(true); - g.blueCheckBox.setSelected(true); - g.blueCheckBox.setEnabled(true); - g.greenCheckBox.setSelected(true); - g.greenCheckBox.setEnabled(true); - g.redCheckBox.setSelected(true); - g.redCheckBox.setEnabled(true); - g.whiteCheckBox.setSelected(true); - g.whiteCheckBox.setEnabled(true); - g.colorlessCheckBox.setSelected(true); - g.colorlessCheckBox.setEnabled(true); - g.artifactCheckBox.setSelected(true); - g.artifactCheckBox.setEnabled(true); - g.creatureCheckBox.setSelected(true); - g.creatureCheckBox.setEnabled(true); - g.enchantmentCheckBox.setSelected(true); - g.enchantmentCheckBox.setEnabled(true); - g.instantCheckBox.setSelected(true); - g.instantCheckBox.setEnabled(true); - g.landCheckBox.setSelected(true); - g.landCheckBox.setEnabled(true); - g.planeswalkerCheckBox.setSelected(true); - g.planeswalkerCheckBox.setEnabled(true); - g.sorceryCheckBox.setSelected(true); - g.sorceryCheckBox.setEnabled(true); - - } - }); - - } - /** *

setupSortMenu.

@@ -196,21 +150,21 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { name.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { //index 1 sorts by card name - for more info see TableSorter // 0 1 2 3 4 5 6 //private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "Rarity"}; - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; + DeckEditor g = (DeckEditor) deckDisplay; g.getTopTableModel().sort(1, true); } }); cost.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { // 0 1 2 3 4 5 6 //private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "Rarity"}; - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; + DeckEditor g = (DeckEditor) deckDisplay; //sort by type, color, cost g.getTopTableModel().sort(4, true); @@ -220,10 +174,10 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); color.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { // 0 1 2 3 4 5 6 //private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "Rarity"}; - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; + DeckEditor g = (DeckEditor) deckDisplay; //sort by type, cost, color g.getTopTableModel().sort(4, true); @@ -233,10 +187,10 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); type.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { // 0 1 2 3 4 5 6 //private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "Rarity"}; - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; + DeckEditor g = (DeckEditor) deckDisplay; //sort by cost, color, type g.getTopTableModel().sort(2, true); @@ -246,10 +200,10 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); stats.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { // 0 1 2 3 4 5 6 //private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "Rarity"}; - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; + DeckEditor g = (DeckEditor) deckDisplay; g.getTopTableModel().sort(4, true); g.getTopTableModel().sort(2, true); @@ -259,10 +213,10 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); rarity.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { // 0 1 2 3 4 5 6 //private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "Rarity"}; - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; + DeckEditor g = (DeckEditor) deckDisplay; //sort by cost, type, color, rarity g.getTopTableModel().sort(2, true); @@ -273,10 +227,10 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); newFirst.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { // 0 1 2 3 4 5 6 //private String column[] = {"Qty", "Name", "Cost", "Color", "Type", "Stats", "Rarity"}; - Gui_DeckEditor g = (Gui_DeckEditor) deckDisplay; + DeckEditor g = (DeckEditor) deckDisplay; g.getTopTableModel().sort(99, true); } @@ -284,16 +238,6 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }//setupSortMenu() - /** - *

populateShop.

- * - * @param shop a {@link forge.CardList} object. - * @param owned a {@link forge.CardList} object. - */ - public void populateShop(CardList shop, CardList owned) { - - deckDisplay.updateDisplay(shop, owned); - } /** *

newConstructed.

@@ -310,8 +254,12 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { setDeckData("", false); // This is an expensive heap operation. - CardList allCards = new CardList(AllZone.getCardFactory()); - deckDisplay.updateDisplay(allCards, new CardList()); + + + CardPool allCards = new CardPool(); + allCards.addAllCards(CardDb.instance().getAllUniqueCards()); + + deckDisplay.setDecks(allCards, new CardPoolView()); }//new constructed /** @@ -329,17 +277,18 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { setDeckData("", false); CardList random = new CardList(AllZone.getCardFactory().getRandomCombinationWithoutRepetition(15 * 5)); - random.add(AllZone.getCardFactory().getCard("Forest", AllZone.getHumanPlayer())); random.add(AllZone.getCardFactory().getCard("Island", AllZone.getHumanPlayer())); random.add(AllZone.getCardFactory().getCard("Plains", AllZone.getHumanPlayer())); random.add(AllZone.getCardFactory().getCard("Mountain", AllZone.getHumanPlayer())); random.add(AllZone.getCardFactory().getCard("Swamp", AllZone.getHumanPlayer())); - random.add(AllZone.getCardFactory().getCard("Terramorphic Expanse", AllZone.getHumanPlayer())); + CardPool cpRandom = new CardPool(); + for (Card c : random) { cpRandom.add(CardDb.instance().getCard(c)); } - deckDisplay.updateDisplay(random, new CardList()); + + deckDisplay.setDecks(cpRandom, new CardPoolView()); }//new sealed @@ -360,8 +309,11 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { GenerateConstructedDeck gen = new GenerateConstructedDeck(); // This is an expensive heap operation. - CardList allCards = new CardList(AllZone.getCardFactory()); - deckDisplay.updateDisplay(allCards, gen.generateDeck()); + CardPool allCards = new CardPool( CardDb.instance().getAllUniqueCards() ); + + CardPool generated = new CardPool(); + for (Card c : gen.generateDeck()) { generated.add( CardDb.instance().getCard(c)); } + deckDisplay.setDecks(allCards, generated); }//new sealed @@ -623,14 +575,9 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { } - Card c = new Card(); - CardList trueList = new CardList(); + CardPool trueList = new CardPool(); for (int i = 0; i < trueCount; i++) { - for (int k = 0; k < Integer.parseInt(trueNumber[i]); k++) { - c = download.getCardDownload(c, trueName[i]); - trueList.add(c); - } - + trueList.add(CardDb.instance().getCard(trueName[i]), Integer.parseInt(trueNumber[i])); } StringBuffer falseCards = new StringBuffer(); @@ -639,7 +586,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { } - deckDisplay.updateDisplay(deckDisplay.getTop(), trueList); + deckDisplay.setDecks(deckDisplay.getTop(), trueList); if (falseCount == 0) { JOptionPane.showMessageDialog(null, "Deck downloads.", "Information", @@ -683,7 +630,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { //and the other 7 are the computer's deck if (currentGameType.equals(Constant.GameType.Draft)) { //read all draft decks - Deck d[] = deckManager.getDraftDeck(currentDeckName); + Deck[] d = deckManager.getDraftDeck(currentDeckName); //replace your deck d[0] = deck; @@ -696,117 +643,9 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { throw new RuntimeException("Gui_DeckEditor_Menu : exportDeck() error, " + ex); } - exportDeckText(deck, filename.getAbsolutePath()); }//exportDeck() - // @SuppressWarnings("unchecked") - // TableSorter type saftey - /** - *

exportDeckText.

- * - * @param aDeck a {@link forge.deck.Deck} object. - * @param filename a {@link java.lang.String} object. - */ - private void exportDeckText(Deck aDeck, String filename) { - //convert Deck into CardList - CardList all = new CardList(); - for (int i = 0; i < aDeck.countMain(); i++) { - String cardName = aDeck.getMain(i); - - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - } - - Card c = AllZone.getCardFactory().getCard(cardName, null); - - all.add(c); - } - - //sort by card name - all.sort(new TableSorter(all, 1, true)); - - //remove all copies of cards - //make a singleton - CardList noCopies = new CardList(); - for (int i = 0; i < all.size(); i++) { - Card c = all.get(i); - - if (!noCopies.containsName(c.getName())) { - noCopies.add(c); - } - } - - - StringBuffer text = new StringBuffer(); - String newLine = "\r\n"; - int count = 0; - - text.append(all.size()).append(" Total Cards").append(newLine).append(newLine); - - //creatures - text.append(all.getType("Creature").size()).append(" Creatures").append(newLine); - text.append("-------------").append(newLine); - - for (int i = 0; i < noCopies.size(); i++) { - Card c = noCopies.get(i); - if (c.isCreature()) { - count = all.getName(c.getName()).size(); - text.append(count).append("x ").append(c.getName()).append(newLine); - } - } - - //count spells, arg! this is tough - CardListFilter cf = new CardListFilter() { - public boolean addCard(Card c) { - return !(c.isCreature() || c.isLand()); - } - };//CardListFilter - count = all.filter(cf).size(); - - //spells - text.append(newLine).append(count).append(" Spells").append(newLine); - text.append("----------").append(newLine); - - for (int i = 0; i < noCopies.size(); i++) { - Card c = noCopies.get(i); - if (!(c.isCreature() || c.isLand())) { - count = all.getName(c.getName()).size(); - text.append(count).append("x ").append(c.getName()).append(newLine); - } - } - - //land - text.append(newLine).append(all.getType("Land").size()).append(" Land").append(newLine); - text.append("--------").append(newLine); - - for (int i = 0; i < noCopies.size(); i++) { - Card c = noCopies.get(i); - if (c.isLand()) { - count = all.getName(c.getName()).size(); - text.append(count).append("x ").append(c.getName()).append(newLine); - } - } - - //remove ".deck" extension - int cut = filename.indexOf("."); - filename = filename.substring(0, cut); - - try { - FileWriter writer = new FileWriter(filename + ".txt"); - writer.write(text.toString()); - - writer.flush(); - writer.close(); - } catch (Exception ex) { - ErrorViewer.showError(ex); - throw new RuntimeException("Gui_DeckEditor_Menu : exportDeckText() error, " + ex.getMessage() + " : " - + Arrays.toString(ex.getStackTrace())); - } - }//exportDeckText() - - /** *

getExportFilename.

* @@ -869,33 +708,11 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * * @param deck a {@link forge.deck.Deck} object. */ - private void showConstructedDeck(Deck deck) { + private void showConstructedDeck(final Deck deck) { setDeckData(deck.getName(), true); - CardList main = new CardList(); - for (int i = 0; i < deck.countMain(); i++) { - String cardName = deck.getMain(i); - String setCode = ""; - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - setCode = s[1]; - } - - Card c = AllZone.getCardFactory().getCard(cardName, AllZone.getHumanPlayer()); - - if (!setCode.equals("")) { - c.setCurSetCode(setCode); - } else if ((c.getSets().size() > 0)) // && card.getCurSetCode().equals("")) - { - c.setRandomSetCode(); - } - - main.add(c); - } - // This is an expensive heap operation. - CardList allCards = new CardList(AllZone.getCardFactory()); - deckDisplay.updateDisplay(allCards, main); + CardPool allCards = new CardPool(CardDb.instance().getAllUniqueCards()); + deckDisplay.setDecks(allCards, deck.getMain()); }//showConstructedDeck() /** @@ -929,41 +746,10 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * * @param deck a {@link forge.deck.Deck} object. */ - public void showSealedDeck(Deck deck) { + public final void showSealedDeck(final Deck deck) { setDeckData(deck.getName(), true); currentDeckPlayerType = deck.getMetadata("PlayerType"); - - CardList top = new CardList(); - if (deck.countSideboard() > 0) { - for (int i = 0; i < deck.countSideboard(); i++) { - String cardName = deck.getSideboard(i); - String setCode = ""; - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - setCode = s[1]; - } - Card c = AllZone.getCardFactory().getCard(cardName, AllZone.getHumanPlayer()); - c.setCurSetCode(setCode); - top.add(c); - } - } - CardList bottom = new CardList(); - if (deck.countMain() > 0) { - for (int i = 0; i < deck.countMain(); i++) { - String cardName = deck.getMain(i); - String setCode = ""; - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - setCode = s[1]; - } - Card c = AllZone.getCardFactory().getCard(cardName, AllZone.getHumanPlayer()); - c.setCurSetCode(setCode); - bottom.add(c); - } - } - deckDisplay.updateDisplay(top, bottom); + deckDisplay.setDecks(deck.getSideboard(), deck.getMain()); }//showSealedDeck() /** @@ -993,32 +779,9 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * * @param deck a {@link forge.deck.Deck} object. */ - private void showDraftDeck(Deck deck) { + private void showDraftDeck(final Deck deck) { setDeckData(deck.getName(), true); - - CardList top = new CardList(); - for (int i = 0; i < deck.countSideboard(); i++) { - String cardName = deck.getSideboard(i); - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - } - - top.add(AllZone.getCardFactory().getCard(cardName, AllZone.getHumanPlayer())); - } - - CardList bottom = new CardList(); - for (int i = 0; i < deck.countMain(); i++) { - String cardName = deck.getMain(i); - if (cardName.contains("|")) { - String s[] = cardName.split("\\|", 2); - cardName = s[0]; - } - - bottom.add(AllZone.getCardFactory().getCard(cardName, AllZone.getHumanPlayer())); - } - - deckDisplay.updateDisplay(top, bottom); + deckDisplay.setDecks(deck.getSideboard(), deck.getMain()); }//showDraftDeck() /** @@ -1100,13 +863,13 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { } setDeckData("", true); - deckDisplay.updateDisplay(new CardList(), new CardList()); + deckDisplay.setDecks(new CardPoolView(), new CardPoolView()); }//delete /** *

close.

*/ - public void close() { + public final void close() { if (debugPrint) { System.out.println("Close"); } @@ -1124,7 +887,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * @param deckName a {@link java.lang.String} object. * @param in_isDeckSaved a boolean. */ - private void setDeckData(String deckName, boolean in_isDeckSaved) { + private void setDeckData(final String deckName, final boolean in_isDeckSaved) { currentDeckName = deckName; isDeckSaved = in_isDeckSaved; @@ -1136,7 +899,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * * @param s a {@link java.lang.String} object. */ - public void setTitle(String s) { + public final void setTitle(final String s) { deckDisplay.setTitle(s); } @@ -1145,7 +908,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * * @return a {@link java.lang.String} object. */ - public String getDeckName() { + public final String getDeckName() { return currentDeckName; } @@ -1154,7 +917,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * * @return a {@link java.lang.String} object. */ - public String getGameType() { + public final String getGameType() { return currentGameType; } @@ -1163,7 +926,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * * @return a boolean. */ - public boolean isDeckSaved() { + public final boolean isDeckSaved() { return isDeckSaved; } @@ -1203,7 +966,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * @param in a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ - private String cleanString(String in) { + private String cleanString(final String in) { char[] c = in.toCharArray(); StringBuilder sb = new StringBuilder(); @@ -1222,7 +985,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * @param deckType a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ - private String getUserInput_OpenDeck(String deckType) { + private String getUserInput_OpenDeck(final String deckType) { ArrayList choices = getDeckNames(deckType); if (choices.size() == 0) { JOptionPane.showMessageDialog(null, "No decks found", "Open Deck", JOptionPane.PLAIN_MESSAGE); @@ -1246,7 +1009,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { * @param deckType a {@link java.lang.String} object. * @return a {@link java.util.ArrayList} object. */ - private ArrayList getDeckNames(String deckType) { + private ArrayList getDeckNames(final String deckType) { ArrayList list = new ArrayList(); //only get decks according to the OldGuiNewGame screen option @@ -1276,29 +1039,11 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { private Deck getDeck() { Deck deck = new Deck(currentGameType); deck.setName(currentDeckName); - CardList list; - String cardName; - - //always move "bottom" to main - list = deckDisplay.getBottom(); - for (int i = 0; i < list.size(); i++) { - if (!list.get(i).getCurSetCode().equals("")) { - cardName = list.get(i).getName() + "|" + list.get(i).getCurSetCode(); - } else { - cardName = list.get(i).getName(); - } - deck.addMain(AllZone.getNameChanger().getOriginalName(cardName)); - } + deck.addMain(deckDisplay.getBottom()); //if sealed or draft, move "top" to sideboard if (!currentGameType.equals(Constant.GameType.Constructed)) { - list = deckDisplay.getTop(); - for (int i = 0; i < list.size(); i++) { - cardName = list.get(i).getName() + "|" + list.get(i).getCurSetCode(); - deck.addSideboard(AllZone.getNameChanger().getOriginalName(cardName)); - } - if (currentGameType.equals(Constant.GameType.Sealed)) - deck.addMetaData("PlayerType", currentDeckPlayerType); + deck.addSideboard(deckDisplay.getTop()); } return deck; }//getDeck() @@ -1365,7 +1110,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { //add listeners exportDeck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1381,7 +1126,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { importDeck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1396,7 +1141,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); downloadDeck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1411,7 +1156,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); newConstructed.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1427,7 +1172,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { newRandomConstructed.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1443,7 +1188,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { newGenerateConstructed.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1489,7 +1234,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); */ openConstructed.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1504,7 +1249,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); openSealed.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1519,7 +1264,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); openDraft.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1534,7 +1279,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); save.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1549,7 +1294,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); saveAs.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1564,7 +1309,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); delete.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -1579,7 +1324,7 @@ public class Gui_DeckEditor_Menu extends JMenuBar implements NewConstants { }); close.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { + public void actionPerformed(final ActionEvent ev) { try { SwingUtilities.invokeLater(new Runnable() { public void run() { diff --git a/src/main/java/forge/gui/deckeditor/DeckEditorQuest.java b/src/main/java/forge/gui/deckeditor/DeckEditorQuest.java new file mode 100644 index 00000000000..dd5418d7bb2 --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/DeckEditorQuest.java @@ -0,0 +1,360 @@ +package forge.gui.deckeditor; + +import forge.AllZone; +import forge.Card; +import forge.CardList; +import forge.Command; +import forge.Constant; +import forge.GUI_DeckAnalysis; +import forge.GuiDisplayUtil; +import forge.ImageCache; +import forge.ImagePreviewPanel; +import forge.MyRandom; +import forge.Constant.GameType; +import forge.Constant.Runtime; +import forge.card.CardRules; +import forge.card.CardDb; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; +import forge.deck.Deck; +import forge.error.ErrorViewer; +import forge.gui.game.CardDetailPanel; +import forge.gui.game.CardPicturePanel; +import forge.properties.ForgeProps; +import forge.properties.NewConstants; +import forge.view.swing.OldGuiNewGame; + +import javax.swing.*; +import javax.swing.border.Border; +import javax.swing.border.EtchedBorder; +import javax.swing.border.TitledBorder; +import javax.swing.event.MouseInputAdapter; +import javax.swing.event.MouseInputListener; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; +import javax.swing.filechooser.FileFilter; + +import net.slightlymagic.maxmtg.Predicate; + +import java.awt.*; +import java.awt.event.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.ArrayList; +import java.util.Map.Entry; +import java.util.Random; + +//import forge.quest.data.QuestBoosterPack; + +/** + *

+ * Gui_Quest_DeckEditor class. + *

+ * + * @author Forge + * @version $Id$ + */ +public class DeckEditorQuest extends DeckEditorBase implements NewConstants { + /** Constant serialVersionUID=152061168634545L */ + private static final long serialVersionUID = 152061168634545L; + + DeckEditorQuestMenu customMenu; + + // private ImageIcon upIcon = Constant.IO.upIcon; + // private ImageIcon downIcon = Constant.IO.downIcon; + + private JButton addButton = new JButton(); + private JButton removeButton = new JButton(); + private JButton analysisButton = new JButton(); + + private GridLayout gridLayout1 = new GridLayout(); + + private JLabel jLabel1 = new JLabel(); + + /** {@inheritDoc} */ + @Override + public void setTitle(String message) { + super.setTitle(message); + } + + /** {@inheritDoc} */ + public void setDecks(CardPoolView top, CardPoolView bottom) { + + this.top = new CardPool( top ); + this.bottom = bottom; + + topModel.clear(); + topModel.addCards(top); + + bottomModel.clear(); + bottomModel.addCards(bottom); + + topModel.resort(); + bottomModel.resort(); + }// updateDisplay + + + /** + *

+ * show. + *

+ * + * @param exitCommand + * a {@link forge.Command} object. + */ + public void show(final Command exitCommand) { + final Command exit = new Command() { + private static final long serialVersionUID = -7428793574300520612L; + + public void execute() { + DeckEditorQuest.this.dispose(); + exitCommand.execute(); + } + }; + + // do not change this!!!! + this.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent ev) { + customMenu.close(); + } + }); + + setup(); + + customMenu = new DeckEditorQuestMenu(this, exit); + this.setJMenuBar(customMenu); + + forge.quest.data.QuestData questData = AllZone.getQuestData(); + Deck deck = null; + + // open deck that the player used if QuestData has it + if (Constant.Runtime.HumanDeck[0] != null + && questData.getDeckNames().contains(Constant.Runtime.HumanDeck[0].getName())) { + deck = questData.getDeck(Constant.Runtime.HumanDeck[0].getName()); + } else { + deck = new Deck(Constant.GameType.Sealed); + deck.setName(""); + } + + // tell Gui_Quest_DeckEditor the name of the deck + customMenu.setPlayerDeckName(deck.getName()); + + CardPoolView bottomPool = deck.getMain(); + CardPool cardpool = new CardPool(); + cardpool.addAll(AllZone.getQuestData().getCardpool()); + + // remove bottom cards that are in the deck from the card pool + cardpool.removeAll(bottomPool); + + // show cards, makes this user friendly, lol, well may, ha + setDecks(cardpool, bottomPool); + + // this affects the card pool + topModel.sort(4, true);// sort by type + topModel.sort(3, true);// then sort by color + + bottomModel.sort(1, true); + }// show(Command) + + + /** + *

+ * setup. + *

+ */ + public void setup() { + List> columns = new ArrayList>(); + columns.add(new TableColumnInfo("Qty", 30, CardColumnPresets.fnQtyCompare, CardColumnPresets.fnQtyGet)); + columns.add(new TableColumnInfo("Name", 180, CardColumnPresets.fnNameCompare, CardColumnPresets.fnNameGet)); + columns.add(new TableColumnInfo("Cost", 70, CardColumnPresets.fnCostCompare, CardColumnPresets.fnCostGet)); + columns.add(new TableColumnInfo("Color", 50, CardColumnPresets.fnColorCompare, CardColumnPresets.fnColorGet)); + columns.add(new TableColumnInfo("Type", 100, CardColumnPresets.fnTypeCompare, CardColumnPresets.fnTypeGet)); + columns.add(new TableColumnInfo("Stats", 40, CardColumnPresets.fnStatsCompare, CardColumnPresets.fnStatsGet)); + columns.add(new TableColumnInfo("R", 35, CardColumnPresets.fnRarityCompare, CardColumnPresets.fnRarityGet)); + columns.add(new TableColumnInfo("Set", 40, CardColumnPresets.fnSetCompare, CardColumnPresets.fnSetGet)); + // Add NEW column here + setupTables(columns, true); + + + setSize(1024, 768); + this.setResizable(false); + Dimension screen = getToolkit().getScreenSize(); + Rectangle bounds = getBounds(); + bounds.width = 1024; + bounds.height = 768; + bounds.x = (screen.width - bounds.width) / 2; + bounds.y = (screen.height - bounds.height) / 2; + setBounds(bounds); + + // TODO use this as soon the deck editor has resizable GUI + // //Use both so that when "un"maximizing, the frame isn't tiny + // setSize(1024, 740); + // setExtendedState(Frame.MAXIMIZED_BOTH); + }// setupAndDisplay() + + public DeckEditorQuest() { + super(true, false); + try { + jbInit(); + } catch (Exception ex) { + ErrorViewer.showError(ex); + } + } + + + private void jbInit() throws Exception { + + jbInitTables("All Cards", "Your deck"); + + jScrollPane1.setBounds(new Rectangle(19, 20, 726, 346)); + jScrollPane2.setBounds(new Rectangle(19, 458, 726, 218)); + + removeButton.setBounds(new Rectangle(180, 403, 146, 49)); + // removeButton.setIcon(upIcon); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + removeButton.setFont(new java.awt.Font("Dialog", 0, 13)); + removeButton.setText("Remove Card"); + removeButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + removeButtonActionPerformed(e); + } + }); + addButton.setText("Add Card"); + addButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + addButtonActionPerformed(e); + } + }); + // addButton.setIcon(downIcon); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + addButton.setFont(new java.awt.Font("Dialog", 0, 13)); + addButton.setBounds(new Rectangle(23, 403, 146, 49)); + + analysisButton.setText("Deck Analysis"); + analysisButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(ActionEvent e) { + analysisButton_actionPerformed(e); + } + }); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + analysisButton.setFont(new java.awt.Font("Dialog", 0, 13)); + analysisButton.setBounds(new Rectangle(578, 426, 166, 25)); + + cardView.jbInit(); + + + /** + * Type filtering + */ + + filterBoxes.land.setBounds(340, 400, 48, 20); + filterBoxes.creature.setBounds(385, 400, 65, 20); + filterBoxes.sorcery.setBounds(447, 400, 62, 20); + filterBoxes.instant.setBounds(505, 400, 60, 20); + filterBoxes.planeswalker.setBounds(558, 400, 85, 20); + filterBoxes.artifact.setBounds(638, 400, 58, 20); + filterBoxes.enchantment.setBounds(692, 400, 80, 20); + + Font f = new Font("Tahoma", Font.PLAIN, 10); + for (JCheckBox box : filterBoxes.allTypes) { + if (!OldGuiNewGame.useLAFFonts.isSelected()) { box.setFont(f); } + box.setOpaque(false); + box.addItemListener(itemListenerUpdatesDisplay); + } + + /** + * Color filtering + */ + filterBoxes.white.setBounds(340, 430, 40, 20); + filterBoxes.blue.setBounds(380, 430, 40, 20); + filterBoxes.black.setBounds(420, 430, 40, 20); + filterBoxes.red.setBounds(460, 430, 40, 20); + filterBoxes.green.setBounds(500, 430, 40, 20); + filterBoxes.colorless.setBounds(540, 430, 40, 20); + + for (JCheckBox box : filterBoxes.allColors) { + box.setOpaque(false); + box.addItemListener(itemListenerUpdatesDisplay); + } + /** + * Other + */ + cardView.setBounds(new Rectangle(765, 23, 239, 687)); + + if (!OldGuiNewGame.useLAFFonts.isSelected()) + statsLabel.setFont(new java.awt.Font("Dialog", 0, 14)); + statsLabel.setText("Total - 0, Creatures - 0 Land - 0"); + statsLabel.setBounds(new Rectangle(19, 672, 720, 31)); + // Do not lower statsLabel any lower, we want this to be visible at 1024 + // x 768 screen size + this.setTitle("Deck Editor"); + gridLayout1.setColumns(1); + gridLayout1.setRows(0); + statsLabel2.setBounds(new Rectangle(19, 365, 720, 31)); + statsLabel2.setText("Total - 0, Creatures - 0 Land - 0"); + if (!OldGuiNewGame.useLAFFonts.isSelected()) + statsLabel2.setFont(new java.awt.Font("Dialog", 0, 14)); + jLabel1.setText("Click on the column name (like name or color) to sort the cards"); + jLabel1.setBounds(new Rectangle(20, 1, 400, 19)); + + this.getContentPane().add(jScrollPane1, null); + this.getContentPane().add(jScrollPane2, null); + this.getContentPane().add(addButton, null); + this.getContentPane().add(removeButton, null); + this.getContentPane().add(analysisButton, null); + this.getContentPane().add(statsLabel2, null); + this.getContentPane().add(statsLabel, null); + this.getContentPane().add(jLabel1, null); + this.getContentPane().add(cardView, null); + + for (JCheckBox box : filterBoxes.allTypes) { + this.getContentPane().add(box, null); + } + + for (JCheckBox box : filterBoxes.allColors) { + this.getContentPane().add(box, null); + } + } + + + final void addButtonActionPerformed(final ActionEvent e) { + setTitle("Deck Editor : " + customMenu.getDeckName() + " : unsaved"); + + int n = topTable.getSelectedRow(); + if (n == -1) { return; } + + CardPrinted c = topModel.rowToCard(n).getKey(); + bottomModel.addCard(c); + bottomModel.resort(); + + // remove from cardpool + top.remove(c); + + // redraw top after deletion + updateDisplay(); + fixSelection(topModel, topTable, n); + } + + + final void removeButtonActionPerformed(final ActionEvent e) { + setTitle("Deck Editor : " + customMenu.getDeckName() + " : unsaved"); + + int n = bottomTable.getSelectedRow(); + if (n == -1) { return; } + + CardPrinted c = bottomModel.rowToCard(n).getKey(); + bottomModel.removeCard(c); + fixSelection(bottomModel, bottomTable, n); + + top.add(c); + updateDisplay(); + } + +} diff --git a/src/main/java/forge/gui/deckeditor/DeckEditorQuestMenu.java b/src/main/java/forge/gui/deckeditor/DeckEditorQuestMenu.java new file mode 100644 index 00000000000..7519b39aa70 --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/DeckEditorQuestMenu.java @@ -0,0 +1,614 @@ +package forge.gui.deckeditor; + + +import forge.AllZone; +import forge.Command; +import forge.Constant; +import forge.Constant.GameType; +import forge.card.CardCoreType; +import forge.card.CardRules; +import forge.card.CardDb; +import forge.card.CardRules.Predicates; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; +import forge.deck.Deck; +import forge.deck.DeckManager; +import forge.error.ErrorViewer; +import forge.gui.GuiUtils; +import forge.gui.ListChooser; +import forge.quest.data.QuestBattleManager; + +import javax.swing.*; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.filechooser.FileFilter; + +import org.apache.commons.lang3.StringUtils; +import org.apache.tools.ant.taskdefs.PathConvert.MapEntry; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map.Entry; +import java.util.Stack; + + +//presumes AllZone.getQuestData() is not null +/** + *

Gui_Quest_DeckEditor_Menu class.

+ * + * @author Forge + * @version $Id$ + */ +public class DeckEditorQuestMenu extends JMenuBar { + /** Constant serialVersionUID=-4052319220021158574L */ + private static final long serialVersionUID = -4052319220021158574L; + + //this should be false in the public version + //if true, the Quest Deck editor will let you edit the computer's decks + private final boolean canEditComputerDecks; + + /** Constant deckEditorName="Deck Editor" */ + private static final String deckEditorName = "Deck Editor"; + + //used for import and export, try to made the gui user friendly + /** Constant previousDirectory */ + private static File previousDirectory = null; + + private Command exitCommand; + private forge.quest.data.QuestData questData; + private Deck currentDeck; + + //the class DeckDisplay is in the file "Gui_DeckEditor_Menu.java" + private DeckDisplay deckDisplay; + + + /** + *

Constructor for Gui_Quest_DeckEditor_Menu.

+ * + * @param d a {@link forge.gui.deckeditor.DeckDisplay} object. + * @param exit a {@link forge.Command} object. + */ + public DeckEditorQuestMenu(DeckDisplay d, Command exit) { + //is a file named "edit" in this directory + //lame but it works, I don't like 2 versions of MTG Forge floating around + //one that lets you edit the AI decks and one that doesn't + File f = new File("edit"); + if (f.exists()) canEditComputerDecks = true; + else canEditComputerDecks = false; + + deckDisplay = d; + d.setTitle(deckEditorName); + + questData = AllZone.getQuestData(); + + exitCommand = exit; + + setupMenu(); + } + + + + /** + *

addImportExport.

+ * + * @param menu a {@link javax.swing.JMenu} object. + * @param isHumanMenu a boolean. + */ + private void addImportExport(JMenu menu, final boolean isHumanMenu) { + JMenuItem import2 = new JMenuItem("Import"); + JMenuItem export = new JMenuItem("Export"); + + import2.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent a) { + importDeck();//importDeck(isHumanMenu); + } + });//import + + export.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent a) { + exportDeck(); + } + });//export + + menu.add(import2); + menu.add(export); + + }//addImportExport() + + /** + *

exportDeck.

+ */ + private void exportDeck() { + File filename = getExportFilename(); + + if (filename == null) return; + + //write is an Object variable because you might just + //write one Deck object + Deck deck = cardPoolToDeck(deckDisplay.getBottom()); + + deck.setName(filename.getName()); + + + try { + ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename)); + out.writeObject(deck); + out.flush(); + out.close(); + } catch (Exception ex) { + ErrorViewer.showError(ex); + throw new RuntimeException("Gui_Quest_DeckEditor_Menu : exportDeck() error, " + ex); + } + + exportDeckText(getExportDeckText(deck), filename.getAbsolutePath()); + + }//exportDeck() + + /** + *

exportDeckText.

+ * + * @param deckText a {@link java.lang.String} object. + * @param filename a {@link java.lang.String} object. + */ + private void exportDeckText(String deckText, String filename) { + + //remove ".deck" extension + int cut = filename.indexOf("."); + filename = filename.substring(0, cut); + + try { + FileWriter writer = new FileWriter(filename + ".txt"); + writer.write(deckText); + + writer.flush(); + writer.close(); + } catch (Exception ex) { + ErrorViewer.showError(ex); + throw new RuntimeException("Gui_Quest_DeckEditor_Menu : exportDeckText() error, " + ex.getMessage() + + " : " + Arrays.toString(ex.getStackTrace())); + } + }//exportDeckText() + + + /** + *

getExportDeckText.

+ * + * @param aDeck a {@link forge.deck.Deck} object. + * @return a {@link java.lang.String} object. + */ + private String getExportDeckText(Deck aDeck) { + //convert Deck into CardList + CardPoolView all = aDeck.getMain(); + //sort by card name + Collections.sort( all.getOrderedList(), TableSorter.byNameThenSet ); + + StringBuffer sb = new StringBuffer(); + String newLine = "\r\n"; + + sb.append(String.format("%d Total Cards%n%n", all.countAll())); + + //creatures + sb.append(String.format("%d Creatures%n-------------%n", CardRules.Predicates.Presets.isCreature.aggregate(all, CardPoolView.fnToCard, CardPoolView.fnToCount))); + for (Entry e : CardRules.Predicates.Presets.isCreature.select(all, CardPoolView.fnToCard)) { + sb.append(String.format("%d x %s%n", e.getValue(), e.getKey().getName())); + } + + //spells + sb.append(String.format("%d Spells%n----------%n", CardRules.Predicates.Presets.isNonCreatureSpell.aggregate(all, CardPoolView.fnToCard, CardPoolView.fnToCount))); + for (Entry e : CardRules.Predicates.Presets.isNonCreatureSpell.select(all, CardPoolView.fnToCard)) { + sb.append(String.format("%d x %s%n", e.getValue(), e.getKey().getName())); + } + + //lands + sb.append(String.format("%d Land%n--------%n", CardRules.Predicates.Presets.isLand.aggregate(all, CardPoolView.fnToCard, CardPoolView.fnToCount))); + for (Entry e : CardRules.Predicates.Presets.isLand.select(all, CardPoolView.fnToCard)) { + sb.append(String.format("%d x %s%n", e.getValue(), e.getKey().getName())); + } + + sb.append(newLine); + + return sb.toString(); + }//getExportDeckText + + + /** + *

getFileFilter.

+ * + * @return a {@link javax.swing.filechooser.FileFilter} object. + */ + private FileFilter getFileFilter() { + FileFilter filter = new FileFilter() { + @Override + public boolean accept(File f) { + return f.getName().endsWith(".dck") || f.isDirectory(); + } + + @Override + public String getDescription() { + return "Deck File .dck"; + } + }; + + return filter; + }//getFileFilter() + + /** + *

getExportFilename.

+ * + * @return a {@link java.io.File} object. + */ + private File getExportFilename() { + //Object o = null; // unused + + JFileChooser save = new JFileChooser(previousDirectory); + + save.setDialogTitle("Export Deck Filename"); + save.setDialogType(JFileChooser.SAVE_DIALOG); + save.addChoosableFileFilter(getFileFilter()); + save.setSelectedFile(new File(currentDeck.getName() + ".deck")); + + int returnVal = save.showSaveDialog(null); + + if (returnVal == JFileChooser.APPROVE_OPTION) { + File file = save.getSelectedFile(); + String check = file.getAbsolutePath(); + + previousDirectory = file.getParentFile(); + + if (check.endsWith(".deck")) return file; + else return new File(check + ".deck"); + } + + return null; + }//getExportFilename() + + /** + *

importDeck.

+ */ + private void importDeck() { + File file = getImportFilename(); + + if (file == null) { + } else if (file.getName().endsWith(".dck")) { + try { + Deck newDeck = DeckManager.readDeck(file); + questData.addDeck(newDeck); + + CardPool cardpool = new CardPool(questData.getCardpool()); + CardPool decklist = new CardPool(); + for (Entry s : newDeck.getMain()) { + CardPrinted cp = s.getKey(); + decklist.add(cp, s.getValue()); + cardpool.add(cp, s.getValue()); + questData.getCardpool().add(cp, s.getValue()); + } + deckDisplay.setDecks(cardpool, decklist); + + } catch (Exception ex) { + ErrorViewer.showError(ex); + throw new RuntimeException("Gui_DeckEditor_Menu : importDeck() error, " + ex); + } + } + + }//importDeck() + + /** + *

getImportFilename.

+ * + * @return a {@link java.io.File} object. + */ + private File getImportFilename() { + JFileChooser chooser = new JFileChooser(previousDirectory); + + chooser.addChoosableFileFilter(getFileFilter()); + int returnVal = chooser.showOpenDialog(null); + + if (returnVal == JFileChooser.APPROVE_OPTION) { + File file = chooser.getSelectedFile(); + previousDirectory = file.getParentFile(); + return file; + } + + return null; + }//openFileDialog() + + + + private final ActionListener addCardActionListener = new ActionListener() { + public void actionPerformed(final ActionEvent a) { + + // Provide a model here: all unique cards to be displayed by only name (unlike default toString) + Iterable uniqueCards = CardDb.instance().getAllUniqueCards(); + List cards = new ArrayList(); + for (CardPrinted c : uniqueCards) { cards.add(c.getName()); } + Collections.sort(cards); + + // use standard forge's list selection dialog + ListChooser c = new ListChooser("Cheat - Add Card to Your Cardpool", 0, 1, cards); + if (c.show()) { + String cardName = c.getSelectedValue(); + DeckEditorQuest g = (DeckEditorQuest) deckDisplay; + g.getTop().add(CardDb.instance().getCard(cardName)); + AllZone.getQuestData().getCardpool().add(CardDb.instance().getCard(cardName)); + g.updateDisplay(); + } + } + }; + + private final ActionListener openDeckActionListener = new ActionListener() { + public void actionPerformed(final ActionEvent a) { + String deckName = getUserInput_OpenDeck(questData.getDeckNames()); + + //check if user selected "cancel" + if (StringUtils.isBlank(deckName)) { return; } + + setPlayerDeckName(deckName); + CardPool cards = new CardPool(questData.getCardpool().getView()); + CardPoolView deck = questData.getDeck(deckName).getMain(); + + // show in pool all cards except ones used in deck + cards.removeAll(deck); + deckDisplay.setDecks(cards, deck); + } + }; + + private final ActionListener newDeckActionListener = new ActionListener() { + public void actionPerformed(final ActionEvent a) { + deckDisplay.setDecks(questData.getCardpool().getView(), new CardPool()); + setPlayerDeckName(""); + } + }; + + private final ActionListener renameDeckActionListener = new ActionListener() { + public void actionPerformed(final ActionEvent a) { + String deckName = getUserInput_GetDeckName(questData.getDeckNames()); + + //check if user cancels + if (StringUtils.isBlank(deckName)) { return; } + + //is the current deck already saved and in QuestData? + if (questData.getDeckNames().contains(currentDeck.getName())) { + questData.removeDeck(currentDeck.getName()); + } + + currentDeck.setName(deckName); + + Deck deck = cardPoolToDeck(deckDisplay.getBottom()); + deck.setName(deckName); + questData.addDeck(deck); + + setPlayerDeckName(deckName); + } + }; + + private final ActionListener saveDeckActionListener = new ActionListener() { + public void actionPerformed(ActionEvent a) { + String name = currentDeck.getName(); + + //check to see if name is set + if (name.equals("")) { + name = getUserInput_GetDeckName(questData.getDeckNames()); + + //check if user cancels + if (name.equals("")) return; + } + + setPlayerDeckName(name); + + Deck deck = cardPoolToDeck(deckDisplay.getBottom()); + deck.setName(name); + + questData.addDeck(deck); + } + }; + + private final ActionListener copyDeckActionListener = new ActionListener() { + public void actionPerformed(ActionEvent a) { + String name = getUserInput_GetDeckName(questData.getDeckNames()); + + //check if user cancels + if (name.equals("")) return; + + setPlayerDeckName(name); + + Deck deck = cardPoolToDeck(deckDisplay.getBottom()); + deck.setName(name); + + questData.addDeck(deck); + } + }; + + private final ActionListener deleteDeckActionListener = new ActionListener() { + public void actionPerformed(ActionEvent a) { + if (currentDeck.getName().equals("")) return; + + int check = JOptionPane.showConfirmDialog(null, "Do you really want to delete this deck?", + "Delete", JOptionPane.YES_NO_OPTION); + if (check == JOptionPane.NO_OPTION) return; //stop here + + questData.removeDeck(currentDeck.getName()); + + //show card pool + deckDisplay.setDecks(questData.getCardpool().getView(), new CardPool()); + + setPlayerDeckName(""); + } + }; + + //the usual menu options that will be used + /** + *

setupMenu.

+ */ + private void setupMenu() { + JMenuItem openDeck = new JMenuItem("Open"); + JMenuItem newDeck = new JMenuItem("New"); + JMenuItem rename = new JMenuItem("Rename"); + JMenuItem save = new JMenuItem("Save"); + JMenuItem copy = new JMenuItem("Copy"); + JMenuItem delete = new JMenuItem("Delete"); + JMenuItem exit = new JMenuItem("Exit"); + + JMenuItem addCard = new JMenuItem("Cheat - Add Card"); + + + addCard.addActionListener(addCardActionListener); + openDeck.addActionListener(openDeckActionListener); + newDeck.addActionListener(newDeckActionListener); + rename.addActionListener(renameDeckActionListener); + save.addActionListener(saveDeckActionListener); + copy.addActionListener(copyDeckActionListener); + delete.addActionListener(deleteDeckActionListener); + + + //human + exit.addActionListener(new ActionListener() { + public void actionPerformed(final ActionEvent a) { + DeckEditorQuestMenu.this.close(); + } + }); + + JMenu deckMenu = new JMenu("Deck"); + deckMenu.add(openDeck); + deckMenu.add(newDeck); + deckMenu.add(rename); + deckMenu.add(save); + deckMenu.add(copy); + + if (Constant.Runtime.DevMode[0]) { + deckMenu.addSeparator(); + deckMenu.add(addCard); + } + + deckMenu.addSeparator(); + addImportExport(deckMenu, true); + + deckMenu.addSeparator(); + deckMenu.add(delete); + deckMenu.addSeparator(); + deckMenu.add(exit); + + this.add(deckMenu); + + } + + /** + *

convertCardPoolToDeck.

+ * + * @param list a {@link forge.CardPool} object. + * @return a {@link forge.deck.Deck} object. + */ + private Deck cardPoolToDeck(final CardPoolView list) { + //put CardPool into Deck main + Deck deck = new Deck(Constant.GameType.Sealed); + deck.addMain(list); + return deck; + } + + //needs to be public because Gui_Quest_DeckEditor.show(Command) uses it + /** + *

setHumanPlayer.

+ * + * @param deckName a {@link java.lang.String} object. + */ + public void setPlayerDeckName(String deckName) { + //the gui uses this, Gui_Quest_DeckEditor + currentDeck = new Deck(Constant.GameType.Sealed); + currentDeck.setName(deckName); + + deckDisplay.setTitle(deckEditorName + " - " + deckName); + } + + //only accepts numbers, letters or dashes up to 20 characters in length + /** + *

cleanString.

+ * + * @param in a {@link java.lang.String} object. + * @return a {@link java.lang.String} object. + */ + private String cleanString(final String in) { + StringBuffer out = new StringBuffer(); + char[] c = in.toCharArray(); + + for (int i = 0; i < c.length && i < 20; i++) { + if (Character.isLetterOrDigit(c[i]) || c[i] == '-' || c[i] == '_' || c[i] == ' ') { out.append(c[i]); } + } + + return out.toString(); + } + + //if user cancels, returns "" + /** + *

getUserInput_GetDeckName.

+ * + * @param nameList a {@link java.util.List} object. + * @return a {@link java.lang.String} object. + */ + private String getUserInput_GetDeckName(List nameList) { + Object o = JOptionPane.showInputDialog(null, "", "Deck Name", JOptionPane.OK_CANCEL_OPTION); + + if (o == null) return ""; + + String deckName = cleanString(o.toString()); + + if (nameList.contains(deckName) || deckName.equals("")) { + JOptionPane.showMessageDialog(null, "Please pick another deck name, a deck currently has that name."); + return getUserInput_GetDeckName(nameList); + } + + return deckName; + }//getUserInput_GetDeckName() + + + //if user cancels, it will return "" + /** + *

getUserInput_OpenDeck.

+ * + * @param deckNameList a {@link java.util.List} object. + * @return a {@link java.lang.String} object. + */ + private String getUserInput_OpenDeck(List deckNameList) { + List choices = deckNameList; + if (choices.size() == 0) { + JOptionPane.showMessageDialog(null, "No decks found", "Open Deck", JOptionPane.PLAIN_MESSAGE); + return ""; + } + + //Object o = JOptionPane.showInputDialog(null, "Deck Name", "Open Deck", JOptionPane.OK_CANCEL_OPTION, null, + // choices.toArray(), choices.toArray()[0]); + Object o = GuiUtils.getChoiceOptional("Select Deck", choices.toArray()); + + if (o == null) return ""; + + return o.toString(); + }//getUserInput_OpenDeck() + + //used by Gui_Quest_DeckEditor + /** + *

close.

+ */ + public void close() { + exitCommand.execute(); + } + + //used by Gui_Quest_DeckEditor + /** + *

getDeckName.

+ * + * @return a {@link java.lang.String} object. + */ + public String getDeckName() { + return currentDeck.getName(); + } + + + +} diff --git a/src/main/java/forge/gui/deckeditor/FilterCheckBoxes.java b/src/main/java/forge/gui/deckeditor/FilterCheckBoxes.java new file mode 100644 index 00000000000..c30408fb64e --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/FilterCheckBoxes.java @@ -0,0 +1,97 @@ +package forge.gui.deckeditor; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.swing.JCheckBox; + +import net.slightlymagic.maxmtg.Predicate; +import forge.card.CardRules; + +/** + * A structural class for some checkboxes need for a deck editor, contains no JPanel to store boxes on + * Checkboxes are public so the using class should place them in some container. + */ +class FilterCheckBoxes { + public final JCheckBox white; + public final JCheckBox blue; + public final JCheckBox black; + public final JCheckBox red; + public final JCheckBox green; + public final JCheckBox colorless; + + public final JCheckBox land; + public final JCheckBox creature; + public final JCheckBox sorcery; + public final JCheckBox instant; + public final JCheckBox planeswalker; + public final JCheckBox artifact; + public final JCheckBox enchantment; + + // Very handy for classes using mass operations on an array of checkboxes + public final List allColors; + public final List allTypes; + + public FilterCheckBoxes(final boolean useGraphicalBoxes) { + if (useGraphicalBoxes) { + white = new GuiFilterCheckBox("white", "White"); + blue = new GuiFilterCheckBox("blue", "Blue"); + black = new GuiFilterCheckBox("black", "Black"); + red = new GuiFilterCheckBox("red", "Red"); + green = new GuiFilterCheckBox("green", "Green"); + colorless = new GuiFilterCheckBox("colorless", "Colorless"); + + land = new GuiFilterCheckBox("land", "Land"); + creature = new GuiFilterCheckBox("creature", "Creature"); + sorcery = new GuiFilterCheckBox("sorcery", "Sorcery"); + instant = new GuiFilterCheckBox("instant", "Instant"); + planeswalker = new GuiFilterCheckBox("planeswalker", "Planeswalker"); + artifact = new GuiFilterCheckBox("artifact", "Artifact"); + enchantment = new GuiFilterCheckBox("enchant", "Enchantment"); + } else { + white = new JCheckBox("W", true); + blue = new JCheckBox("U", true); + black = new JCheckBox("B", true); + red = new JCheckBox("R", true); + green = new JCheckBox("G", true); + colorless = new JCheckBox("C", true); + + land = new JCheckBox("Land", true); + creature = new JCheckBox("Creature", true); + sorcery = new JCheckBox("Sorcery", true); + instant = new JCheckBox("Instant", true); + planeswalker = new JCheckBox("Planeswalker", true); + artifact = new JCheckBox("Artifact", true); + enchantment = new JCheckBox("Enchant", true); + } + + allColors = Arrays.asList(new JCheckBox[]{ white, blue, black, red, green, colorless}); + allTypes = Arrays.asList(new JCheckBox[]{ land, creature, sorcery, instant, planeswalker, artifact, enchantment }); + } + + + public final Predicate buildFilter() { + List> colors = new ArrayList>(); + if (white.isSelected()) { colors.add(CardRules.Predicates.Presets.isWhite); } + if (blue.isSelected()) { colors.add(CardRules.Predicates.Presets.isBlue); } + if (black.isSelected()) { colors.add(CardRules.Predicates.Presets.isBlack); } + if (red.isSelected()) { colors.add(CardRules.Predicates.Presets.isRed); } + if (green.isSelected()) { colors.add(CardRules.Predicates.Presets.isGreen); } + if (colorless.isSelected()) { colors.add(CardRules.Predicates.Presets.isColorless); } + Predicate filterByColor = colors.size() == 6 ? Predicate.getTrue(CardRules.class) : Predicate.or(colors); + + List> types = new ArrayList>(); + if (land.isSelected()) { types.add(CardRules.Predicates.Presets.isLand); } + if (creature.isSelected()) { types.add(CardRules.Predicates.Presets.isCreature); } + if (sorcery.isSelected()) { types.add(CardRules.Predicates.Presets.isSorcery); } + if (instant.isSelected()) { types.add(CardRules.Predicates.Presets.isInstant); } + if (planeswalker.isSelected()) { types.add(CardRules.Predicates.Presets.isPlaneswalker); } + if (artifact.isSelected()) { types.add(CardRules.Predicates.Presets.isArtifact); } + if (enchantment.isSelected()) { types.add(CardRules.Predicates.Presets.isEnchantment); } + Predicate filterByType = colors.size() == 7 ? Predicate.getTrue(CardRules.class) : Predicate.or(types); + + return Predicate.and(filterByColor, filterByType); + } + +} diff --git a/src/main/java/forge/GuiFilterCheckBox.java b/src/main/java/forge/gui/deckeditor/GuiFilterCheckBox.java similarity index 97% rename from src/main/java/forge/GuiFilterCheckBox.java rename to src/main/java/forge/gui/deckeditor/GuiFilterCheckBox.java index 517b4ae4c42..47a43b19e43 100644 --- a/src/main/java/forge/GuiFilterCheckBox.java +++ b/src/main/java/forge/gui/deckeditor/GuiFilterCheckBox.java @@ -1,4 +1,4 @@ -package forge; +package forge.gui.deckeditor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; diff --git a/src/main/java/forge/Gui_BoosterDraft.java b/src/main/java/forge/gui/deckeditor/Gui_BoosterDraft.java similarity index 50% rename from src/main/java/forge/Gui_BoosterDraft.java rename to src/main/java/forge/gui/deckeditor/Gui_BoosterDraft.java index b2a934f8e0a..3c17fce0ab0 100644 --- a/src/main/java/forge/Gui_BoosterDraft.java +++ b/src/main/java/forge/gui/deckeditor/Gui_BoosterDraft.java @@ -1,6 +1,15 @@ -package forge; - +package forge.gui.deckeditor; +import forge.AllZone; +import forge.BoosterDraft; +import forge.CardList; +import forge.Constant; +import forge.FileUtil; +import forge.HttpUtil; +import forge.Constant.GameType; +import forge.Constant.Runtime; +import forge.card.CardPoolView; +import forge.card.CardPrinted; import forge.deck.Deck; import forge.deck.DeckManager; import forge.error.ErrorViewer; @@ -15,10 +24,10 @@ import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; -import java.awt.Color; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; +import java.util.List; import java.util.Random; @@ -28,7 +37,7 @@ import java.util.Random; * @author Forge * @version $Id$ */ -public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConstants, NewConstants.LANG.Gui_BoosterDraft { +public class Gui_BoosterDraft extends JFrame implements NewConstants, NewConstants.LANG.Gui_BoosterDraft { /** * Constant serialVersionUID=-6055633915602448260L */ @@ -48,8 +57,7 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta private JScrollPane jScrollPane2 = new JScrollPane(); private TitledBorder titledBorder1; private TitledBorder titledBorder2; - private Border border3; - private TitledBorder titledBorder3; + private JLabel statsLabel = new JLabel(); private JTable allCardTable = new JTable(); private JTable deckTable = new JTable(); @@ -58,8 +66,8 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta private GridLayout gridLayout1 = new GridLayout(); private JLabel statsLabel2 = new JLabel(); private JButton jButton1 = new JButton(); - private CardDetailPanel detail = new CardDetailPanel(null); - private CardPicturePanel picture = new CardPicturePanel(null); + + private CardViewPanelLite cardView = new CardViewPanelLite(); /** *

showGui.

@@ -102,18 +110,28 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta addListeners(); // setupMenu(); + + List> columns = new ArrayList>(); + columns.add(new TableColumnInfo("Qty", 30, CardColumnPresets.fnQtyCompare, CardColumnPresets.fnQtyGet)); + columns.add(new TableColumnInfo("Name", 180, CardColumnPresets.fnNameCompare, CardColumnPresets.fnNameGet)); + columns.add(new TableColumnInfo("Cost", 70, CardColumnPresets.fnCostCompare, CardColumnPresets.fnCostGet)); + columns.add(new TableColumnInfo("Color", 50, CardColumnPresets.fnColorCompare, CardColumnPresets.fnColorGet)); + columns.add(new TableColumnInfo("Type", 100, CardColumnPresets.fnTypeCompare, CardColumnPresets.fnTypeGet)); + columns.add(new TableColumnInfo("Stats", 40, CardColumnPresets.fnStatsCompare, CardColumnPresets.fnStatsGet)); + columns.add(new TableColumnInfo("R", 35, CardColumnPresets.fnRarityCompare, CardColumnPresets.fnRarityGet)); + columns.add(new TableColumnInfo("Set", 40, CardColumnPresets.fnSetCompare, CardColumnPresets.fnSetGet)); + columns.add(new TableColumnInfo("AI", 30, CardColumnPresets.fnAiStatusCompare, CardColumnPresets.fnAiStatusGet)); + //construct allCardTable, get all cards - allCardModel = new TableModel(new CardList(), this); + allCardModel = new TableModel(cardView, columns); allCardModel.addListeners(allCardTable); allCardTable.setModel(allCardModel); - allCardModel.resizeCols(allCardTable); //construct deckModel - deckModel = new TableModel(this); + deckModel = new TableModel(cardView, columns); deckModel.addListeners(deckTable); deckTable.setModel(deckModel); - deckModel.resizeCols(deckTable); //add cards to GUI from deck @@ -121,7 +139,7 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta allCardTable.addMouseListener(new MouseAdapter() { @Override - public void mousePressed(MouseEvent e) { + public void mousePressed(final MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0) jButton1_actionPerformed(null); } });//MouseListener @@ -130,8 +148,7 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta //get stats from deck deckModel.addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent ev) { - CardList deck = deckModel.getCards(); - statsLabel.setText(getStats(deck)); + statsLabel.setText(getStats(deckModel.getCards())); } }); @@ -139,8 +156,8 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta //get stats from all cards allCardModel.addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent ev) { - CardList deck = allCardModel.getCards(); - statsLabel2.setText(getStats(deck)); + + statsLabel2.setText(getStats(allCardModel.getCards())); } }); @@ -149,29 +166,11 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta setExtendedState(Frame.MAXIMIZED_BOTH); }//setupAndDisplay() - /** - *

getStats.

- * - * @param deck a {@link forge.CardList} object. - * @return a {@link java.lang.String} object. - */ - private String getStats(CardList deck) { - int total = deck.size(); - int creature = deck.getType("Creature").size(); - int land = deck.getType("Land").size(); - StringBuffer show = new StringBuffer(); - show.append("Total - ").append(total).append(", Creatures - ").append(creature).append(", Land - ").append(land); - String[] color = Constant.Color.Colors; - for (int i = 0; i < 5; i++) - show.append(", ").append(color[i]).append(" - ").append(CardListUtil.getColor(deck, color[i]).size()); + private String getStats(final CardPoolView deck) { + return DeckEditorBase.getStats(deck); + } - return show.toString(); - }//getStats() - - /** - *

Constructor for Gui_BoosterDraft.

- */ public Gui_BoosterDraft() { try { jbInit(); @@ -180,20 +179,6 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta } } - /** - *

getCard.

- * - * @return a {@link forge.Card} object. - */ - public Card getCard() { - return detail.getCard(); - } - - /** {@inheritDoc} */ - public void setCard(Card card) { - detail.setCard(card); - picture.setCard(card); - } /** *

jbInit.

@@ -205,16 +190,16 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta "Previously Picked Cards"); titledBorder2 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)), "Choose one card"); - border3 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)); - titledBorder3 = new TitledBorder(border3, "Card Detail"); + this.getContentPane().setLayout(null); jScrollPane1.setBorder(titledBorder2); jScrollPane1.setBounds(new Rectangle(19, 28, 661, 344)); jScrollPane2.setBorder(titledBorder1); jScrollPane2.setBounds(new Rectangle(19, 478, 661, 184)); - detail.setBorder(titledBorder3); - detail.setBounds(new Rectangle(693, 23, 239, 323)); - picture.setBounds(new Rectangle(693, 348, 240, 340)); + + cardView.jbInit(); + cardView.setBounds(new Rectangle(693, 23, 239, 665)); + statsLabel.setFont(new java.awt.Font("Dialog", 0, 16)); statsLabel.setText("Total - 0, Creatures - 0 Land - 0"); statsLabel.setBounds(new Rectangle(19, 665, 665, 31)); @@ -237,8 +222,7 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta jButton1_actionPerformed(e); } }); - this.getContentPane().add(detail, null); - this.getContentPane().add(picture, null); + this.getContentPane().add(cardView, null); this.getContentPane().add(jScrollPane1, null); this.getContentPane().add(statsLabel2, null); this.getContentPane().add(statsLabel, null); @@ -258,13 +242,11 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta if (n != -1) { setTitle("Deck Editor - " + Constant.Runtime.HumanDeck[0].getName() + " - changed"); - Card c = allCardModel.rowToCard(n); + CardPrinted c = allCardModel.rowToCard(n).getKey(); deckModel.addCard(c); deckModel.resort(); - if (limitedDeckEditor) { - allCardModel.removeCard(c); - } + allCardModel.removeCard(c); //3 conditions" 0 cards left, select the same row, select next row int size = allCardModel.getRowCount(); @@ -285,7 +267,7 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta if (n != -1) { setTitle("Deck Editor - " + Constant.Runtime.HumanDeck[0].getName() + " - changed"); - Card c = deckModel.rowToCard(n); + CardPrinted c = deckModel.rowToCard(n).getKey(); deckModel.removeCard(c); if (limitedDeckEditor) { @@ -304,235 +286,6 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta //if true, don't do anything else - /** - *

checkSaveDeck.

- * - * @return a boolean. - */ - private boolean checkSaveDeck() { - //a crappy way of checking if the deck has been saved - if (getTitle().endsWith("changed")) { - - int n = JOptionPane.showConfirmDialog(null, ForgeProps.getLocalized(SAVE_MESSAGE), - ForgeProps.getLocalized(SAVE_TITLE), JOptionPane.YES_NO_CANCEL_OPTION); - if (n == JOptionPane.CANCEL_OPTION) return true; - else if (n == JOptionPane.YES_OPTION) saveItem_actionPerformed(); - } - return false; - }//checkSaveDeck() - - /** - *

newItem_actionPerformed.

- */ - private void newItem_actionPerformed() { - if (checkSaveDeck()) return; - - setTitle("Deck Editor"); - - Deck deck = Constant.Runtime.HumanDeck[0]; - while (deck.countMain() != 0) - deck.addSideboard(deck.removeMain(0)); - - //refreshGui(); - }//newItem_actionPerformed - - /** - *

closeItem_actionPerformed.

- */ - private void closeItem_actionPerformed() { - //check if saved, show dialog "yes, "no" - checkSaveDeck(); - dispose(); - } - - /** - *

stats_actionPerformed.

- * - * @param list a {@link forge.CardList} object. - */ - private void stats_actionPerformed(CardList list) { - - } - - /** - *

saveAsItem_actionPerformed.

- */ - private void saveAsItem_actionPerformed() { - }//saveItem_actionPerformed() - - /** - *

saveItem_actionPerformed.

- */ - private void saveItem_actionPerformed() { - } - - /** - *

openItem_actionPerformed.

- */ - private void openItem_actionPerformed() { - }//openItem_actionPerformed() - - /** - *

deleteItem_actionPerformed.

- */ - public void deleteItem_actionPerformed() { - } - - /** - *

renameItem_actionPerformed.

- */ - public void renameItem_actionPerformed() { - String newName = ""; - while (newName.equals("")) { - newName = JOptionPane.showInputDialog(null, ForgeProps.getLocalized(RENAME_MESSAGE), - ForgeProps.getLocalized(RENAME_TITLE), JOptionPane.QUESTION_MESSAGE); - if (newName == null) break; - } - - //when the user selects "Cancel" - if (newName != null) { - //String oldName = Constant.Runtime.HumanDeck[0].getName(); //unused - - Constant.Runtime.HumanDeck[0].setName(newName); - setTitle("Deck Editor - " + newName + " - changed"); - } - } - - /** - *

setupMenu.

- */ - @SuppressWarnings("unused") - // setupMenu - private void setupMenu() { - //final boolean[] isSaved = new boolean[1]; // unused - - JMenuItem newItem = new JMenuItem("New"); - JMenuItem openItem = new JMenuItem("Open"); - JMenuItem saveItem = new JMenuItem("Save"); - JMenuItem saveAsItem = new JMenuItem("Save As"); - JMenuItem renameItem = new JMenuItem("Rename"); - JMenuItem deleteItem = new JMenuItem("Delete"); - JMenuItem statsPoolItem = new JMenuItem("Statistics - Card Pool"); - JMenuItem statsDeckItem = new JMenuItem("Statistics - Deck"); - JMenuItem closeItem = new JMenuItem("Close"); - - newItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - newItem_actionPerformed(); - } - }); - openItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - openItem_actionPerformed(); - } - }); - saveItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - saveItem_actionPerformed(); - } - }); - saveAsItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - saveAsItem_actionPerformed(); - } - }); - renameItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - renameItem_actionPerformed(); - } - }); - deleteItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - deleteItem_actionPerformed(); - } - }); - statsPoolItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - stats_actionPerformed(allCardModel.getCards()); - } - }); - statsDeckItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - stats_actionPerformed(deckModel.getCards()); - } - }); - closeItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - closeItem_actionPerformed(); - } - }); - - JMenu fileMenu = new JMenu("Deck Actions"); - fileMenu.add(newItem); - fileMenu.add(openItem); - fileMenu.add(saveItem); - fileMenu.add(saveAsItem); - - fileMenu.addSeparator(); - fileMenu.add(renameItem); - fileMenu.add(deleteItem); -// fileMenu.add(statsPoolItem); -// fileMenu.add(statsDeckItem); - fileMenu.addSeparator(); - fileMenu.add(closeItem); - - JMenuBar menuBar = new JMenuBar(); - menuBar.add(fileMenu); - - this.setJMenuBar(menuBar); - }/*setupMenu(); */ - - //refresh Gui from deck, Gui shows the cards in the deck - -// /** -// *

refreshGui.

-// */ -/* private void refreshGui() { - Deck deck = Constant.Runtime.HumanDeck[0]; - if (deck == null) //this is just a patch, i know - deck = new Deck(Constant.Runtime.GameType[0]); - - allCardModel.clear(); - deckModel.clear(); - - Card c; - //ReadDraftBoosterPack pack = new ReadDraftBoosterPack(); - for (int i = 0; i < deck.countMain(); i++) { - c = AllZone.getCardFactory().getCard(deck.getMain(i), AllZone.getHumanPlayer()); - - //add rarity to card if this is a sealed card pool - //if (!Constant.Runtime.GameType[0].equals(Constant.GameType.Constructed)) - // c.setRarity(pack.getRarity(c.getName())); - //; - - - deckModel.addCard(c); - }//for - - if (deck.isSealed() || deck.isRegular()) { - //add sideboard to GUI - for (int i = 0; i < deck.countSideboard(); i++) { - c = AllZone.getCardFactory().getCard(deck.getSideboard(i), AllZone.getHumanPlayer()); - //c.setRarity(pack.getRarity(c.getName())); - allCardModel.addCard(c); - } - } else { - - * Braids: "getAllCards copies the entire array, but that does not - * seem to be needed here. Significant performance improvement is - * possible if this code used getCards instead (along with a for each - * loop instead of using get(i), if applicable)." - -// CardList all = AllZone.getCardFactory().getAllCards(); -// for (int i = 0; i < all.size(); i++) -// allCardModel.addCard(all.get(i)); - } - - allCardModel.resort(); - deckModel.resort(); - }//refreshGui() -*/ - //updates Constant.Runtime.HumanDeck[0] from the cards shown in the GUI /** *

refreshDeck.

@@ -546,15 +299,10 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta Constant.Runtime.HumanDeck[0] = deck; //update Deck with cards shown in GUI - CardList list = deckModel.getCards(); - for (int i = 0; i < list.size(); i++) - deck.addMain(list.get(i).getName()); - + + deck.addMain(deckModel.getCards()); if (deck.isSealed()) { - //add sideboard to deck - list = allCardModel.getCards(); - for (int i = 0; i < list.size(); i++) - deck.addSideboard(list.get(i).getName()); + deck.addSideboard(allCardModel.getCards()); } }/* refreshDeck() */ @@ -569,7 +317,7 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta if (n == -1) //is valid selection? return; - Card c = allCardModel.rowToCard(n); + CardPrinted c = allCardModel.rowToCard(n).getKey(); deckModel.addCard(c); deckModel.resort(); @@ -608,38 +356,9 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta * * @param list a {@link forge.CardList} object. */ - private void showChoices(CardList list) { + private void showChoices(CardPoolView list) { allCardModel.clear(); - - //ReadDraftBoosterPack pack = new ReadDraftBoosterPack(); - Card c; - for (int i = 0; i < list.size(); i++) { - c = list.get(i); - //c.setRarity(pack.getRarity(c.getName())); - - //String PC = c.getSVar("PicCount"); - Random r = MyRandom.random; - //int n = 0; - //if (PC.matches("[0-9][0-9]?")) - // n = Integer.parseInt(PC); - //if (n > 1) - // c.setRandomPicture(r.nextInt(n)); - - if (c.getCurSetCode().equals("")) - c.setCurSetCode(c.getMostRecentSet()); - - if (!c.getCurSetCode().equals("")) { - int n = SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()).PicCount; - if (n > 1) - c.setRandomPicture(r.nextInt(n - 1) + 1); - - c.setImageFilename(CardUtil.buildFilename(c)); - - c.setRarity(SetInfoUtil.getSetInfo_Code(c.getSets(), c.getCurSetCode()).Rarity); - } - - allCardModel.addCard(c); - } + allCardModel.addCards(list); allCardModel.resort(); allCardTable.setRowSelectionInterval(0, 0); @@ -655,10 +374,8 @@ public class Gui_BoosterDraft extends JFrame implements CardContainer, NewConsta Constant.Runtime.HumanDeck[0] = deck; //add sideboard to deck - CardList list = deckModel.getCards(); - for (int i = 0; i < list.size(); i++) - deck.addSideboard(list.get(i).getName() + "|" + list.get(i).getCurSetCode()); - + CardPoolView list = deckModel.getCards(); + deck.addSideboard(list); for (int i = 0; i < 20; i++) { deck.addSideboard("Forest|" + BoosterDraft.LandSetCode[0]); diff --git a/src/main/java/forge/gui/deckeditor/TableColumnInfo.java b/src/main/java/forge/gui/deckeditor/TableColumnInfo.java new file mode 100644 index 00000000000..03809bb3c42 --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/TableColumnInfo.java @@ -0,0 +1,53 @@ +package forge.gui.deckeditor; + +import java.util.Map.Entry; + +import net.slightlymagic.braids.util.lambda.Lambda1; + +/** + * Holds single column set up for TableModel. + * Contains name, width + functions to retrieve column's value for compare and for display + * (they are different, in case of sets for instance) + */ + + @SuppressWarnings("rawtypes") + public class TableColumnInfo { + private final String name; + + public int minWidth; + public int maxWidth; + public int nominalWidth; + + public boolean isMinMaxApplied = true; + + public final Lambda1> fnSort; // this will be used for sorting + public final Lambda1> fnDisplay; // this is used to display + + public final String getName() { return name; } + + public TableColumnInfo(final String colName, + final Lambda1> fieldSort, + final Lambda1> fieldDisplay) { + fnSort = fieldSort; + fnDisplay = fieldDisplay; + this.name = colName; + } + + public TableColumnInfo(final String colName, final int width, + final Lambda1> fieldSort, + final Lambda1> fieldDisplay) { + this(colName, fieldSort, fieldDisplay); + this.maxWidth = width; + this.minWidth = width; + this.nominalWidth = width; + } + public TableColumnInfo(final String colName, final int wMin, final int width, final int wMax, + final Lambda1> fieldSort, + final Lambda1> fieldDisplay) { + this(colName, fieldSort, fieldDisplay); + this.maxWidth = wMax; + this.minWidth = wMin; + this.nominalWidth = width; + } + } + diff --git a/src/main/java/forge/gui/deckeditor/TableModel.java b/src/main/java/forge/gui/deckeditor/TableModel.java new file mode 100644 index 00000000000..cf0df6d11d7 --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/TableModel.java @@ -0,0 +1,230 @@ +package forge.gui.deckeditor; + + +import javax.swing.*; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.event.TableModelEvent; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; + +import net.slightlymagic.braids.util.lambda.Lambda1; + +import forge.Card; +import forge.SetInfoUtil; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; + +import java.awt.event.*; +import java.util.Collections; +import java.util.List; +import java.util.Map.Entry; + + +/** + *

TableModel class.

+ * + * @author Forge + * @version $Id$ + */ +public class TableModel extends AbstractTableModel { + /** + * + */ + private static final long serialVersionUID = -6896726613116254828L; + + @SuppressWarnings("rawtypes") // We use raw comparables to provide fields for sorting + + + + private int sortColumn; + private boolean isSortAsc = true; + + private CardPool data = new CardPool(); + private final CardDisplay cardDisplay; + private final List> columns; + + public TableModel(final CardDisplay cd, List> columnsToShow ) { + cardDisplay = cd; + columns = columnsToShow; + columns.get(4).isMinMaxApplied = false; + } + + + + @SuppressWarnings("rawtypes") + private final TableColumnInfo columnAI = new TableColumnInfo("AI", 30, + new Lambda1>() { + @Override public Comparable apply(final Entry from) { + return "n/a"; } }, + new Lambda1>() { + @Override public Object apply(final Entry from) { + return "n/a"; } }); + + /* + columnQty, columnName, columnCost, + columnColor, columnType, columnStats, + columnRarity, columnSet, columnAI + */ + + + public void resizeCols(final JTable table) { + TableColumn tableColumn = null; + for (int i = 0; i < table.getColumnCount(); i++) { + tableColumn = table.getColumnModel().getColumn(i); + TableColumnInfo colInfo = columns.get(i); + + tableColumn.setPreferredWidth(colInfo.nominalWidth); + if (colInfo.isMinMaxApplied) { + tableColumn.setMinWidth(colInfo.minWidth); + tableColumn.setMaxWidth(colInfo.maxWidth); + } + }//for + } + + public void clear() { data.clear(); } + public CardPoolView getCards() { return data.getView(); } + + /** + *

removeCard.

+ * + * @param c a {@link forge.Card} object. + */ + public void removeCard(final CardPrinted c) { + boolean wasThere = data.count(c) > 0; + if (wasThere) { + data.remove(c); + fireTableDataChanged(); + } + } + + + public void addCard(final CardPrinted c) { + data.add(c); + fireTableDataChanged(); + } + public void addCard(final CardPrinted c, final int count) { + data.add(c, count); + fireTableDataChanged(); + } + public void addCard(final Entry e) { + data.add(e.getKey(), e.getValue()); + fireTableDataChanged(); + } + public void addCards(final Iterable> c) { + data.addAll(c); + fireTableDataChanged(); + } + public void addAllCards(final Iterable c) { + data.addAllCards(c); + fireTableDataChanged(); + } + + public Entry rowToCard(final int row) { + return data.getOrderedList().get(row); + } + public int getRowCount() { + return data.countDistinct(); + } + + public int getColumnCount() { + return columns.size(); + } + + /** {@inheritDoc} */ + @Override + public String getColumnName(int n) { + return columns.get(n).getName(); + } + + /** {@inheritDoc} */ + public Object getValueAt(int row, int column) { + return columns.get(column).fnDisplay.apply(rowToCard(row)); + } + + + class ColumnListener extends MouseAdapter { + protected JTable table; + + public ColumnListener(JTable t) { table = t; } + + public void mouseClicked(MouseEvent e) { + TableColumnModel colModel = table.getColumnModel(); + int columnModelIndex = colModel.getColumnIndexAtX(e.getX()); + int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex(); + + if (modelIndex < 0) { return; } + if (sortColumn == modelIndex) { + isSortAsc = !isSortAsc; + } + else { + isSortAsc = true; + sortColumn = modelIndex; + } + + for (int i = 0; i < columns.size(); i++) { + TableColumn column = colModel.getColumn(i); + column.setHeaderValue(getColumnName(column.getModelIndex())); + } + table.getTableHeader().repaint(); + + resort(); + table.tableChanged(new TableModelEvent(TableModel.this)); + table.repaint(); + } + } + + + public void showSelectedCard(JTable table) + { + int row = table.getSelectedRow(); + if (row != -1) { + CardPrinted cp = rowToCard(row).getKey(); + cardDisplay.showCard(cp); + } + } + + /** + *

addListeners.

+ * + * @param table a {@link javax.swing.JTable} object. + */ + public void addListeners(final JTable table) { + //updates card detail, listens to any key strokes + table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { + + @Override + public void valueChanged(ListSelectionEvent arg0) { + showSelectedCard(table); + } + }); + table.addFocusListener(new FocusListener() { + + @Override public void focusLost(FocusEvent e) {} + @Override public void focusGained(FocusEvent e) { + showSelectedCard(table); + } + }); + + + + table.getTableHeader().addMouseListener(new ColumnListener(table)); + + }//addCardListener() + + + public void resort() { + TableSorter sorter = new TableSorter(columns.get(sortColumn).fnSort, isSortAsc); + Collections.sort(data.getOrderedList(), sorter); + } + + public void sort( int iCol, boolean isAsc ) + { + sortColumn = iCol; + isSortAsc = isAsc; + resort(); + } + +}//CardTableModel diff --git a/src/main/java/forge/gui/deckeditor/TableSorter.java b/src/main/java/forge/gui/deckeditor/TableSorter.java new file mode 100644 index 00000000000..f055c565b23 --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/TableSorter.java @@ -0,0 +1,52 @@ +package forge.gui.deckeditor; + + +import forge.card.CardPrinted; +import java.util.Comparator; +import java.util.Map.Entry; + +import net.slightlymagic.braids.util.lambda.Lambda1; + +/** + *

TableSorter class.

+ * + * @author Forge + * @version $Id$ + */ +@SuppressWarnings("unchecked") // Comparable needs +public class TableSorter implements Comparator> { + private boolean ascending; + @SuppressWarnings("rawtypes") + private Lambda1> field; + + /** + *

Constructor for TableSorter.

+ * + * @param in_all a {@link forge.CardList} object. + * @param in_column a int. + * @param in_ascending a boolean. + */ + @SuppressWarnings("rawtypes") + public TableSorter(Lambda1> field, boolean in_ascending) { + this.field = field; + ascending = in_ascending; + } + + @SuppressWarnings("rawtypes") + public static final TableSorter byNameThenSet = new TableSorter( + new Lambda1>() { + @Override public Comparable apply(final Entry from) { return from.getKey(); } + }, true); + + + @SuppressWarnings("rawtypes") + @Override + public int compare(Entry arg0, Entry arg1) { + Comparable obj1 = field.apply(arg0); + Comparable obj2 = field.apply(arg1); + //System.out.println(String.format("%s vs %s _______ %s vs %s", arg0, arg1, obj1, obj2)); + if (ascending) { return obj1.compareTo(obj2); } + else { return obj2.compareTo(obj1); } + } + +} diff --git a/src/main/java/forge/gui/deckeditor/package-info.java b/src/main/java/forge/gui/deckeditor/package-info.java new file mode 100644 index 00000000000..0768bd2449b --- /dev/null +++ b/src/main/java/forge/gui/deckeditor/package-info.java @@ -0,0 +1,2 @@ +/** Forge Card Game */ +package forge.gui.deckeditor; diff --git a/src/main/java/forge/gui/game/CardPicturePanel.java b/src/main/java/forge/gui/game/CardPicturePanel.java index 521b7f35819..e0b7df6c36b 100644 --- a/src/main/java/forge/gui/game/CardPicturePanel.java +++ b/src/main/java/forge/gui/game/CardPicturePanel.java @@ -13,6 +13,7 @@ import arcane.ui.ScaledImagePanel.ScalingType; import forge.Card; import forge.CardContainer; import forge.ImageCache; +import forge.card.CardPrinted; import javax.swing.*; import java.awt.*; @@ -27,11 +28,12 @@ import java.awt.event.ComponentEvent; * @author Clemens Koza * @version V0.0 17.02.2010 */ -public class CardPicturePanel extends JPanel implements CardContainer { +public final class CardPicturePanel extends JPanel implements CardContainer { /** Constant serialVersionUID=-3160874016387273383L */ private static final long serialVersionUID = -3160874016387273383L; private Card card; + private CardPrinted cardPrinted; // private JLabel label; // private ImageIcon icon; @@ -41,9 +43,9 @@ public class CardPicturePanel extends JPanel implements CardContainer { /** *

Constructor for CardPicturePanel.

* - * @param card a {@link forge.Card} object. + * @param c a {@link forge.Card} object. */ - public CardPicturePanel(Card card) { + public CardPicturePanel(final Card c) { super(new BorderLayout()); // add(label = new JLabel(icon = new ImageIcon())); add(panel = new ScaledImagePanel()); @@ -53,33 +55,48 @@ public class CardPicturePanel extends JPanel implements CardContainer { addComponentListener(new ComponentAdapter() { @Override - public void componentShown(ComponentEvent e) { + public void componentShown(final ComponentEvent e) { update(); } @Override - public void componentResized(ComponentEvent e) { + public void componentResized(final ComponentEvent e) { update(); } }); - setCard(card); + setCard(c); } /** *

update.

*/ - public void update() { - setCard(getCard()); + public void update() { setCard(getCard()); } + + public void setCard(final CardPrinted cp) { + card = null; + cardPrinted = cp; + if (!isShowing()) { return; } + + setImage(); } /** {@inheritDoc} */ - public void setCard(Card card) { - this.card = card; - if (!isShowing()) return; + public void setCard(final Card c) { + card = c; + cardPrinted = null; + if (!isShowing()) { return; } + + setImage(); + } + + private void setImage() { Insets i = getInsets(); - Image image = card == null ? null : ImageCache.getImage(card, getWidth() - i.left - i.right, getHeight() - - i.top - i.bottom); + Image image = null; + if (cardPrinted != null) { + image = ImageCache.getImage(cardPrinted, getWidth() - i.left - i.right, getHeight() - i.top - i.bottom); } + if (card != null && image == null) { + image = ImageCache.getImage(card, getWidth() - i.left - i.right, getHeight() - i.top - i.bottom); } if (image != currentImange) { currentImange = image; @@ -103,6 +120,9 @@ public class CardPicturePanel extends JPanel implements CardContainer { * @return a {@link forge.Card} object. */ public Card getCard() { + if ( card == null && cardPrinted != null ) { + card = cardPrinted.toForgeCard(); + } return card; } } diff --git a/src/main/java/forge/model/FModel.java b/src/main/java/forge/model/FModel.java index 14b82eb6c62..70b66eade55 100644 --- a/src/main/java/forge/model/FModel.java +++ b/src/main/java/forge/model/FModel.java @@ -78,12 +78,12 @@ public class FModel { Constant.Runtime.UpldDrft[0] = preferences.uploadDraftAI; Constant.Runtime.RndCFoil[0] = preferences.randCFoil; - final HttpUtil pinger = new HttpUtil(); +/* final HttpUtil pinger = new HttpUtil(); if (pinger.getURL("http://cardforge.org/draftAI/ping.php").equals("pong")) { Constant.Runtime.NetConn[0] = true; - } else { + } else {*/ Constant.Runtime.UpldDrft[0] = false; - } + // } setBuildInfo(new BuildInfo()); } diff --git a/src/main/java/forge/quest/data/QuestBattleManager.java b/src/main/java/forge/quest/data/QuestBattleManager.java index c5314d89661..df4dc95c3b7 100644 --- a/src/main/java/forge/quest/data/QuestBattleManager.java +++ b/src/main/java/forge/quest/data/QuestBattleManager.java @@ -18,8 +18,6 @@ import java.util.*; * @version $Id$ */ public class QuestBattleManager { - /** Constant aiDecks */ - private static transient Map aiDecks = new HashMap(); /** Constant easyAIDecks */ private static transient List easyAIDecks; /** Constant mediumAIDecks */ @@ -30,53 +28,12 @@ public class QuestBattleManager { private static transient List veryHardAIDecks; static { - List aiDeckNames = getAIDeckNames(); - easyAIDecks = readFile(ForgeProps.getFile(NewConstants.QUEST.EASY), aiDeckNames); - mediumAIDecks = readFile(ForgeProps.getFile(NewConstants.QUEST.MEDIUM), aiDeckNames); - hardAIDecks = readFile(ForgeProps.getFile(NewConstants.QUEST.HARD), aiDeckNames); - veryHardAIDecks = readFile(ForgeProps.getFile(NewConstants.QUEST.VERYHARD), aiDeckNames); + easyAIDecks = readFile(ForgeProps.getFile(NewConstants.QUEST.EASY)); + mediumAIDecks = readFile(ForgeProps.getFile(NewConstants.QUEST.MEDIUM)); + hardAIDecks = readFile(ForgeProps.getFile(NewConstants.QUEST.HARD)); + veryHardAIDecks = readFile(ForgeProps.getFile(NewConstants.QUEST.VERYHARD)); } - - /** - *

removeAIDeck.

- * Removes a deck object stored in the - *{@link forge.quest.gui.main.aiDecks} map. - * - * @param deckName a {@link java.lang.String} object. - */ - public static void removeAIDeck(String deckName) { - aiDecks.remove(deckName); - } - - /** - *

addAIDeck.

- * Adds a deck object stored in the - *{@link forge.quest.gui.main.aiDecks} map. - * - * @param d a {@link forge.deck.Deck} object. - */ - public static void addAIDeck(Deck d) { - aiDecks.put(d.getName(), d); - } - - /** - *

getAIDeckFromMap.

- * Returns a deck object stored in the - *{@link forge.quest.gui.main.aiDecks} map. - * - * @param deckName a {@link java.lang.String} object. - * @return a {@link forge.deck.Deck} object. - */ - public static Deck getAIDeckFromMap(String deckName) { - if (!aiDecks.containsKey(deckName)) { - ErrorViewer.showError(new Exception(), - "QuestData : getAIDeckFromMap(String deckName) error, deck name not found - %s", deckName); - } - - return aiDecks.get(deckName); - } - /** *

getAIDeckNames.

* Returns a list of decks stored in the @@ -87,23 +44,10 @@ public class QuestBattleManager { public static List getAIDeckNames() { return new ArrayList(aiDecks.keySet()); } - - /** - *

getDeckFromFile.

- * Returns a deck object built from a file name. - * - * @param deckName a {@link java.lang.String} object. - * @return a {@link forge.deck.Deck} object. - */ - public static Deck getAIDeckFromFile(String deckName) { - final File file = ForgeProps.getFile(NewConstants.QUEST.DECKS); - final DeckManager manager = new DeckManager(file); - return manager.getDeck(deckName); - } /** *

getOpponent.

- * + * * Badly named; AllZoneUtil already has a method called getOpponents. * ????? * @@ -178,11 +122,11 @@ public class QuestBattleManager { * @param aiDecks a {@link java.util.List} object. * @return a {@link java.util.List} object. */ - private static List readFile(File file, List aiDecks) { + private static List readFile(File file) { ArrayList list = FileUtil.readFile(file); //remove any blank lines - ArrayList noBlankLines = new ArrayList(); + ArrayList noBlankLines = new ArrayList(); String s; for (String aList : list) { s = aList.trim(); @@ -198,12 +142,6 @@ public class QuestBattleManager { file); } - for (String aList : list) { - if (!aiDecks.contains(aList)) { - aiDecks.add(aList); - } - } - return list; } diff --git a/src/main/java/forge/quest/data/QuestBoosterPack.java b/src/main/java/forge/quest/data/QuestBoosterPack.java index 579d394340c..4f88a86acbe 100644 --- a/src/main/java/forge/quest/data/QuestBoosterPack.java +++ b/src/main/java/forge/quest/data/QuestBoosterPack.java @@ -3,14 +3,22 @@ package forge.quest.data; import forge.Card; import forge.CardFilter; import forge.Constant; +import forge.card.CardDb; +import forge.card.CardPrinted; +import forge.card.CardRarity; +import forge.card.CardRules; import forge.properties.NewConstants; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.List; import java.util.NoSuchElementException; +import org.apache.commons.lang3.StringUtils; + import net.slightlymagic.braids.util.generator.GeneratorFunctions; +import net.slightlymagic.maxmtg.Predicate; import com.google.code.jyield.Generator; @@ -61,46 +69,40 @@ public class QuestBoosterPack implements NewConstants { * * @return a {@link java.util.ArrayList} object. */ - public ArrayList getQuestStarterDeck(Generator allCards, int numCommon, int numUncommon, int numRare, boolean standardPool) { - ArrayList names = new ArrayList(); + public List getQuestStarterDeck( final Predicate filter, + int numCommon, int numUncommon, int numRare ) { + ArrayList names = new ArrayList(); // Each color should have around the same amount of monocolored cards // There should be 3 Colorless cards for every 4 cards in a single color // There should be 1 Multicolor card for every 4 cards in a single color - ArrayList started = new ArrayList(); - started.add("Multicolor"); + List> colorFilters = new ArrayList>(); + colorFilters.add(CardRules.Predicates.Presets.isMulticolor); + for (int i = 0; i < 4; i++) { - if (i != 2) - started.add(Constant.Color.Colorless); + if (i != 2) { colorFilters.add(CardRules.Predicates.Presets.isColorless); } - started.addAll(Arrays.asList(Constant.Color.onlyColors)); + colorFilters.add(CardRules.Predicates.Presets.isWhite); + colorFilters.add(CardRules.Predicates.Presets.isRed); + colorFilters.add(CardRules.Predicates.Presets.isBlue); + colorFilters.add(CardRules.Predicates.Presets.isBlack); + colorFilters.add(CardRules.Predicates.Presets.isGreen); } - if (standardPool) { - // filter Cards for cards appearing in Standard Sets - ArrayList sets = new ArrayList(); + Iterable cardpool = CardDb.instance().getAllUniqueCards(); - //TODO: It would be handy if the list of any sets can be chosen - // Can someone clarify that? I don't understand it. -Braids - sets.add("M12"); - sets.add("NPH"); - sets.add("MBS"); - sets.add("SOM"); - sets.add("M11"); - sets.add("ROE"); - sets.add("WWK"); - sets.add("ZEN"); - - allCards = CardFilter.getSets(allCards, sets); - } - - names.addAll(generateCards(allCards, numCommon, Constant.Rarity.Common, null, started)); - names.addAll(generateCards(allCards, numUncommon, Constant.Rarity.Uncommon, null, started)); - names.addAll(generateCards(allCards, numRare, Constant.Rarity.Rare, null, started)); + names.addAll(generateDefinetlyColouredCards(cardpool, + Predicate.and(filter, CardPrinted.Predicates.Presets.isCommon), numCommon, colorFilters)); + names.addAll(generateDefinetlyColouredCards(cardpool, + Predicate.and(filter, CardPrinted.Predicates.Presets.isUncommon), numUncommon, colorFilters)); + names.addAll(generateDefinetlyColouredCards(cardpool, + Predicate.and(filter, CardPrinted.Predicates.Presets.isRareOrMythic), numRare, colorFilters)); return names; } + + /** * Create the list of card names at random from the given pool. @@ -112,92 +114,114 @@ public class QuestBoosterPack implements NewConstants { * @param colorOrder we shuffle this as a side effect of calling this method * @return a list of card names */ - public ArrayList generateCards(Generator allCards, int num, String rarity, String color, ArrayList colorOrder) + public ArrayList generateDefinetlyColouredCards( + Iterable source, + Predicate filter, + int cntNeeded, + List> allowedColors) { // If color is null, use colorOrder progression to grab cards - ArrayList names = new ArrayList(); + ArrayList result = new ArrayList(); - int size = colorOrder.size(); - Collections.shuffle(colorOrder); + int size = allowedColors == null ? 0 : allowedColors.size(); + Collections.shuffle(allowedColors); - allCards = CardFilter.getRarity(allCards, rarity); - int count = 0, i = 0; + int cntMade = 0, iAttempt = 0; - while (count < num) { - String name = null; + // This will prevent endless loop @ wh + int allowedMisses = (2 + size + 2) * cntNeeded; // lol, 2+2 is not magic constant! - if (color == null) { - final String color2 = colorOrder.get(i % size); + while (cntMade < cntNeeded && allowedMisses > 0) { + CardPrinted card = null; + if (size > 0) { + final Predicate color2 = allowedColors.get(iAttempt % size); if (color2 != null) { - // Mantis Issue 77: avoid calling - // getCardName(Generator, String) with null as 2nd - // parameter. - name = getCardName(allCards, color2); + card = Predicate.and(filter, color2, CardPrinted.fnGetRules).random(source); } } - if (name == null) { + if (card == null) { // We can't decide on a color, so just pick a card. - name = getCardName(allCards); + card = filter.random(source); } - if (name != null && !names.contains(name)) { - names.add(name); - count++; + if (card != null && !result.contains(card)) { + result.add(card); + cntMade++; } - i++; + else { allowedMisses--; } + iAttempt++; } - return names; + return result; } - /** - * Convenience for generateCards(cards, num, rarity, color, this.choices); - * - * @see #generateCards(Generator, int, String, String, ArrayList) - */ - public ArrayList generateCards(Generator cards, int num, String rarity, String color) { - return generateCards(cards, num, rarity, color, choices); - } - /** - * Retrieve a card name at random from the given pool of cards; - * the card must have a specific color. - * - * This forces one evaluation of the allCards Generator. - * - * @param allCards the card pool to use - * @param color a {@link java.lang.String} object. - * @return a random card name with the given color from allCards - */ - public String getCardName(Generator allCards, String color) { - return getCardName(CardFilter.getColor(allCards, color)); - } + public ArrayList generateDistinctCards( + final Iterable source, + final Predicate filter, + final int cntNeeded) + { + ArrayList result = new ArrayList(); + int cntMade = 0, iAttempt = 0; - /** - * Fetch a random card name from the given pool. - * - * This forces one evaluation of the cards Generator. - * - * @param cards the card pool from which to select - * @return a card name from cards - */ - public String getCardName(Generator cards) { - Card selected = null; - try { - selected = GeneratorFunctions.selectRandom(cards); - } - catch (NoSuchElementException ignored) { - ; - } - if (selected == null) { - // Previously, it was thought that this - // Only should happen if something is programmed wrong - // But empirical evidence contradicts this. - return null; + // This will prevent endless loop @ wh + int allowedMisses = (2 + 2) * cntNeeded; // lol, 2+2 is not magic constant! + + while (cntMade < cntNeeded && allowedMisses > 0) { + CardPrinted card = filter.random(source); + + if (card != null && !result.contains(card)) { + result.add(card); + cntMade++; + } + else { allowedMisses--; } + iAttempt++; } - - return selected.getName(); + + return result; } + + + // Left if only for backwards compatibility + public ArrayList generateCards(int num, CardRarity rarity, String color) { + Predicate whatYouWant = getPredicateForConditions(rarity, color); + return generateDistinctCards(CardDb.instance().getAllUniqueCards(), whatYouWant, num); + } + + public ArrayList generateCards(Predicate filter, int num, CardRarity rarity, String color) { + Predicate whatYouWant = Predicate.and(filter, getPredicateForConditions(rarity, color)); + return generateDistinctCards(CardDb.instance().getAllUniqueCards(), whatYouWant, num); + } + + protected Predicate getPredicateForConditions(CardRarity rarity, String color) + { + Predicate rFilter; + switch (rarity) { + case Rare: rFilter = CardPrinted.Predicates.Presets.isRareOrMythic; break; + case Common: rFilter = CardPrinted.Predicates.Presets.isCommon; break; + case Uncommon: rFilter = CardPrinted.Predicates.Presets.isUncommon; break; + default: rFilter = Predicate.getTrue(CardPrinted.class); + } + + Predicate colorFilter; + if (StringUtils.isBlank(color)) { + colorFilter = Predicate.getTrue(CardRules.class); + } else { + String col = color.toLowerCase(); + if (col.startsWith("wh")) colorFilter = CardRules.Predicates.Presets.isWhite; + else if (col.startsWith("bla")) colorFilter = CardRules.Predicates.Presets.isBlack; + else if (col.startsWith("blu")) colorFilter = CardRules.Predicates.Presets.isBlue; + else if (col.startsWith("re")) colorFilter = CardRules.Predicates.Presets.isRed; + else if (col.startsWith("col")) colorFilter = CardRules.Predicates.Presets.isColorless; + else if (col.startsWith("gre")) colorFilter = CardRules.Predicates.Presets.isGreen; + else if (col.startsWith("mul")) colorFilter = CardRules.Predicates.Presets.isMulticolor; + else colorFilter = Predicate.getTrue(CardRules.class); + } + return Predicate.and(rFilter, colorFilter, CardPrinted.fnGetRules); + } + + } + diff --git a/src/main/java/forge/quest/data/QuestData.java b/src/main/java/forge/quest/data/QuestData.java index d3a7825d3ea..c3427204b88 100644 --- a/src/main/java/forge/quest/data/QuestData.java +++ b/src/main/java/forge/quest/data/QuestData.java @@ -1,6 +1,11 @@ package forge.quest.data; import forge.*; +import forge.card.CardDb; +import forge.card.CardPool; +import forge.card.CardPoolView; +import forge.card.CardPrinted; +import forge.card.CardRarity; import forge.deck.Deck; import forge.error.ErrorViewer; import forge.game.GameLossReason; @@ -17,6 +22,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.commons.lang3.ArrayUtils; + +import net.slightlymagic.maxmtg.Predicate; + import com.google.code.jyield.Generator; import com.google.code.jyield.YieldUtils; @@ -36,14 +45,13 @@ import com.google.code.jyield.YieldUtils; * @author Forge * @version $Id$ */ -public class QuestData { +public final class QuestData { int rankIndex; int win; int lost; int life; - //private int maxLife; int questsPlayed; @@ -55,11 +63,8 @@ public class QuestData { Map myDecks = new HashMap(); - //holds String card names - List cardPool = new ArrayList(); - List newCardList = new ArrayList(); - - List shopList = new ArrayList(); + CardPool cardPool = new CardPool(); + CardPool shopList = new CardPool(); List availableQuests = new ArrayList(); List completedQuests = new ArrayList(); @@ -79,8 +84,8 @@ public class QuestData { QuestInventory inventory = new QuestInventory(); //This field holds the version of the Quest Data - /** Constant CURRENT_VERSION_NUMBER=1 */ - public static final int CURRENT_VERSION_NUMBER = 1; + /** Constant CURRENT_VERSION_NUMBER=2 */ + public static final int CURRENT_VERSION_NUMBER = 2; //This field places the version number into QD instance, //but only when the object is created through the constructor @@ -94,21 +99,17 @@ public class QuestData { */ public QuestData() { - for (int i = 0; i < QuestPreferences.getStartingBasic(); i++) { - cardPool.add("Forest"); - cardPool.add("Mountain"); - cardPool.add("Swamp"); - cardPool.add("Island"); - cardPool.add("Plains"); - } + cardPool.add(CardDb.instance().getCard("Forest", "M10"), QuestPreferences.getStartingBasic()); + cardPool.add(CardDb.instance().getCard("Mountain", "M10"), QuestPreferences.getStartingBasic()); + cardPool.add(CardDb.instance().getCard("Swamp", "M10"), QuestPreferences.getStartingBasic()); + cardPool.add(CardDb.instance().getCard("Island", "M10"), QuestPreferences.getStartingBasic()); + cardPool.add(CardDb.instance().getCard("Plains", "M10"), QuestPreferences.getStartingBasic()); - for (int i = 0; i < QuestPreferences.getStartingSnowBasic(); i++) { - cardPool.add("Snow-Covered Forest"); - cardPool.add("Snow-Covered Mountain"); - cardPool.add("Snow-Covered Swamp"); - cardPool.add("Snow-Covered Island"); - cardPool.add("Snow-Covered Plains"); - } + cardPool.add(CardDb.instance().getCard("Snow-Covered Forest", "ICE"), QuestPreferences.getStartingSnowBasic()); + cardPool.add(CardDb.instance().getCard("Snow-Covered Mountain", "ICE"), QuestPreferences.getStartingSnowBasic()); + cardPool.add(CardDb.instance().getCard("Snow-Covered Swamp", "ICE"), QuestPreferences.getStartingSnowBasic()); + cardPool.add(CardDb.instance().getCard("Snow-Covered Island", "ICE"), QuestPreferences.getStartingSnowBasic()); + cardPool.add(CardDb.instance().getCard("Snow-Covered Plains", "ICE"), QuestPreferences.getStartingSnowBasic()); initTransients(); randomizeOpponents(); @@ -148,15 +149,18 @@ public class QuestData { public void newGame(int difficulty, String m, boolean standardStart) { setDifficulty(difficulty); - Generator allCards = YieldUtils.toGenerator(AllZone.getCardFactory()); + Predicate filter = standardStart + ? CardPrinted.Predicates.Presets.isStandard + : Predicate.getTrue(CardPrinted.class); - ArrayList list = new ArrayList(); - - list.addAll(boosterPack.getQuestStarterDeck(allCards, QuestPreferences.getStartingCommons(difficulty), - QuestPreferences.getStartingUncommons(difficulty), QuestPreferences.getStartingRares(difficulty), standardStart)); + List list = boosterPack.getQuestStarterDeck( + filter, + QuestPreferences.getStartingCommons(difficulty), + QuestPreferences.getStartingUncommons(difficulty), + QuestPreferences.getStartingRares(difficulty)); //because cardPool already has basic land added to it - cardPool.addAll(list); + addAllCards(list); credits = QuestPreferences.getStartingCredits(); mode = m; @@ -183,26 +187,8 @@ public class QuestData { } - //returns Strings of the card names - - /** - *

getCardpool.

- * - * @return a {@link java.util.List} object. - */ - public List getCardpool() { - //make a copy so the internal ArrrayList cannot be changed externally - return new ArrayList(cardPool); - } - - /** - *

setCardpool.

- * - * @param pool a {@link java.util.ArrayList} object. - * @since 1.0.15 - */ - public void setCardpool(ArrayList pool) { - cardPool = pool; + public CardPool getCardpool() { + return cardPool; } /** @@ -210,12 +196,11 @@ public class QuestData { * * @return a {@link java.util.List} object. */ - public List getShopList() { - if (shopList != null) { - return new ArrayList(shopList); - } else { - return null; + public CardPoolView getShopList() { + if (shopList.isEmpty()) { + generateCardsInShop(); } + return shopList; } /** @@ -223,8 +208,11 @@ public class QuestData { * * @param list a {@link java.util.List} object. */ - public void setShopList(List list) { - shopList = list; + public void generateCardsInShop() { + ReadBoosterPack pack = new ReadBoosterPack(); + CardPoolView fromBoosters = pack.getShopCards(getWin(), getLevel()); + shopList.clear(); + shopList.addAll(fromBoosters); } @@ -284,7 +272,7 @@ public class QuestData { *

clearShopList.

*/ public void clearShopList() { - shopList.clear(); + if (null != shopList) { shopList.clear(); } } @@ -328,17 +316,7 @@ public class QuestData { Deck d = myDecks.get(deckName); - //below is probably not needed - - //remove old cards from card pool - for (int i = 0; i < d.countSideboard(); i++) { - d.removeSideboard(i); - } - - //add all cards to card pool - for (int i = 0; i < cardPool.size(); i++) { - d.addSideboard(cardPool.get(i)); - } + d.clearSideboard(); return d; } @@ -357,41 +335,24 @@ public class QuestData { } - //get new cards that were added to your card pool by addCards() - - /** - *

getAddedCards.

- * - * @return a {@link java.util.List} object. - */ - public List getAddedCards() { - return new ArrayList(newCardList); - } - //adds 11 cards, to the current card pool //(I chose 11 cards instead of 15 in order to make things more challenging) /** *

addCards.

*/ - public ArrayList addCards( List setsFilter ) { - Generator cards = YieldUtils.toGenerator(AllZone.getCardFactory()); - if ( setsFilter != null ) - cards = CardFilter.getSets(cards, setsFilter); - + public ArrayList addCards( List setsFilter ) { int nCommon = QuestPreferences.getNumCommon(); int nUncommon = QuestPreferences.getNumUncommon(); int nRare = QuestPreferences.getNumRare(); + Predicate fSets = CardPrinted.Predicates.printedInSets(setsFilter, true); - ArrayList newCards = new ArrayList(); - newCards.addAll(boosterPack.generateCards(cards, nCommon, Constant.Rarity.Common, null)); - newCards.addAll(boosterPack.generateCards(cards, nUncommon, Constant.Rarity.Uncommon, null)); - newCards.addAll(boosterPack.generateCards(cards, nRare, Constant.Rarity.Rare, null)); + ArrayList newCards = new ArrayList(); + newCards.addAll(boosterPack.generateCards(fSets, nCommon, CardRarity.Common, null)); + newCards.addAll(boosterPack.generateCards(fSets, nUncommon, CardRarity.Uncommon, null)); + newCards.addAll(boosterPack.generateCards(fSets, nRare, CardRarity.Rare, null)); - cardPool.addAll(newCards); - - //getAddedCards() uses newCardList - newCardList = newCards; + addAllCards(newCards); return newCards; } @@ -401,95 +362,40 @@ public class QuestData { * @param n a int. * @return a {@link java.util.ArrayList} object. */ - public ArrayList addRandomRare(int n) { - Generator allCards = YieldUtils.toGenerator(AllZone.getCardFactory()); - ArrayList newCards = new ArrayList(); - newCards.addAll(boosterPack.generateCards(allCards, n, Constant.Rarity.Rare, null)); + public ArrayList addRandomRare(int n) { + ArrayList newCards = new ArrayList(); + newCards.addAll(boosterPack.generateCards(n, CardRarity.Rare, null)); - cardPool.addAll(newCards); - newCardList.addAll(newCards); + addAllCards(newCards); return newCards; } + public void addAllCards(Iterable newCards) { + for (CardPrinted card : newCards) { + cardPool.add( card ); + } + } + /** *

addRandomRare.

* * @return a {@link java.lang.String} object. */ - public String addRandomRare() { + public CardPrinted addRandomRare() { return addRandomRare(1).get(0); } - /** - *

addCard.

- * - * @param c a {@link forge.Card} object. - */ - public void addCard(Card c) { - cardPool.add(c.getName()); - } - - /** - *

addCard.

- * - * @param s a {@link java.lang.String} object. - */ - public void addCard(String s) { - cardPool.add(s); - } - - /** - *

removeCard.

- * - * @param c a {@link forge.Card} object. - */ - public void removeCard(Card c) { - - String s = c.getName(); - if (!cardPool.contains(s)) { - return; - } - - for (int i = 0; i < cardPool.size(); i++) { - String str = cardPool.get(i); - if (str.equals(s)) { - cardPool.remove(i); - break; - } - } - } /** *

addCardToShopList.

* * @param c a {@link forge.Card} object. */ - public void addCardToShopList(Card c) { - shopList.add(c.getName()); + public void addCardToShopList(CardPrinted c) { + shopList.add(c); } - /** - *

removeCardFromShopList.

- * - * @param c a {@link forge.Card} object. - */ - public void removeCardFromShopList(Card c) { - String s = c.getName(); - if (!shopList.contains(s)) { - return; - } - - for (int i = 0; i < shopList.size(); i++) { - String str = shopList.get(i); - if (str.equals(s)) { - shopList.remove(i); - break; - } - } - } - - public final int getCreditsRewardForAltWin(final GameLossReason whyAiLost) { int rewardAltWinCondition = 0; switch (whyAiLost) { @@ -504,6 +410,9 @@ public class QuestData { case DidNotLoseYet: // must be player's alternate win condition: felidar, helix pinnacle and like this rewardAltWinCondition = QuestPreferences.getMatchRewardAltWinBonus(); break; + case SpellEffect: // Door to Nothingness or something like this + rewardAltWinCondition = QuestPreferences.getMatchRewardAltWinBonus(); + break; default: // this .checkstyle forces us to write some idiotic code rewardAltWinCondition = 0; } @@ -569,18 +478,6 @@ public class QuestData { //gets all of the cards that are in the cardpool - /** - *

getCards.

- * - * @return a {@link java.util.List} object. - */ - public List getCards() { - //copy CardList in order to keep private variables private - //if we just return cardPool, it could be changed externally - return new ArrayList(cardPool); - } - - /** *

getTotalNumberOfGames.

* @@ -723,6 +620,27 @@ public class QuestData { return mode; } + public double getSellMutliplier() { + double multi = 0.20 + (0.001 * getWin()); + if (multi > 0.6) + multi = 0.6; + + if (getMode().equals(forge.quest.data.QuestData.FANTASY)) { + if (getInventory().getItemLevel("Estates") == 1) + multi += 0.01; + else if (getInventory().getItemLevel("Estates") == 2) + multi += 0.0175; + else if (getInventory().getItemLevel("Estates") >= 3) + multi += 0.025; + } + return multi; + } + + public int getSellPriceLimit() { + return getWin() <= 50 ? 1000 : Integer.MAX_VALUE; + } + + //should be called first, because the difficultly won't change /** @@ -847,25 +765,6 @@ public class QuestData { ForgeProps.getFile(NewConstants.QUEST.XMLDATA).exists(); } - /** - *

main.

- * - * @param args an array of {@link java.lang.String} objects. - */ - public static void main(String[] args) { - QuestData q = new QuestData(); - for (int i = 0; i < 20; i++) { - q.addCards( null ); - } - - for (int i = 0; i < 10; i++) { - q.saveData(); - q = QuestDataIO.loadData(); - } - - System.exit(1); - } - /** *

Getter for the field petManager.

* @@ -877,14 +776,6 @@ public class QuestData { //get new cards that were added to your card pool by addCards() - /** - *

addToNewList.

- * - * @param added a {@link java.util.ArrayList} object. - */ - public void addToNewList(ArrayList added) { - newCardList.addAll(added); - } /** *

readResolve.

@@ -913,4 +804,18 @@ public class QuestData { public long getRandomSeed() { return randomSeed; } + + public void buyCard(final CardPrinted card, final int value) { + if (credits >= value) { + credits -= value; + getCardpool().add(card); + shopList.remove(card); + } + } + + public void sellCard(final CardPrinted card, final int price) { + if (price > 0) { credits += price; } + getCardpool().remove(card); + // remove from decks right here + } } diff --git a/src/main/java/forge/quest/data/QuestDataIO.java b/src/main/java/forge/quest/data/QuestDataIO.java index d246f288f54..1d71a8aa378 100644 --- a/src/main/java/forge/quest/data/QuestDataIO.java +++ b/src/main/java/forge/quest/data/QuestDataIO.java @@ -1,7 +1,15 @@ package forge.quest.data; import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.mapper.MapperWrapper; +import com.thoughtworks.xstream.converters.Converter; +import com.thoughtworks.xstream.converters.MarshallingContext; +import com.thoughtworks.xstream.converters.UnmarshallingContext; + +import forge.card.CardDb; +import forge.card.CardPrinted; import forge.error.ErrorViewer; import forge.properties.ForgeProps; import forge.properties.NewConstants; @@ -55,6 +63,8 @@ public class QuestDataIO { } IgnoringXStream xStream = new IgnoringXStream(); + xStream.registerConverter(new CardReferenceToXml()); + xStream.alias("cref", CardPrinted.class); data = (QuestData) xStream.fromXML(xml.toString()); if (data.versionNumber != QuestData.CURRENT_VERSION_NUMBER) { @@ -109,6 +119,12 @@ public class QuestDataIO { newData.inventory.setItemLevel("Zeppelin", 1); } break; + + case 1: + // card names are stored as plain text - need to read them from there + + break; + } //mark the QD as the latest version @@ -129,12 +145,20 @@ public class QuestDataIO { File f = ForgeProps.getFile(NewConstants.QUEST.XMLDATA); BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(f)); GZIPOutputStream zout = new GZIPOutputStream(bout); + + BufferedOutputStream bout_unp = new BufferedOutputStream(new FileOutputStream(f+".xml")); XStream xStream = new XStream(); + xStream.registerConverter(new CardReferenceToXml()); + xStream.alias("cref", CardPrinted.class); xStream.toXML(qd, zout); + xStream.toXML(qd, bout_unp); zout.flush(); zout.close(); + + bout_unp.flush(); + bout_unp.close(); } catch (Exception ex) { ErrorViewer.showError(ex, "Error saving Quest Data."); throw new RuntimeException(ex); @@ -163,4 +187,31 @@ public class QuestDataIO { }; } } + + private static class CardReferenceToXml implements Converter { + @SuppressWarnings("rawtypes") + @Override + public boolean canConvert(Class clasz) { + return clasz.equals(CardPrinted.class); + } + + @Override + public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { + CardPrinted cref = (CardPrinted) source; + writer.addAttribute("s", cref.getSet()); + writer.addAttribute("i", Integer.toString(cref.getArtIndex())); + if (cref.isFoil()) { writer.addAttribute("foil", "1"); } + writer.addAttribute("n", cref.getName()); + } + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + String name = reader.getAttribute("n"); + String set = reader.getAttribute("s"); + short index = Short.parseShort(reader.getAttribute("i")); + boolean foil = "1".equals(reader.getAttribute("foil")); + CardPrinted card = CardDb.instance().getCard(name, set, index); + return foil ? CardPrinted.makeFoiled(card) : card; + } + } } diff --git a/src/main/java/forge/quest/data/QuestUtil.java b/src/main/java/forge/quest/data/QuestUtil.java index 1ae4c38a18f..3fbf9a71748 100644 --- a/src/main/java/forge/quest/data/QuestUtil.java +++ b/src/main/java/forge/quest/data/QuestUtil.java @@ -1,6 +1,7 @@ package forge.quest.data; import forge.*; +import forge.card.CardRarity; import java.util.ArrayList; @@ -97,13 +98,11 @@ public class QuestUtil { int id = qa.getId(); - Generator cards = YieldUtils.toGenerator(AllZone.getCardFactory()); - if (id == 1) //White Dungeon { qa.addCompy("Divine Presence"); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, Constant.Color.White)); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, Constant.Color.White)); } else if (id == 2) //Blue Dungeon { CardList humanList = new CardList(); @@ -118,17 +117,17 @@ public class QuestUtil { qa.addCompy("Forced Fruition"); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, Constant.Color.Blue)); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, Constant.Color.Blue)); } else if (id == 3) //Black Dungeon { qa.addCompy("Infernal Genesis"); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, Constant.Color.Black)); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, Constant.Color.Black)); } else if (id == 4) //Red Dungeon { qa.addCompy("Furnace of Rath"); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, Constant.Color.Red)); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, Constant.Color.Red)); } else if (id == 5) //Green Dungeon { CardList humanList = new CardList(); @@ -144,17 +143,17 @@ public class QuestUtil { qa.addCompy("Eladamri's Vineyard"); qa.addCompy("Upwelling"); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, Constant.Color.Green)); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, Constant.Color.Green)); } else if (id == 6) //Colorless Dungeon { for (int i = 0; i < 3; i++) qa.addCompy("Eon Hub"); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, Constant.Color.Colorless)); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, Constant.Color.Colorless)); } else if (id == 7) //Gold Dungeon { qa.addCompy("Darksteel Ingot"); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, "Multicolor")); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, "Multicolor")); } else if (id == 8) { CardList humanList = new CardList(); for (int i = 0; i < 3; i++) { @@ -179,7 +178,7 @@ public class QuestUtil { humanList.add(c); } qa.setHuman(humanList); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, null)); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, null)); } else if (id == 9) { CardList humanList = new CardList(); Card c = AllZone.getCardFactory().getCard("Trusty Machete", AllZone.getHumanPlayer()); @@ -194,7 +193,7 @@ public class QuestUtil { for (int i = 0; i < 3; i++) qa.addCompy("Wall of Wood"); - qa.setCardRewardList(pack.generateCards(cards, 4, Constant.Rarity.Rare, Constant.Color.Green)); + qa.setCardRewardList(pack.generateCards(4, CardRarity.Rare, Constant.Color.Green)); } else if (id == 10) { CardList humanList = new CardList(); @@ -232,7 +231,7 @@ public class QuestUtil { qa.addCompy("Scathe Zombies"); qa.addCompy("Mass of Ghouls"); - qa.setCardRewardList(pack.generateCards(cards, 4, Constant.Rarity.Rare, Constant.Color.Black)); + qa.setCardRewardList(pack.generateCards(4, CardRarity.Rare, Constant.Color.Black)); } else if (id == 11) // The King's Contest { CardList humanList = new CardList(); @@ -247,7 +246,7 @@ public class QuestUtil { qa.addCompy("Loyal Retainers"); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, null)); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, null)); } else if (id == 12) // Barroom Brawl { CardList humanList = new CardList(); @@ -278,7 +277,7 @@ public class QuestUtil { qa.addCompy("Lowland Giant"); - qa.setCardRewardList(pack.generateCards(cards, 4, Constant.Rarity.Rare, null)); + qa.setCardRewardList(pack.generateCards(4, CardRarity.Rare, null)); } else if (id == 13) // The Court Jester { CardList humanList = new CardList(); @@ -293,7 +292,7 @@ public class QuestUtil { qa.addCompy("Teferi's Puzzle Box"); - qa.setCardRewardList(pack.generateCards(cards, 4, Constant.Rarity.Rare, "Multicolor")); + qa.setCardRewardList(pack.generateCards(4, CardRarity.Rare, "Multicolor")); } else if (id == 14) // Ancient Battlefield { CardList humanList = new CardList(); @@ -315,7 +314,7 @@ public class QuestUtil { qa.addCompy(compySetupCards[i]); } - qa.setCardRewardList(pack.generateCards(cards, 4, Constant.Rarity.Rare, null)); + qa.setCardRewardList(pack.generateCards(4, CardRarity.Rare, null)); } else if (id == 15) // Don't Play With Matches { CardList humanList = new CardList(); @@ -337,7 +336,7 @@ public class QuestUtil { qa.addCompy(compySetupCards[i]); } - qa.setCardRewardList(pack.generateCards(cards, 4, Constant.Rarity.Rare, Constant.Color.Red)); + qa.setCardRewardList(pack.generateCards(4, CardRarity.Rare, Constant.Color.Red)); } else if (id == 16) // Mines of Kazum Durl { CardList humanList = new CardList(); @@ -360,7 +359,7 @@ public class QuestUtil { qa.addCompy(compySetupCards[i]); } - qa.setCardRewardList(pack.generateCards(cards, 4, Constant.Rarity.Rare, Constant.Color.Green)); + qa.setCardRewardList(pack.generateCards(4, CardRarity.Rare, Constant.Color.Green)); } else if (id == 17) // House Party { CardList humanList = new CardList(); @@ -382,7 +381,7 @@ public class QuestUtil { qa.addCompy(compySetupCards[i]); } - qa.setCardRewardList(pack.generateCards(cards, 4, Constant.Rarity.Rare, Constant.Color.Colorless)); + qa.setCardRewardList(pack.generateCards(4, CardRarity.Rare, Constant.Color.Colorless)); } else if (id == 18) // Crows in the Field { CardList humanList = new CardList(); @@ -404,7 +403,7 @@ public class QuestUtil { qa.addCompy(compySetupCards[i]); } - qa.setCardRewardList(pack.generateCards(cards, 5, Constant.Rarity.Rare, null)); + qa.setCardRewardList(pack.generateCards(5, CardRarity.Rare, null)); } else if (id == 19) // The Desert Caravan { CardList humanList = new CardList(); @@ -426,7 +425,7 @@ public class QuestUtil { qa.addCompy(compySetupCards[i]); } - qa.setCardRewardList(pack.generateCards(cards, 5, Constant.Rarity.Rare, null)); + qa.setCardRewardList(pack.generateCards(5, CardRarity.Rare, null)); } else if (id == 20) // Blood Oath { CardList humanList = new CardList(); @@ -448,7 +447,7 @@ public class QuestUtil { qa.addCompy(compySetupCards[i]); } - qa.setCardRewardList(pack.generateCards(cards, 5, Constant.Rarity.Rare, Constant.Color.Colorless)); + qa.setCardRewardList(pack.generateCards(5, CardRarity.Rare, Constant.Color.Colorless)); } else if (id == 21) // Private Domain { CardList humanList = new CardList(); @@ -467,7 +466,7 @@ public class QuestUtil { for (int i = 0; i < 5; i++) qa.addCompy(compySetupCards[i]); - qa.setCardRewardList(pack.generateCards(cards, 6, Constant.Rarity.Rare, null)); + qa.setCardRewardList(pack.generateCards(6, CardRarity.Rare, null)); } else if (id == 22) // Pied Piper { CardList humanList = new CardList(); @@ -488,7 +487,7 @@ public class QuestUtil { for (int i = 0; i < 2; i++) qa.addCompy(compySetupCards[i]); - qa.setCardRewardList(pack.generateCards(cards, 3, Constant.Rarity.Rare, null)); + qa.setCardRewardList(pack.generateCards(3, CardRarity.Rare, null)); } } diff --git a/src/main/java/forge/quest/gui/main/QuestMainPanel.java b/src/main/java/forge/quest/gui/main/QuestMainPanel.java index 387e1f1a670..f2f084fcfcb 100644 --- a/src/main/java/forge/quest/gui/main/QuestMainPanel.java +++ b/src/main/java/forge/quest/gui/main/QuestMainPanel.java @@ -4,6 +4,8 @@ package forge.quest.gui.main; import forge.*; import forge.deck.Deck; import forge.gui.GuiUtils; +import forge.gui.deckeditor.CardShop; +import forge.gui.deckeditor.DeckEditorQuest; import forge.quest.data.QuestBattleManager; import forge.quest.data.QuestData; import forge.quest.data.item.QuestItemZeppelin; @@ -588,7 +590,7 @@ public class QuestMainPanel extends QuestAbstractPanel { } }; - Gui_Quest_DeckEditor g = new Gui_Quest_DeckEditor(); + DeckEditorQuest g = new DeckEditorQuest(); g.show(exit); g.setVisible(true); @@ -617,7 +619,7 @@ public class QuestMainPanel extends QuestAbstractPanel { } }; - Gui_CardShop g = new Gui_CardShop(questData); + CardShop g = new CardShop(questData); g.show(exit); g.setVisible(true); diff --git a/src/main/java/forge/view/swing/ApplicationView.java b/src/main/java/forge/view/swing/ApplicationView.java index dd95339ac04..ee7dd1f1f37 100644 --- a/src/main/java/forge/view/swing/ApplicationView.java +++ b/src/main/java/forge/view/swing/ApplicationView.java @@ -99,8 +99,6 @@ public class ApplicationView implements FView { Log.error("Error loading preferences: " + exn); } - OldGuiNewGame.loadDynamicGamedata(); - SwingUtilities.invokeLater(new Runnable() { // NOPMD by Braids on 8/7/11 1:07 PM: this isn't a web app public void run() { final ForgePreferences finalPreferences = model.getPreferences(); diff --git a/src/main/java/forge/view/swing/Main.java b/src/main/java/forge/view/swing/Main.java index 8d41334be04..a5a95ffc0d5 100644 --- a/src/main/java/forge/view/swing/Main.java +++ b/src/main/java/forge/view/swing/Main.java @@ -32,8 +32,12 @@ public final class Main { final FModel model = new FModel(null); Singletons.setModel(model); + // Need this soon after card factory is loaded + OldGuiNewGame.loadDynamicGamedata(); + // TODO: this code should go elsewhere, like wherever we start a new game. // It is only here to maintain semantic equality with the current code base. + model.resetGameState(); view.setModel(model); diff --git a/src/main/java/forge/view/swing/OldGuiNewGame.java b/src/main/java/forge/view/swing/OldGuiNewGame.java index bce4db1bfee..d8f1b806825 100644 --- a/src/main/java/forge/view/swing/OldGuiNewGame.java +++ b/src/main/java/forge/view/swing/OldGuiNewGame.java @@ -3,6 +3,7 @@ package forge.view.swing; import arcane.ui.util.ManaSymbols; import com.esotericsoftware.minlog.Log; import forge.*; +import forge.card.CardPool; import forge.deck.Deck; import forge.deck.DeckManager; import forge.deck.generate.*; @@ -10,6 +11,8 @@ import forge.error.BugzReporter; import forge.error.ErrorViewer; import forge.gui.GuiUtils; import forge.gui.ListChooser; +import forge.gui.deckeditor.Gui_BoosterDraft; +import forge.gui.deckeditor.DeckEditor; import forge.properties.ForgePreferences; import forge.properties.ForgePreferences.CardSizeType; import forge.properties.ForgePreferences.StackOffsetType; @@ -53,7 +56,7 @@ public class OldGuiNewGame extends JFrame implements NewConstants, NewConstants. // with the new IO, there's no reason to use different instances private List allDecks; /** Constant editor. */ - private static Gui_DeckEditor editor; + private static DeckEditor editor; private JLabel titleLabel = new JLabel(); private JLabel jLabel2 = new JLabel(); @@ -317,13 +320,11 @@ public class OldGuiNewGame extends JFrame implements NewConstants, NewConstants. "choice <<" + safeToString(o) + ">> does not equal any of the sealedTypes."); } - CardList sDeck = sd.getCardpool(); + CardPool sDeck = sd.getCardpool(); - if (sDeck.size() > 1) { + if (sDeck.countAll() > 1) { - for (int i = 0; i < sDeck.size(); i++) { - deck.addSideboard(sDeck.get(i).getName() + "|" + sDeck.get(i).getCurSetCode()); - } + deck.addSideboard(sDeck); for (int i = 0; i < Constant.Color.BasicLands.length; i++) { for (int j = 0; j < 18; j++) { @@ -340,7 +341,7 @@ public class OldGuiNewGame extends JFrame implements NewConstants, NewConstants. Constant.Runtime.HumanDeck[0] = deck; Constant.Runtime.GameType[0] = Constant.GameType.Sealed; - Deck aiDeck = sd.buildAIDeck(sd.getCardpool()); + Deck aiDeck = sd.buildAIDeck(sDeck.toForgeCardList()); aiDeck.setName("AI_" + sDeckName); aiDeck.addMetaData("PlayerType", "AI"); deckManager.addDeck(aiDeck); @@ -625,7 +626,7 @@ public class OldGuiNewGame extends JFrame implements NewConstants, NewConstants. final void deckEditorButtonActionPerformed(final ActionEvent e) { if (editor == null) { - editor = new Gui_DeckEditor(); + editor = new DeckEditor(); Command exit = new Command() { private static final long serialVersionUID = -9133358399503226853L; @@ -645,8 +646,8 @@ public class OldGuiNewGame extends JFrame implements NewConstants, NewConstants. // this for real, feel free. // This make it so the second time you open the Deck Editor, typing a // card name and pressing enter will filter - javax.swing.JRootPane rootPane = editor.getRootPane(); - rootPane.setDefaultButton(editor.filterButton); + //javax.swing.JRootPane rootPane = editor.getRootPane(); + //rootPane.setDefaultButton(editor.filterButton); editor.setVisible(true); diff --git a/src/test/java/forge/BoosterDraftAITest.java b/src/test/java/forge/BoosterDraftAITest.java index 35313546087..60da04b1d16 100644 --- a/src/test/java/forge/BoosterDraftAITest.java +++ b/src/test/java/forge/BoosterDraftAITest.java @@ -1,5 +1,9 @@ package forge; +import java.util.List; + +import forge.card.CardPool; +import forge.card.CardPrinted; import forge.deck.Deck; import org.testng.annotations.Test; @@ -17,15 +21,17 @@ public class BoosterDraftAITest { Deck[] deck = ai.getDecks(); for (int outer = 0; outer < 7; outer++) { - System.out.print(deck[outer].countMain() + " - "); + Deck thisDeck = deck[outer]; + System.out.print(thisDeck.countMain() + " - "); + List cards = thisDeck.getMain().toFlatList(); for (int i = 0; i < 16; i++) - System.out.print(deck[outer].getMain(i) + ", "); + System.out.print(cards.get(i) + ", "); System.out.println(""); for (int i = 16; i < 22; i++) - System.out.print(deck[outer].getMain(i) + ", "); + System.out.print(cards.get(i) + ", "); System.out.println("\n"); }//for outer @@ -35,13 +41,14 @@ public class BoosterDraftAITest { public void runTest(BoosterDraftAI ai) { ReadDraftBoosterPack booster = new ReadDraftBoosterPack(); for (int outer = 0; outer < 1; outer++) { - CardList allBooster = new CardList(); + CardPool allBooster = new CardPool(); for (int i = 0; i < 21; i++) allBooster.addAll(booster.getBoosterPack()); - - int stop = allBooster.size(); + + CardList forgeCardlist = allBooster.toForgeCardList(); + int stop = forgeCardlist.size(); for (int i = 0; i < stop; i++) { - ai.choose(allBooster, i); + forgeCardlist.remove(ai.choose(forgeCardlist, i)); } //ai.checkDeckList(ai.deck); } diff --git a/src/test/java/forge/BoosterDraftTest.java b/src/test/java/forge/BoosterDraftTest.java index 4faa71a3717..37bafb5c733 100644 --- a/src/test/java/forge/BoosterDraftTest.java +++ b/src/test/java/forge/BoosterDraftTest.java @@ -1,5 +1,7 @@ package forge; +import forge.card.CardPoolView; +import forge.card.CardPrinted; import forge.deck.Deck; import org.testng.annotations.Test; @@ -28,14 +30,14 @@ public class BoosterDraftTest implements BoosterDraft { * * @return a {@link forge.CardList} object. */ - public CardList nextChoice() { + public CardPoolView nextChoice() { n--; ReadDraftBoosterPack pack = new ReadDraftBoosterPack(); return pack.getBoosterPack(); } /** {@inheritDoc} */ - public void setChoice(Card c) { + public void setChoice(CardPrinted c) { System.out.println(c.getName()); } diff --git a/src/test/java/forge/BoosterDraft_1Test.java b/src/test/java/forge/BoosterDraft_1Test.java index 8ebfe28f8cf..d35da7dab44 100644 --- a/src/test/java/forge/BoosterDraft_1Test.java +++ b/src/test/java/forge/BoosterDraft_1Test.java @@ -1,7 +1,12 @@ package forge; +import net.slightlymagic.maxmtg.Predicate; + import org.testng.annotations.Test; +import forge.card.CardRules; +import forge.card.CardPoolView; + /** * Unit test for simple App. @@ -16,9 +21,9 @@ public class BoosterDraft_1Test { public void BoosterDraft_1Test1() throws Exception { BoosterDraft_1 draft = new BoosterDraft_1(); while (draft.hasNextChoice()) { - CardList list = draft.nextChoice(); - System.out.println(list.size()); - draft.setChoice(list.get(0)); + CardPoolView list = draft.nextChoice(); + System.out.println(list.countAll()); + draft.setChoice(Predicate.getTrue(CardRules.class).first(list, CardPoolView.fnToCard, CardPoolView.fnToReference)); } } } diff --git a/src/test/java/forge/GuiBoosterDraftTest.java b/src/test/java/forge/GuiBoosterDraftTest.java index ca690a40a12..1eedb49cc1b 100644 --- a/src/test/java/forge/GuiBoosterDraftTest.java +++ b/src/test/java/forge/GuiBoosterDraftTest.java @@ -1,6 +1,7 @@ package forge; import forge.deck.Deck; +import forge.gui.deckeditor.Gui_BoosterDraft; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/src/test/java/forge/GuiFilterTest.java b/src/test/java/forge/GuiFilterTest.java deleted file mode 100644 index 304190c693c..00000000000 --- a/src/test/java/forge/GuiFilterTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package forge; - -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * Created by IntelliJ IDEA. - * User: dhudson - */ -@Test(groups = {"UnitTest"}) -public class GuiFilterTest { - /** - * - * - */ - @Test(groups = {"UnitTest", "fast"}) - public void guiFilterTest1() { - try { - GuiFilter dialog = new GuiFilter(null, null); - dialog.setVisible(true); - Assert.assertNotNull(dialog); - dialog.dispose(); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/test/java/forge/GuiQuestFilterTest.java b/src/test/java/forge/GuiQuestFilterTest.java deleted file mode 100644 index b33856bc8da..00000000000 --- a/src/test/java/forge/GuiQuestFilterTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package forge; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import javax.swing.*; - -/** - * Created by IntelliJ IDEA. - * User: dhudson - */ -@Test(groups = {"UnitTest"}) -public class GuiQuestFilterTest { - /** - * - * - */ - @Test(groups = {"UnitTest", "fast"}) - public void guiQuestFilterTest1() { - try { - GuiQuestFilter dialog = new GuiQuestFilter(null, null); - dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); - dialog.setVisible(true); - Assert.assertNotNull(dialog); - dialog.dispose(); - } catch (Exception e) { - e.printStackTrace(); - } - } -}