This commit is contained in:
jendave
2011-08-06 02:37:41 +00:00
parent e0630099c5
commit e0224bd465
203 changed files with 107449 additions and 0 deletions

6
.classpath Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="src"/>
</classpath>

202
.gitattributes vendored
View File

@@ -1,2 +1,204 @@
* text=auto !eol
/.classpath -text
/.project -text
.settings/org.eclipse.jdt.core.prefs -text
/delete-me.txt svneol=native#text/plain
src/.classpath -text
src/.project -text
src/2009-10-12-00.txt -text svneol=native#text/plain
src/Ability.java svneol=native#text/plain
src/Ability_Activated.java svneol=native#text/plain
src/Ability_Hand.java svneol=native#text/plain
src/Ability_Mana.java -text svneol=native#text/plain
src/Ability_Tap.java svneol=native#text/plain
src/All.java svneol=native#text/plain
src/AllZone.java svneol=native#text/plain
src/BackgroundPanel.java -text svneol=native#text/plain
src/BoosterDraft.java svneol=native#text/plain
src/BoosterDraftAI.java svneol=native#text/plain
src/BoosterPack.java svneol=native#text/plain
src/ButtonUtil.java svneol=native#text/plain
src/Card.java svneol=native#text/plain
src/CardDetailUtil.java svneol=native#text/plain
src/CardFactory.java svneol=native#text/plain
src/CardFactoryUtil.java svneol=native#text/plain
src/CardList.java svneol=native#text/plain
src/CardListFilter.java svneol=native#text/plain
src/CardListUtil.java svneol=native#text/plain
src/CardPanel.java svneol=native#text/plain
src/CardUtil.java svneol=native#text/plain
src/Combat.java svneol=native#text/plain
src/CombatPlaneswalker.java svneol=native#text/plain
src/CombatUtil.java svneol=native#text/plain
src/Command.java svneol=native#text/plain
src/CommandArgs.java svneol=native#text/plain
src/CommandList.java svneol=native#text/plain
src/CommandReturn.java svneol=native#text/plain
src/Computer.java svneol=native#text/plain
src/ComputerAI_Burn.java svneol=native#text/plain
src/ComputerAI_Burn2.java svneol=native#text/plain
src/ComputerAI_General.java svneol=native#text/plain
src/ComputerAI_Input.java svneol=native#text/plain
src/ComputerAI_Rats2.java svneol=native#text/plain
src/ComputerAI_StackNotEmpty.java svneol=native#text/plain
src/ComputerAI_Testing.java svneol=native#text/plain
src/ComputerAI_counterSpells.java -text svneol=native#text/plain
src/ComputerUtil.java -text svneol=native#text/plain
src/ComputerUtil_Attack2.java svneol=native#text/plain
src/ComputerUtil_Block2.java svneol=native#text/plain
src/Computer_Cleanup.java svneol=native#text/plain
src/Computer_Draw.java svneol=native#text/plain
src/Computer_Race.java svneol=native#text/plain
src/Constant.java svneol=native#text/plain
src/Deck.java svneol=native#text/plain
src/DeckIO.java svneol=native#text/plain
src/DefaultPlayerZone.java svneol=native#text/plain
src/Display.java svneol=native#text/plain
src/EndOfTurn.java svneol=native#text/plain
src/ErrorViewer.java svneol=native#text/plain
src/ExternalPanel.java svneol=native#text/plain
src/FileUtil.java -text svneol=native#text/plain
src/GameAction.java svneol=native#text/plain
src/GameActionUtil.java svneol=native#text/plain
src/GenerateConstructedDeck.java svneol=native#text/plain
src/GenerateConstructedMultiColorDeck.java -text svneol=native#text/plain
src/GenerateDraftDeck.java svneol=native#text/plain
src/GenerateSealedDeck.java svneol=native#text/plain
src/GuiDisplay.java svneol=native#text/plain
src/GuiDisplay2.java svneol=native#text/plain
src/GuiDisplay3.java -text svneol=native#text/plain
src/GuiDisplayUtil.java svneol=native#text/plain
src/GuiInput.java svneol=native#text/plain
src/Gui_BoosterDraft.java svneol=native#text/plain
src/Gui_DeckEditor.java -text svneol=native#text/plain
src/Gui_DeckEditor_Menu.java svneol=native#text/plain
src/Gui_DownloadPictures.java svneol=native#text/plain
src/Gui_MultipleBlockers.java svneol=native#text/plain
src/Gui_NewGame.java svneol=native#text/plain
src/Gui_Quest.java svneol=native#text/plain
src/Gui_QuestOptions.java svneol=native#text/plain
src/Gui_Quest_DeckEditor.java -text svneol=native#text/plain
src/Gui_Quest_DeckEditor_Menu.java -text svneol=native#text/plain
src/Gui_SealedDeck.java svneol=native#text/plain
src/Gui_SetEditor.java svneol=native#text/plain
src/Gui_Welcome.java svneol=native#text/plain
src/Gui_WinLose.java svneol=native#text/plain
src/IO.java svneol=native#text/plain
src/ImageCache.java svneol=native#text/plain
src/ImageJPanel.java -text svneol=native#text/plain
src/ImageUtil.java svneol=native#text/plain
src/Input.java svneol=native#text/plain
src/InputControl.java svneol=native#text/plain
src/InputUtil.java svneol=native#text/plain
src/Input_Attack.java svneol=native#text/plain
src/Input_Attack_Instant.java -text svneol=native#text/plain
src/Input_Attack_Planeswalker.java svneol=native#text/plain
src/Input_Before_Attack_Instant.java -text svneol=native#text/plain
src/Input_Block.java svneol=native#text/plain
src/Input_Block_Instant.java svneol=native#text/plain
src/Input_Block_Planeswalker.java svneol=native#text/plain
src/Input_Cleanup.java svneol=native#text/plain
src/Input_CombatDamage.java svneol=native#text/plain
src/Input_Draw.java svneol=native#text/plain
src/Input_EOT.java svneol=native#text/plain
src/Input_FirstStrikeDamage.java -text svneol=native#text/plain
src/Input_Main.java svneol=native#text/plain
src/Input_Mulligan.java svneol=native#text/plain
src/Input_NoCost_TapAbility.java svneol=native#text/plain
src/Input_PayManaCost.java svneol=native#text/plain
src/Input_PayManaCostUtil.java svneol=native#text/plain
src/Input_PayManaCost_Ability.java svneol=native#text/plain
src/Input_StackNotEmpty.java svneol=native#text/plain
src/Input_Untap.java svneol=native#text/plain
src/KeyListenerTest.java -text svneol=native#text/plain
src/MagicStack.java svneol=native#text/plain
src/ManaCost.java svneol=native#text/plain
src/ManaPool.java svneol=native#text/plain
src/Mana_Part.java svneol=native#text/plain
src/Mana_PartColor.java svneol=native#text/plain
src/Mana_PartColorless.java svneol=native#text/plain
src/Mana_PartSplit.java svneol=native#text/plain
src/Mana_PartTest.java svneol=native#text/plain
src/Mana_PayCost.java svneol=native#text/plain
src/MenuItem_HowToPlay.java svneol=native#text/plain
src/Move.java svneol=native#text/plain
src/MoveAttack.java svneol=native#text/plain
src/MyButton.java svneol=native#text/plain
src/MyObservable.java svneol=native#text/plain
src/MyRandom.java svneol=native#text/plain
src/NameChanger.java svneol=native#text/plain
src/NewIO.java svneol=native#text/plain
src/NonScrollingJEditorPane.java -text svneol=native#text/plain
src/Phase.java svneol=native#text/plain
src/PhaseObserver.java svneol=native#text/plain
src/PicturePanel.java svneol=native#text/plain
src/PlayerLife.java svneol=native#text/plain
src/PlayerZone.java svneol=native#text/plain
src/PlayerZoneUtil.java svneol=native#text/plain
src/PlayerZone_ComesIntoPlay.java svneol=native#text/plain
src/PrintCardNames.java svneol=native#text/plain
src/PrintCardPictures.java svneol=native#text/plain
src/QuestData.java svneol=native#text/plain
src/QuestData_BoosterPack.java svneol=native#text/plain
src/ReadBoosterPack.java svneol=native#text/plain
src/ReadCard.java svneol=native#text/plain
src/Run.java svneol=native#text/plain
src/RunTest.java svneol=native#text/plain
src/SimpleCombat.java svneol=native#text/plain
src/Spell.java svneol=native#text/plain
src/SpellAbility.java -text svneol=native#text/plain
src/SpellAbilityList.java svneol=native#text/plain
src/SpellAbilityUtil.java svneol=native#text/plain
src/Spell_Evoke.java svneol=native#text/plain
src/Spell_Permanent.java svneol=native#text/plain
src/StackObserver.java svneol=native#text/plain
src/StateBasedEffects.java -text svneol=native#text/plain
src/TableModel.java -text svneol=native#text/plain
src/TableSorter.java svneol=native#text/plain
src/TempRun.java svneol=native#text/plain
src/Test.java svneol=native#text/plain
src/TestMove.java svneol=native#text/plain
src/TestPanel.java svneol=native#text/plain
src/Time.java svneol=native#text/plain
src/UndoCommand.java svneol=native#text/plain
src/Wait.java svneol=native#text/plain
src/WinLose.java svneol=native#text/plain
src/forge.properties svneol=native#text/plain
src/forge/error/ErrorViewer.java svneol=native#text/plain
src/forge/error/ExceptionHandler.java -text svneol=native#text/plain
src/forge/gui/ForgeAction.java svneol=native#text/plain
src/forge/gui/ListChooser.java svneol=native#text/plain
src/forge/properties/ForgeProps.java svneol=native#text/plain
src/forge/properties/NewConstants.java svneol=native#text/plain
src/org/jdesktop/swingx/MultiSplitLayout.java -text svneol=native#text/plain
src/org/jdesktop/swingx/MultiSplitPane.java -text svneol=native#text/plain
src/res/AllTokens.txt -text svneol=native#text/plain
src/res/all-decks2 -text svneol=unset#unset
src/res/booster-decks -text svneol=unset#unset
src/res/card-pictures.txt -text svneol=native#text/plain
src/res/cards.txt -text svneol=native#text/plain
src/res/common.txt -text svneol=native#text/plain
src/res/gui/display_layout.xml svneol=native#text/xml
src/res/gui/gui.properties svneol=native#text/plain
src/res/lang/de.properties svneol=native#text/plain
src/res/lang/en.properties svneol=native#text/plain
src/res/lang/howTo/de.properties svneol=native#text/plain
src/res/lang/howTo/en.properties svneol=native#text/plain
src/res/lang/lang.properties svneol=native#text/plain
src/res/main.properties svneol=native#text/plain
src/res/name-mutator.txt -text svneol=native#text/plain
src/res/quest/common.txt -text svneol=native#text/plain
src/res/quest/easy.txt -text svneol=native#text/plain
src/res/quest/hard.txt -text svneol=native#text/plain
src/res/quest/medium.txt -text svneol=native#text/plain
src/res/quest/quest.properties svneol=native#text/plain
src/res/quest/questData -text svneol=unset#unset
src/res/quest/rare.txt -text svneol=native#text/plain
src/res/quest/uncommon.txt -text svneol=native#text/plain
src/res/rare.txt -text svneol=native#text/plain
src/res/tokens.txt -text svneol=native#text/plain
src/res/uncommon.txt -text svneol=native#text/plain
src/treeProperties/PropertyElement.java svneol=native#text/plain
src/treeProperties/PropertyType.java -text svneol=native#text/plain
src/treeProperties/TreeProperties.java -text svneol=native#text/plain
src/treeProperties/types/FileType.java -text svneol=native#text/plain

17
.project Normal file
View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ForgeSVN</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,12 @@
#Mon Oct 12 15:27:12 CDT 2009
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.5

6
src/.classpath Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path=""/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path=""/>
</classpath>

17
src/.project Normal file
View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Forge2</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

41
src/2009-10-12-00.txt Normal file
View File

@@ -0,0 +1,41 @@
An error has occured. You can copy/paste this message or save it to a file.
Please report this, plus what you tried to do, to:
http://www.slightlymagic.net/forum/viewforum.php?f=26
If you don't want to register an account, you can mail it directly to
mtgrares@yahoo.com
Index: 7, Size: 4
Detailed error trace:
java.lang.IndexOutOfBoundsException: Index: 7, Size: 4
at java.util.ArrayList.add(Unknown Source)
at CardList.add(CardList.java:69)
at GameAction.smoothComputerManaCurve(GameAction.java:831)
at GameAction.newGame(GameAction.java:783)
at Gui_NewGame.startButton_actionPerformed(Gui_NewGame.java:433)
at Gui_NewGame$5.actionPerformed(Gui_NewGame.java:272)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

21
src/Ability.java Normal file
View File

@@ -0,0 +1,21 @@
abstract public class Ability extends SpellAbility
{
public Ability(Card sourceCard, String manaCost)
{
super(SpellAbility.Ability, sourceCard);
setManaCost(manaCost);
}
public Ability(Card sourceCard, String manaCost, String stackDescription)
{
this(sourceCard, manaCost);
setStackDescription(stackDescription);
System.out.println("an ability is being played from" + sourceCard.getName());
}
public boolean canPlay()
{
// if(getSourceCard().isCreature() && (!getSourceCard().hasSickness()))
return AllZone.GameAction.isCardInPlay(getSourceCard()) && !getSourceCard().isFaceDown();
// return false;
}
}

View File

@@ -0,0 +1,24 @@
abstract public class Ability_Activated extends SpellAbility implements java.io.Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
public Ability_Activated(Card sourceCard)
{
this(sourceCard, "");
}
public Ability_Activated(Card sourceCard, String manaCost)
{
super(SpellAbility.Ability, sourceCard);
setManaCost(manaCost);
}
public boolean canPlay()
{
Card c = getSourceCard();
return AllZone.GameAction.isCardInPlay(c) && !c.isFaceDown();
//TODO: make sure you can't play the Computer's activated abilities
}
}

23
src/Ability_Hand.java Normal file
View File

@@ -0,0 +1,23 @@
//TODO: make this class a type of Ability
abstract public class Ability_Hand extends SpellAbility implements java.io.Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
public Ability_Hand(Card sourceCard)
{
this(sourceCard, "");
}
public Ability_Hand(Card sourceCard, String manaCost)
{
super(SpellAbility.Ability, sourceCard);
setManaCost(manaCost);
}
public boolean canPlay()
{
PlayerZone zone = AllZone.getZone(getSourceCard());
return zone.is(Constant.Zone.Hand, getSourceCard().getController());
}
}

158
src/Ability_Mana.java Normal file
View File

@@ -0,0 +1,158 @@
import java.util.*;
abstract public class Ability_Mana extends SpellAbility implements java.io.Serializable
{
private ArrayList<Command> runcommands = new ArrayList<Command>();
public String orig;
private String Mana;
public boolean isBasic()
{
return(orig.length() ==10 && orig.startsWith("tap: add ") && "1WBURG".contains(""+orig.charAt(9)));
}
private static final long serialVersionUID = 8292723782268822439L;
/*public Ability_Mana(Card sourceCard, String mana)
{
this(sourceCard, "0");
}*/
public boolean isTapAbility(){return isTapAbility(orig);}
private static boolean isTapAbility(String orig){
String cost = orig.split(":")[0];
cost = cost.replaceAll("tap", "T");
return (cost.contains("T"));
}
public Ability_Mana(Card sourceCard, String orig)
{
super(isTapAbility(orig) ? SpellAbility.Ability_Tap : SpellAbility.Ability, sourceCard);
this.orig=orig;
setDescription(orig);
if(isBasic())//lowers memory usage drastically
{
Mana = "" + orig.charAt(9);
setManaCost("0");
return;
}
String[] parts = orig.split(":");
Mana=parts[1];
Mana = Mana.replaceAll(" add ", "");
setStackDescription("Add "+ Mana +" to your mana pool.");
Mana = Mana.replaceAll(" ", "");
String cost=parts[0];
cost = cost.replaceAll("tap", "T");
//cost = cost.replaceAll("T, ", "");
setManaCost(cost.replaceAll("T", "").split(",")[0]);
if (getManaCost().equals("")) setManaCost("0");
//pain lands
ArrayList<String> pain = new ArrayList<String>();
pain.add("Battlefield Forge");
pain.add("Caves of Koilos");
pain.add("Llanowar Wastes");
pain.add("Shivan Reef");
pain.add("Yavimaya Coast");
pain.add("Adarkar Wastes");
pain.add("Brushland");
pain.add("Karplusan Forest");
pain.add("Underground River");
pain.add("Sulfurous Springs");
if(pain.contains(sourceCard.getName()) && !Mana.equals("1"))
runcommands.add(new Command()
{
private static final long serialVersionUID = 1L;
public void execute(){
AllZone.GameAction.getPlayerLife(getController()).subtractLife(1);
}});
//parseCosts();
/*for(String subcost : cost.split(","))
{
subcost.trim();
if (subcost.equals("") || subcost.equals("T") ||
subcost.equals(getManaCost())) continue;
if (subcost.startsWith("Sacrifice a")){
String sactype= subcost.substring(12).trim();//will remove both "Sac a " and "Sac an" :P
Input bpM_old = getBeforePayMana();
}
}*/
}
public boolean equals(Object o)//Mana abilities with equal descriptions are considered equal, please take this into account
{return (o instanceof Ability_Mana ? ((Ability_Mana)o).orig.equals(orig) : (o instanceof String ? o.toString().equals(orig) : false )) ;}
public boolean equalsIgnoreMana(Ability_Mana ma)
{
String noManaDesc=orig.substring(0,orig.indexOf(Mana));
noManaDesc+=orig.substring(orig.indexOf(Mana)+Mana.length());
String noManaDesc_2=ma.orig.substring(0,ma.orig.indexOf(Mana));
noManaDesc_2+=ma.orig.substring(ma.orig.indexOf(Mana)+Mana.length());
return noManaDesc.equals(noManaDesc_2);
}
public String toString(){return orig;}
boolean undoable=false;
public void undo(){getSourceCard().untap();}//override undo() and set undoable for custom undo costs
public boolean undoable(){return isBasic() || undoable;}
public void parseCosts(){parseCosts(orig);}
private void parseCosts(String orig)
{
setBeforePayMana(null);// reset everything
setAfterPayMana(null);
setAfterResolve(null);
String[] split={",",":","."};//i.e. "cost,cost,cost<...>:Effect.Effect.Effect.
String copy=orig+"";
for(String s : split)
{
copy=copy.replaceAll(" " + s, s); //trim splitter whitespace
copy=copy.replaceAll(s + " ", s);
}
copy=copy.replaceAll("T"+split[0], "");//i.e. "T,"-> ""(reason for this is that tapCost is already determined)
copy=copy.trim();
if (!("123456789GWURBXY(".contains(copy.charAt(0)+"")))
{
setManaCost("0");
copy=split[0] + copy;
}//Hacky, but should work
else setManaCost(copy.substring(0, copy.indexOf(",")));
String divider = ",";
while(!copy.trim().equals(""))
{
if(copy.startsWith(":"))
if (!divider.equals(".")) divider=".";
while (copy.startsWith(":") || copy.startsWith(divider) ) copy=copy.substring(1);
String current=copy.substring(0, copy.indexOf(","));
if (current.startsWith("Sacrifice a")){
}
copy=copy.substring(current.length());
}
}
public void resolve(){
AllZone.ManaPool.addMana(this);
if(!runcommands.isEmpty())
for(Command c : runcommands) c.execute();
}
public int getX(){return getSourceCard().getX();}//override these when not defined by card,
public void setX(int X){getSourceCard().setX(X);}//i.e. "T, remove X charge counters from {name}: add X+1 <color> mana to your mana pool"
public String Mana(){return Mana;}//override for all non-X variable mana,
public String getController(){return getSourceCard().getController();}
public boolean canPlayAI(){return false;}
public boolean canPlay()
{
Card card = getSourceCard();
if(AllZone.GameAction.isCardInPlay(card) &&(!isTapAbility() || card.isUntapped()))
{
if(card.isFaceDown())
return false;
if(card.isArtifact() && card.isCreature())
return !(card.hasSickness() && isTapAbility());
if(card.isCreature() && (!card.hasSickness() || !isTapAbility()))
return true;
else if(card.isArtifact() || card.isGlobalEnchantment() || card.isLand())
return true;
}
return false;
}
}

33
src/Ability_Tap.java Normal file
View File

@@ -0,0 +1,33 @@
abstract public class Ability_Tap extends SpellAbility implements java.io.Serializable
{
private static final long serialVersionUID = 8292723782268822539L;
public Ability_Tap(Card sourceCard)
{
this(sourceCard, "0");
}
public Ability_Tap(Card sourceCard, String manaCost)
{
super(SpellAbility.Ability_Tap, sourceCard);
setManaCost(manaCost);
}
public boolean canPlay()
{
Card card = getSourceCard();
if(AllZone.GameAction.isCardInPlay(card) && card.isUntapped())
{
if(card.isFaceDown())
return false;
if(card.isArtifact() && card.isCreature())
return !card.hasSickness();
if(card.isCreature() && (!card.hasSickness()))
return true;
else if(card.isArtifact() || card.isGlobalEnchantment() || card.isLand())
return true;
}
return false;
}
}

21
src/All.java Normal file
View File

@@ -0,0 +1,21 @@
public class All
{
public Phase Phase = new Phase();
public MagicStack Stack = new MagicStack();
public PlayerLife Human_Life = new PlayerLife();
public PlayerLife Computer_Life = new PlayerLife();
//Human_Play, Computer_Play is different because Card.comesIntoPlay() is called when a card is added by PlayerZone.add(Card)
public PlayerZone Human_Play = new PlayerZone_ComesIntoPlay(Constant.Zone.Play, Constant.Player.Human);
public PlayerZone Human_Hand = new DefaultPlayerZone(Constant.Zone.Hand , Constant.Player.Human);
public PlayerZone Human_Graveyard = new DefaultPlayerZone(Constant.Zone.Graveyard , Constant.Player.Human);
public PlayerZone Human_Library = new DefaultPlayerZone(Constant.Zone.Library , Constant.Player.Human);
public PlayerZone Human_Removed = new DefaultPlayerZone(Constant.Zone.Removed_From_Play, Constant.Player.Human);
public PlayerZone Computer_Play = new PlayerZone_ComesIntoPlay(Constant.Zone.Play , Constant.Player.Computer);
public PlayerZone Computer_Hand = new DefaultPlayerZone(Constant.Zone.Hand , Constant.Player.Computer);
public PlayerZone Computer_Graveyard = new DefaultPlayerZone(Constant.Zone.Graveyard , Constant.Player.Computer);
public PlayerZone Computer_Library = new DefaultPlayerZone(Constant.Zone.Library , Constant.Player.Computer);
public PlayerZone Computer_Removed = new DefaultPlayerZone(Constant.Zone.Removed_From_Play, Constant.Player.Computer);
}

99
src/AllZone.java Normal file
View File

@@ -0,0 +1,99 @@
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import forge.properties.ForgeProps;
import forge.properties.NewConstants;
public class AllZone implements NewConstants {
//only for testing, should read decks from local directory
// public static final IO IO = new IO("all-decks");
public static QuestData QuestData = null;
public static final NameChanger NameChanger = new NameChanger();
public static EndOfTurn EndOfTurn = new EndOfTurn();
public static final CardFactory CardFactory = new CardFactory(ForgeProps.getFile(CARDS));
public static final Phase Phase = new Phase();
public static final MagicStack Stack = new MagicStack();
public static final InputControl InputControl = new InputControl();
public static final GameAction GameAction = new GameAction();
public static final StateBasedEffects StateBasedEffects = new StateBasedEffects();
//initialized at Runtime since it has to be the last object constructed
public static ComputerAI_Input Computer;
//shared between Input_Attack , Input_Block,
// Input_CombatDamage , InputState_Computer
public static Combat Combat = new Combat();
public static Combat pwCombat = new Combat();//for Planeswalker combat
public static PlayerLife Human_Life = new PlayerLife();
public static PlayerLife Computer_Life = new PlayerLife();
//Human_Play, Computer_Play is different because Card.comesIntoPlay() is called when a card is added by PlayerZone.add(Card)
public final static PlayerZone Human_Play = new PlayerZone_ComesIntoPlay(Constant.Zone.Play, Constant.Player.Human);
public final static PlayerZone Human_Hand = new DefaultPlayerZone(Constant.Zone.Hand , Constant.Player.Human);
public final static PlayerZone Human_Graveyard = new DefaultPlayerZone(Constant.Zone.Graveyard , Constant.Player.Human);
public final static PlayerZone Human_Library = new DefaultPlayerZone(Constant.Zone.Library , Constant.Player.Human);
public final static PlayerZone Human_Removed = new DefaultPlayerZone(Constant.Zone.Removed_From_Play, Constant.Player.Human);
public final static PlayerZone Computer_Play = new PlayerZone_ComesIntoPlay(Constant.Zone.Play , Constant.Player.Computer);
public final static PlayerZone Computer_Hand = new DefaultPlayerZone(Constant.Zone.Hand , Constant.Player.Computer);
public final static PlayerZone Computer_Graveyard = new DefaultPlayerZone(Constant.Zone.Graveyard , Constant.Player.Computer);
public final static PlayerZone Computer_Library = new DefaultPlayerZone(Constant.Zone.Library , Constant.Player.Computer);
public final static PlayerZone Computer_Removed = new DefaultPlayerZone(Constant.Zone.Removed_From_Play, Constant.Player.Computer);
public static final ManaPool ManaPool = new ManaPool();
public static Display Display = new GuiDisplay2();
private final static Map<String,PlayerZone> map = new HashMap<String,PlayerZone>();
static
{
map.put(Constant.Zone.Graveyard + Constant.Player.Human, Human_Graveyard);
map.put(Constant.Zone.Hand + Constant.Player.Human, Human_Hand);
map.put(Constant.Zone.Library + Constant.Player.Human, Human_Library);
map.put(Constant.Zone.Play + Constant.Player.Human, Human_Play);
map.put(Constant.Zone.Removed_From_Play + Constant.Player.Human, Human_Removed);
map.put(Constant.Zone.Graveyard + Constant.Player.Computer, Computer_Graveyard);
map.put(Constant.Zone.Hand + Constant.Player.Computer, Computer_Hand);
map.put(Constant.Zone.Library + Constant.Player.Computer, Computer_Library);
map.put(Constant.Zone.Play + Constant.Player.Computer, Computer_Play);
map.put(Constant.Zone.Removed_From_Play + Constant.Player.Computer, Computer_Removed);
}
public static PlayerZone getZone(Card c)
{
Iterator<PlayerZone> it = map.values().iterator();
PlayerZone p;
while(it.hasNext())
{
p = (PlayerZone)it.next();
if(GameAction.isCardInZone(c, p))
return p;
}
return null;
// throw new RuntimeException("AllZone : getZone() error, card is not found, card is " +c);
}
public static PlayerZone getZone(String zone, String player)
{
if (player.equals("")) { //this is a really bad hack, to allow raging goblin to attack on turn 1
player = "Human";
System.out.println("Evil hack");
}
Object o = map.get(zone + player);
if(o == null)
throw new RuntimeException("AllZone : getZone() invalid parameters " +zone +" " +player);
return (PlayerZone)o;
}
}//AllZone

275
src/BackgroundPanel.java Normal file
View File

@@ -0,0 +1,275 @@
import java.awt.*;
import javax.swing.*;
/*
* Support custom painting on a panel in the form of
*
* a) images - that can be scaled, tiled or painted at original size
* b) non solid painting - that can be done by using a Paint object
*
* Also, any component added directly to this panel will be made
* non-opaque so that the custom painting can show through.
*/
public class BackgroundPanel extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int SCALED = 0;
public static final int TILED = 1;
public static final int ACTUAL = 2;
private Paint painter;
private Image image;
private int style = ACTUAL;
private float alignmentX = 0.5f;
private float alignmentY = 0.5f;
private boolean isTransparentAdd = true;
/*
* Set image-string as the background with the SCALED style
*/
public BackgroundPanel(String s)
{
ImageIcon imageIcon = new ImageIcon("pics\\" + s);
image = imageIcon.getImage();
setImage( image );
setStyle( style );
setLayout( new BorderLayout() );
repaint();
}
public BackgroundPanel()
{
setStyle( style );
setLayout( new BorderLayout() );
repaint();
}
/*
* Set image as the background with the SCALED style
*/
public BackgroundPanel(Image image)
{
this(image, SCALED);
}
/*
* Set image as the background with the specified style
*/
public BackgroundPanel(Image image, int style)
{
setImage( image );
setStyle( style );
setLayout( new BorderLayout() );
}
/*
* Set image as the backround with the specified style and alignment
*/
public BackgroundPanel(Image image, int style, float alignmentX, float alignmentY)
{
setImage( image );
setStyle( style );
setImageAlignmentX( alignmentX );
setImageAlignmentY( alignmentY );
setLayout( new BorderLayout() );
}
/*
* Use the Paint interface to paint a background
*/
public BackgroundPanel(Paint painter)
{
setPaint( painter );
setLayout( new BorderLayout() );
}
/*
* Set the image used as the background
*/
public void setImage(Image image)
{
this.image = image;
repaint();
}
/*
* Set the style used to paint the background image
*/
public void setStyle(int style)
{
this.style = style;
repaint();
}
/*
* Set the Paint object used to paint the background
*/
public void setPaint(Paint painter)
{
this.painter = painter;
repaint();
}
/*
* Specify the horizontal alignment of the image when using ACTUAL style
*/
public void setImageAlignmentX(float alignmentX)
{
this.alignmentX = alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX;
repaint();
}
/*
* Specify the horizontal alignment of the image when using ACTUAL style
*/
public void setImageAlignmentY(float alignmentY)
{
this.alignmentY = alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY;
repaint();
}
/*
* Override method so we can make the component transparent
*/
public void add(JComponent component)
{
add(component, null);
}
/*
* Override method so we can make the component transparent
*/
public void add(JComponent component, Object constraints)
{
if (isTransparentAdd)
{
makeComponentTransparent(component);
}
super.add(component, constraints);
}
/*
* Controls whether components added to this panel should automatically
* be made transparent. That is, setOpaque(false) will be invoked.
* The default is set to true.
*/
public void setTransparentAdd(boolean isTransparentAdd)
{
this.isTransparentAdd = isTransparentAdd;
}
/*
* Try to make the component transparent.
* For components that use renderers, like JTable, you will also need to
* change the renderer to be transparent. An easy way to do this it to
* set the background of the table to a Color using an alpha value of 0.
*/
private void makeComponentTransparent(JComponent component)
{
component.setOpaque( false );
if (component instanceof JScrollPane)
{
JScrollPane scrollPane = (JScrollPane)component;
JViewport viewport = scrollPane.getViewport();
viewport.setOpaque( false );
Component c = viewport.getView();
if (c instanceof JComponent)
{
((JComponent)c).setOpaque( false );
}
}
}
/*
* Add custom painting
*/
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// Invoke the painter for the background
if (painter != null)
{
Dimension d = getSize();
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(painter);
g2.fill( new Rectangle(0, 0, d.width, d.height) );
}
// Draw the image
if (image == null ) return;
switch (style)
{
case SCALED :
drawScaled(g);
break;
case TILED :
drawTiled(g);
break;
case ACTUAL :
drawActual(g);
break;
default:
drawScaled(g);
}
}
/*
* Custom painting code for drawing a SCALED image as the background
*/
private void drawScaled(Graphics g)
{
Dimension d = getSize();
g.drawImage(image, 0, 0, d.width, d.height, null);
}
/*
* Custom painting code for drawing TILED images as the background
*/
private void drawTiled(Graphics g)
{
Dimension d = getSize();
int width = image.getWidth( null );
int height = image.getHeight( null );
for (int x = 0; x < d.width; x += width)
{
for (int y = 0; y < d.height; y += height)
{
g.drawImage( image, x, y, null, null );
}
}
}
/*
* Custom painting code for drawing the ACTUAL image as the background.
* The image is positioned in the panel based on the horizontal and
* vertical alignments specified.
*/
private void drawActual(Graphics g)
{
Dimension d = getSize();
Insets insets = getInsets();
int width = d.width - insets.left - insets.right;
int height = d.height - insets.top - insets.left;
float x = (width - image.getWidth(null)) * alignmentX;
float y = (height - image.getHeight(null)) * alignmentY;
g.drawImage(image, (int)x + insets.left, (int)y + insets.top, this);
}
}

122
src/BoosterDraft.java Normal file
View File

@@ -0,0 +1,122 @@
public interface BoosterDraft
{
public CardList nextChoice();
public void setChoice(Card c);
public boolean hasNextChoice();
public Deck[] getDecks(); //size 7, all the computers decks
}
class BoosterDraft_1 implements BoosterDraft
{
private final BoosterDraftAI draftAI = new BoosterDraftAI();
private final int nPlayers = 8;
private final int boosterPackSize = 15;
private final int stopCount = boosterPackSize * 3;//should total of 45
private int currentCount = 0;
private CardList[] pack;//size 8
//helps the computer choose which booster packs to pick from
//the first row says "pick from boosters 1-7, skip 0" since the players picks from 0
//the second row says "pick from 0 and 2-7 boosters, skip 1" - player chooses from 1
private final int computerChoose[][] = {
{ 1,2,3,4,5,6,7},
{0, 2,3,4,5,6,7},
{0,1, 3,4,5,6,7},
{0,1,2, 4,5,6,7},
{0,1,2,3, 5,6,7},
{0,1,2,3,4, 6,7},
{0,1,2,3,4,5, 7},
{0,1,2,3,4,5,6 }
};
public static void main(String[] args)
{
BoosterDraft_1 draft = new BoosterDraft_1();
while(draft.hasNextChoice())
{
CardList list = draft.nextChoice();
System.out.println(list.size());
draft.setChoice(list.get(0));
}
}
BoosterDraft_1() {pack = get8BoosterPack();}
public CardList nextChoice()
{
if(pack[getMod()].size() == 0)
pack = get8BoosterPack();
computerChoose();
CardList list = pack[getMod()];
return list;
}
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(),
};
ReadBoosterPack pack = new ReadBoosterPack();
for(int i = 0; i < list.length; i++)
list[i].addAll(pack.getBoosterPack().toArray());
return list;
}//get8BoosterPack()
//size 7, all the computers decks
public Deck[] getDecks() {return draftAI.getDecks();}
private void computerChoose()
{
int row[] = computerChoose[getMod()];
for(int i = 0; i < row.length; i++)
draftAI.choose(pack[row[i]]);
}//computerChoose()
private int getMod() {return currentCount % nPlayers;}
public boolean hasNextChoice() {return currentCount < stopCount;}
public void setChoice(Card c)
{
CardList list = pack[getMod()];
currentCount++;
if(! list.contains(c))
throw new RuntimeException("BoosterDraft : setChoice() error - card not found - " +c +" - booster pack = " +list);
list.remove(c);
}//setChoice()
}
class BoosterDraftTest implements BoosterDraft
{
int n = 3;
public Deck[] getDecks() {return null;}
public CardList nextChoice()
{
n--;
ReadBoosterPack pack = new ReadBoosterPack();
return pack.getBoosterPack();
}
public void setChoice(Card c) {System.out.println(c.getName());}
public boolean hasNextChoice()
{
return n > 0;
}
public CardList getChosenCards() {return null;}
public CardList getUnchosenCards() {return null;}
}

302
src/BoosterDraftAI.java Normal file
View File

@@ -0,0 +1,302 @@
import java.util.*;
public class BoosterDraftAI
{
//once a deck has this number of creatures the computer randomly
//picks a card, so the final computer deck has 12-20 creatures
//minimum of creatures per deck
private final int nCreatures = 16;
private final int nDecks = 7;
//holds all the cards for each of the computer's decks
private CardList[] deck = new CardList[nDecks];
private String[][] deckColor = new String[nDecks][];
private static Map<String, String> colorToLand = new HashMap<String, String>();
public static void main(String[] args)
{
BoosterDraftAI ai = new BoosterDraftAI();
ai.runTestPrint();
}
public void runTestPrint()
{
BoosterDraftAI ai = new BoosterDraftAI();
ai.runTest(ai);
Deck[] deck = ai.getDecks();
for(int outer = 0; outer < 7; outer++)
{
System.out.print(deck[outer].countMain() +" - ");
for(int i = 0; i < 16; i++)
System.out.print(deck[outer].getMain(i) +", ");
System.out.println("");
for(int i = 16; i < 22; i++)
System.out.print(deck[outer].getMain(i) +", ");
System.out.println("\n");
}//for outer
}//runTestPrint()
//throws Exception if error
public void runTest(BoosterDraftAI ai)
{
ReadBoosterPack booster = new ReadBoosterPack();
for(int outer = 0; outer < 1; outer++)
{
CardList allBooster = new CardList();
for(int i = 0; i < 21; i++)
allBooster.addAll(booster.getBoosterPack().toArray());
int stop = allBooster.size();
for(int i = 0; i < stop; i++)
{
ai.choose(allBooster);
}
//ai.checkDeckList(ai.deck);
}
}//runTest()
//picks one Card from augment, removes that card, and returns the list
//returns the cards not picked
public CardList choose(final CardList in_choose)
{
//in_choose should ONLY be on the RIGHT side of any equal sign
//only 1 card should be removed from in_choose
CardList list = new CardList();
boolean hasPicked = false;
//try to choose a creature that has one of the colors that are in the deck
for(int i = 0; i < nDecks; i++)
{
if(countCreatures(deck[i]) < nCreatures)
{
list.clear();
//get creature cards that match the decks 2 colors
list.addAll(CardListUtil.getColor(in_choose.getType("Creature"), deckColor[i][0]).toArray());
list.addAll(CardListUtil.getColor(in_choose.getType("Creature"), deckColor[i][1]).toArray());
for(int j=0;j<list.size();j++)
{
//go through list and remove gold cards:
if(CardUtil.getColors(list.get(j)).size() > 1)
{
//TODO maybe keep in cards that have 2 colors, and match the colors
list.remove(list.get(j));
}
}
list.shuffle();
if(! list.isEmpty())
{
deck[i].add(list.get(0));
hasPicked = true;
break;
}
}//if
}//for
//no card was chosen
if(! hasPicked)
{
//TODO: remove cards that the computer can't play
//holds instants and sorceries
CardList spell = new CardList();
spell.addAll(in_choose.getType("Instant").toArray());
spell.addAll(in_choose.getType("Sorcery").toArray());
//choose any card that matches the decks color
for(int i = 0; i < nDecks; i++)
{
list.clear();
list.addAll(deck[i].getType("Instant").toArray());
list.addAll(deck[i].getType("Sorcery").toArray());
//does the deck need more spells?
//16 creatures, 6 spells per deck
if(list.size() < 6)
{
list.clear();
//get any cards that match the decks 2 colors
list.addAll(CardListUtil.getColor(new CardList(spell.toArray()), deckColor[i][0]).toArray());
list.addAll(CardListUtil.getColor(new CardList(spell.toArray()), deckColor[i][1]).toArray());
list.shuffle();
if(! list.isEmpty())
{
deck[i].add(list.get(0));
hasPicked = true;
break;
}
}//if - deck[i].size() < 22
}//for
}//if - choose any card
if(hasPicked)
in_choose.remove(list.get(0));
else//computer didn't choose a card, just remove any card - all computer decks are done
{
in_choose.remove(0);
}
return in_choose;
}//choose()
/*
I get some wierd error when I have this method, I don't know whats wrong
private void checkDeckList(CardList[] deck)
{
if(deck.length != nDecks)
throw new RuntimeException("BoosterDraftAI : checkDeckList() error, deck list size is not 7 - " +deck.length);
for(int i = 0; i < nDecks; i++)
{
if(deck[i].size() != 22)
{
throw new RuntimeException("BoosterDraftAI : checkDeckList() error, deck list size is not 22 - " +deck[i].size() +" - " +deck.toString());
}
if(countCreatures(deck[i]) < nCreatures)
throw new RuntimeException("BoosterDraftAI : checkDeckList() error, deck needs more creatures - " +countCreatures(deck[i]));
for(int inner = 0; inner < 22; inner++)
if(! CardUtil.getColors(deck[i].getCard(inner)).contains(deckColor[i][0]) &&
! CardUtil.getColors(deck[i].getCard(inner)).contains(deckColor[i][1]))
throw new RuntimeException("BoosterDraftAI : checkDeckList() error, deck has different card colors");
}//for
}//checkDeckList()
*/
private int countCreatures(CardList list) {return list.getType("Creature").size();}
private void testColors(int[] n)
{
if(n.length != nDecks)
throw new RuntimeException("BoosterDraftAI : testColors error, numbers array length does not equal 7");
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nDecks; i++)
set.add(new Integer(n[i]));
if(set.size() != nDecks)
throw new RuntimeException("BoosterDraftAI : testColors error, numbers not unique");
for(int i = 0; i < nDecks; i++)
if(n[i] < 0 || deckColorChoices.length <= n[i])
throw new RuntimeException("BoosterDraftAI : testColors error, index out of range - " +n[i]);
}//testColors()
public Deck[] getDecks()
{
//check CardList[] deck for errors
//checkDeckList(deck);
Deck[] out = new Deck[deck.length];
for(int i = 0; i < deck.length; i++)
{
addLand(deck[i], deckColor[i]);
out[i] = getDeck(deck[i]);
}
return out;
}//getDecks()
private Deck getDeck(CardList list)
{
Deck out = new Deck(Constant.GameType.Draft);
for(int i = 0; i < list.size(); i++)
out.addMain(list.get(i).getName());
return out;
}//getDeck()
//add Land to list argument
private void addLand(CardList list, String[] color)
{
Card land;
for(int i = 0; i < 9; i++)
{
land = AllZone.CardFactory.getCard(colorToLand.get(color[0]).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(colorToLand.get(color[1]).toString(), Constant.Player.Computer);
list.add(land);
}
if(list.getType("Land").size() != 18)
throw new RuntimeException("BoosterDraftAI : addLand() error, deck does not have 18 lands - " +list.getType("Land").size());
if(list.size() != 40)
throw new RuntimeException("BoosterDraftAI : addLand() error, deck is not 40 cards - " +list.size());
}//addLand()
//returns 7 different ints, within the range of 0-9
private int[] getDeckColors()
{
int[] out = new int[nDecks];
int start = MyRandom.random.nextInt();
start = Math.abs(start);//make number positive, stupid number generator
for(int i = 0; i < out.length; i++)
{
//% to get an index between 0 and deckColorChoices.length
out[i] = start % deckColorChoices.length;
start++;
}
testColors(out);
return out;
}//getDeckColors()
public BoosterDraftAI()
{
//choose colors for decks
int[] n = getDeckColors();
for(int i = 0; i < n.length; i++)
deckColor[i] = deckColorChoices[n[i]];
//initilize color map
colorToLand.put(Constant.Color.Black , "Swamp");
colorToLand.put(Constant.Color.Blue , "Island");
colorToLand.put(Constant.Color.Green , "Forest");
colorToLand.put(Constant.Color.Red , "Mountain");
colorToLand.put(Constant.Color.White , "Plains");
//initilize deck array
for(int i = 0; i < deck.length; i++)
deck[i] = new CardList();
}//BoosterDraftAI()
//all 10 two color combinations
private String[][] deckColorChoices =
{
{Constant.Color.Black, Constant.Color.Blue},
{Constant.Color.Black, Constant.Color.Green},
{Constant.Color.Black, Constant.Color.Red},
{Constant.Color.Black, Constant.Color.White},
{Constant.Color.Blue, Constant.Color.Green},
{Constant.Color.Blue, Constant.Color.Red},
{Constant.Color.Blue, Constant.Color.White},
{Constant.Color.Green, Constant.Color.Red},
{Constant.Color.Green, Constant.Color.White},
{Constant.Color.Red, Constant.Color.White}
};
}//BoosterDraftAI()

27
src/BoosterPack.java Normal file
View File

@@ -0,0 +1,27 @@
public class BoosterPack
{
public static CardList getBoosterPack(int number)
{
CardList all = new CardList();
for(int i = 0; i < number; i++)
all.addAll(getBoosterPack().toArray());
return all;
}
public static CardList getBoosterPack()
{
CardList all = AllZone.CardFactory.getAllCards();
CardList pack = new CardList();
for(int i = 0; i < 10; i++)
pack.add(all.get(MyRandom.random.nextInt(all.size())));
for(int i = 0; i < 5; i++)
pack.add(AllZone.CardFactory.copyCard(pack.get(i)));
return pack;
}//getBoosterPack()
}

34
src/ButtonUtil.java Normal file
View File

@@ -0,0 +1,34 @@
public class ButtonUtil
{
public static void reset()
{
getOK().setText("OK");
getCancel().setText("Cancel");
getOK().setSelectable(false);
getCancel().setSelectable(false);
}
public static void enableOnlyOK()
{
getOK().setSelectable(true);
getCancel().setSelectable(false);
}
public static void enableOnlyCancel()
{
getOK().setSelectable(false);
getCancel().setSelectable(true);
}
public static void disableAll()
{
getOK().setSelectable(false);
getCancel().setSelectable(false);
}
public static void enableAll()
{
getOK().setSelectable(true);
getCancel().setSelectable(true);
}
private static MyButton getOK() {return AllZone.Display.getButtonOK();}
private static MyButton getCancel() {return AllZone.Display.getButtonCancel();}
}

855
src/Card.java Normal file
View File

@@ -0,0 +1,855 @@
import java.util.*;
enum Counters {
AGE, BLAZE, CHARGE, DIVINITY, FADE, HOOFPRINT, ICE, LOYALTY, M1M1, MANA, P0M1, P1P1, QUEST, SPORE
}
public class Card extends MyObservable
{
private static int nextUniqueNumber;
private int uniqueNumber = nextUniqueNumber++;
//private Collection keyword = new TreeSet();
//private ArrayList<String> keyword = new ArrayList<String>();
private ArrayList<String> intrinsicKeyword = new ArrayList<String>();
private ArrayList<String> extrinsicKeyword = new ArrayList<String>();
private ArrayList<String> prevIntrinsicKeyword = new ArrayList<String>();
private ArrayList<Card> attached = new ArrayList<Card>();
private ArrayList<Card> equippedBy = new ArrayList<Card>(); //which equipment cards are equipping this card?
//equipping size will always be 0 or 1
private ArrayList<Card> equipping = new ArrayList<Card>(); //if this card is of the type equipment, what card is it currently equipping?
private ArrayList<Card> enchantedBy = new ArrayList<Card>(); //which auras enchanted this card?
//enchanting size will always be 0 or 1
private ArrayList<Card> enchanting = new ArrayList<Card>(); //if this card is an Aura, what card is it enchanting?
private ArrayList<String> type = new ArrayList<String>();
private ArrayList<String> prevType = new ArrayList<String>();
private ArrayList<SpellAbility> spellAbility = new ArrayList<SpellAbility>();
private ArrayList<Ability_Mana> manaAbility = new ArrayList<Ability_Mana>();
private HashMap<Card, Integer> receivedDamageFromThisTurn = new HashMap<Card, Integer>();
private boolean tapped;
private boolean sickness = true;//summoning sickness
private boolean token = false;
private boolean creatureAttackedThisTurn = false;
private boolean creatureBlockedThisTurn = false;
private boolean creatureGotBlockedThisTurn = false;
private boolean dealtCombatDmgToOppThisTurn = false;
private boolean dealtDmgToOppThisTurn = false;
private boolean exaltedBonus = false;
private boolean faceDown = false;
private boolean echoPaid = false;
private boolean sacrificeAtEOT = false;
private boolean firstStrike = false;
private boolean doubleStrike = false;
private boolean flashback = false;
private int exaltedMagnitude = 0;
private int baseAttack;
private int baseDefense;
private int damage;
private int assignedDamage;
private int nShield;
private int turnInZone;
private int tempAttackBoost = 0;
private int tempDefenseBoost = 0;
private int semiPermanentAttackBoost = 0;
private int semiPermanentDefenseBoost = 0;
private int otherAttackBoost = 0;
private int otherDefenseBoost = 0;
private int randomPicture = 0;
private int X = 0;
private String owner = "";
private String controller = "";
private String name = "";
private String imageName = "";
private String rarity = "";
private String text = "";
private String manaCost = "";
private String chosenType = "";
private ArrayList<Command> comesIntoPlayCommandList = new ArrayList<Command>();
private ArrayList<Command> destroyCommandList = new ArrayList<Command>();
private ArrayList<Command> leavesPlayCommandList = new ArrayList<Command>();
private ArrayList<Command> turnFaceUpCommandList = new ArrayList<Command>();
private ArrayList<Command> equipCommandList = new ArrayList<Command>();
private ArrayList<Command> unEquipCommandList = new ArrayList<Command>();
private ArrayList<Command> enchantCommandList = new ArrayList<Command>();
private ArrayList<Command> unEnchantCommandList = new ArrayList<Command>();
private ArrayList<Command> replaceMoveToGraveyardCommandList = new ArrayList<Command>();
private ArrayList<Command> cycleCommandList = new ArrayList<Command>();
private Hashtable<Counters,Integer> counters = new Hashtable<Counters,Integer>();
//hacky code below, used to limit the number of times an ability
//can be used per turn like Vampire Bats
//should be put in SpellAbility, but it is put here for convienance
//this is make public just to make things easy
//this code presumes that each card only has one ability that can be
//used a limited number of times per turn
//CardFactory.SSP_canPlay(Card) uses these variables
private int abilityTurnUsed; //What turn did this card last use this ability?
private int abilityUsed; //How many times has this ability been used?
public void setAbilityTurnUsed(int i) {abilityTurnUsed = i; }
public int getAbilityTurnUsed() { return abilityTurnUsed; }
public void setAbilityUsed(int i) {abilityUsed = i;}
public int getAbilityUsed() { return abilityUsed; }
//****************TODO:Check
public void setX(int i){X = i;}
public int getX() { return X; }
//***************/
//used to see if an attacking creature with a triggering attack ability triggered this turn:
public void setCreatureAttackedThisTurn(boolean b) { creatureAttackedThisTurn = b; }
public boolean getCreatureAttackedThisTurn() { return creatureAttackedThisTurn; }
public void setCreatureBlockedThisTurn(boolean b) { creatureBlockedThisTurn = b; }
public boolean getCreatureBlockedThisTurn() { return creatureBlockedThisTurn; }
public void setCreatureGotBlockedThisTurn(boolean b) { creatureGotBlockedThisTurn = b; }
public boolean getCreatureGotBlockedThisTurn() { return creatureGotBlockedThisTurn; }
public void setDealtCombatDmgToOppThisTurn(boolean b) { dealtCombatDmgToOppThisTurn = b; }
public boolean getDealtCombatDmgToOppThisTurn() { return dealtCombatDmgToOppThisTurn; }
public void setDealtDmgToOppThisTurn(boolean b) { dealtDmgToOppThisTurn = b;}
public boolean getDealtDmgToOppThisTurn() { return dealtDmgToOppThisTurn; }
public void addReceivedDamageFromThisTurn(Card c, int damage) { receivedDamageFromThisTurn.put(c, damage);}
public void setReceivedDamageFromThisTurn(HashMap<Card, Integer> receivedDamageFromThisTurn) {
this.receivedDamageFromThisTurn = receivedDamageFromThisTurn;
}
public HashMap<Card, Integer> getReceivedDamageFromThisTurn() {
return receivedDamageFromThisTurn;
}
public void resetReceivedDamageFromThisTurn() {
receivedDamageFromThisTurn.clear();
}
public boolean getSacrificeAtEOT()
{
return sacrificeAtEOT;
}
public void setSacrificeAtEOT(boolean sacrificeAtEOT)
{
this.sacrificeAtEOT = sacrificeAtEOT;
}
public boolean hasFirstStrike() {
return firstStrike || getKeyword().contains("First Strike");
}
public void setFirstStrike(boolean firstStrike){
this.firstStrike = firstStrike;
}
public void setDoubleStrike(boolean doubleStrike){
this.doubleStrike = doubleStrike;
}
public boolean hasDoubleStrike() {
return doubleStrike || getKeyword().contains("Double Strike");
}
public void addCounter(Counters counterName, int n)
{
if(counters.containsKey(counterName))
{
Integer aux = counters.get(counterName) + n;
counters.put(counterName,aux);
}
else
{
counters.put(counterName, new Integer(n));
}
this.updateObservers();
}
public void subtractCounter(Counters counterName, int n)
{
if(counters.containsKey(counterName))
{
Integer aux = counters.get(counterName) - n;
counters.put(counterName,aux);
this.updateObservers();
}
}
public int getCounters(Counters counterName)
{
if(counters.containsKey(counterName))
{
return counters.get(counterName);
}
else
return 0;
}
public void setCounter(Counters counterName, int n) {
counters.put(counterName,new Integer(n));
this.updateObservers();
}
public int sumAllCounters()
{
Object[] values = counters.values().toArray();
int count = 0;
int num = 0;
for(int i=0;i<values.length;i++)
{
num = (Integer)values[i];
count += num;
}
return count;
}
public int getNetPTCounters()
{
return getCounters(Counters.P1P1) - getCounters(Counters.M1M1);
}
//the amount of damage needed to kill the creature
public int getKillDamage() {return getNetDefense() - getDamage();}
public int getTurnInZone() {return turnInZone;}
public void setTurnInZone(int turn) {turnInZone = turn;}
public boolean getEchoPaid() {return echoPaid;}
public void setEchoPaid(boolean b) {echoPaid = b;}
public void setManaCost(String s) {manaCost = s;}
public String getManaCost() {return manaCost;}
//used for cards like Belbe's Portal, Conspiracy, Cover of Darkness, etc.
public String getChosenType() { return chosenType;}
public void setChosenType(String s) {chosenType = s;}
public String getSpellText() {return text;}
public void setText(String t) {text = t;}
public String getText()
{
if(isInstant() || isSorcery())
{
String s = getSpellText();
SpellAbility[] sa = getSpellAbility();
for(int i = 0; i < sa.length; i++)
s += sa[i].toString() +"\r\n";
return s;
}
String s = "";
ArrayList<String> keyword = getKeyword();
for(int i = 0; i < keyword.size(); i++)
{
if(i != 0)
s += ", ";
s += keyword.get(i).toString();
}
s += "\r\n" +text +"\r\n";
SpellAbility[] sa = getSpellAbility();
for(int i = 0; i < sa.length; i++)
{
//presumes the first SpellAbility added to this card, is the "main" spell
//skip the first SpellAbility for creatures, since it says "Summon this creature"
//looks bad on the Gui card detail
if(isPermanent() && i != 0 && !(manaAbility.contains(sa[i]) && ((Ability_Mana) sa[i]).isBasic()))//prevent mana ability duplication
s += sa[i].toString() +"\r\n";
}
return s.trim();
}//getText()
/* private ArrayList<Ability_Mana> addLandAbilities ()
{
ArrayList<Ability_Mana> res = new ArrayList<Ability_Mana>(manaAbility);
if (!getType().contains("Land")) return res;
ArrayList<String> types = getType();
for(int i = 0; i < basics.length; i++)
if(types.contains(basics[i]) && !res.contains("tap: add "+ ManaPool.colors.charAt(i)))
res.add(new Ability_Mana(this, "tap: add "+ ManaPool.colors.charAt(i)){});
return res;
}*/
/*ArrayList<Ability_Mana> addExtrinsicAbilities(ArrayList<Ability_Mana> have)
{
try{
if (AllZone.getZone(this).is(Constant.Zone.Play))
{
for (Card c : AllZone.getZone(Constant.Zone.Play, getController()).getCards())
if (c.getName().equals("Joiner Adept") && getType().contains("Land") || c.getName().equals("Gemhide Sliver") && getType().contains("Sliver"))
for (char ch : ManaPool.colors.toCharArray())
have.add(new Ability_Mana(this, "tap: add " + ch){});
}}
catch(NullPointerException ex){}//TODO: fix this to something more memory-efficient than catching 2000 NullPointer Exceptions every time you open deck editor
return have;
}*/
public ArrayList<Ability_Mana> getManaAbility(){return new ArrayList<Ability_Mana>(manaAbility);}
public ArrayList<Ability_Mana> getBasicMana()
{
ArrayList<Ability_Mana> res = new ArrayList<Ability_Mana>();
for(Ability_Mana am : getManaAbility())
if(am.isBasic() && !res.contains(am))
res.add(am);
return res;
}
public void clearSpellAbility() {spellAbility.clear(); manaAbility.clear();}
public void clearSpellKeepManaAbility() { spellAbility.clear(); }
public void clearManaAbility() { manaAbility.clear(); }
public void addSpellAbility(SpellAbility a) {a.setSourceCard(this); if (a instanceof Ability_Mana) manaAbility.add((Ability_Mana) a); else spellAbility.add(a);}
public void removeSpellAbility(SpellAbility a)
{
if(a instanceof Ability_Mana)
//if (a.isExtrinsic()) //never remove intrinsic mana abilities, is this the way to go??
manaAbility.remove((Ability_Mana)a);
else
spellAbility.remove(a);
}
public void removeAllExtrinsicManaAbilities()
{
//temp ArrayList, otherwise ConcurrentModificationExceptions occur:
ArrayList<SpellAbility> saList = new ArrayList<SpellAbility>();
for (SpellAbility var : manaAbility)
{
if(var.isExtrinsic())
saList.add(var);
}
for (SpellAbility sa : saList)
{
removeSpellAbility(sa);
}
}
public ArrayList<String> getIntrinsicManaAbilitiesDescriptions()
{
ArrayList<String> list = new ArrayList<String>();
for (SpellAbility var : manaAbility)
{
if (var.isIntrinsic())
list.add(var.toString());
}
return list;
}
public SpellAbility[] getSpellAbility()
{
ArrayList<SpellAbility> res = new ArrayList<SpellAbility>(spellAbility);
res.addAll(getManaAbility());
SpellAbility[] s = new SpellAbility[res.size()];
res.toArray(s);
return s;
}
//shield = regeneration
public void setShield(int n) {nShield = n;}
public int getShield() {return nShield;}
public void addShield() {nShield++;}
public void subtractShield() {nShield--;}
public void resetShield() {nShield = 0;}
//is this "Card" supposed to be a token?
public void setToken(boolean b) {token = b;}
public boolean isToken() {return token;}
public void setExaltedBonus(boolean b) {exaltedBonus = b;}
public boolean hasExaltedBonus() {return exaltedBonus;}
public void setExaltedMagnitude(int i) {exaltedMagnitude = i;}
public int getExaltedMagnitude() { return exaltedMagnitude; }
public void setIsFaceDown(boolean b) { faceDown = b;}
public boolean isFaceDown() { return faceDown; }
public void addComesIntoPlayCommand(Command c) {comesIntoPlayCommandList.add(c);}
public void removeComesIntoPlayCommand(Command c) { comesIntoPlayCommandList.remove(c);}
public void comesIntoPlay() {
for (Command var : comesIntoPlayCommandList)
var.execute();
}
public void addTurnFaceUpCommand(Command c) { turnFaceUpCommandList.add(c); }
public void removeTurnFaceUpCommand(Command c) { turnFaceUpCommandList.remove(c); }
public void turnFaceUp() {
for (Command var : turnFaceUpCommandList)
var.execute();
}
public void addDestroyCommand(Command c) {destroyCommandList.add(c);}
public void removeDestroyCommand(Command c) {destroyCommandList.remove(c); }
public void destroy()
{
for (Command var : destroyCommandList)
var.execute();
}
public void addLeavesPlayCommand(Command c) { leavesPlayCommandList.add(c);}
public void removeLeavesPlayCommand(Command c) { leavesPlayCommandList.remove(c); }
public void leavesPlay() {
for (Command var : leavesPlayCommandList)
var.execute();
}
public void addEquipCommand(Command c) {equipCommandList.add(c); }
public void removeEquipCommand(Command c) { equipCommandList.remove(c); }
public void equip() {
for (Command var : equipCommandList)
var.execute();
}
public void addUnEquipCommand(Command c) {unEquipCommandList.add(c); }
public void removeUnEquipCommand(Command c) { unEquipCommandList.remove(c); }
public void unEquip() {
for (Command var : unEquipCommandList)
var.execute();
}
public void addEnchantCommand(Command c) {enchantCommandList.add(c); }
public void removeEnchantCommand(Command c) {enchantCommandList.add(c); }
public void enchant() {
for (Command var : enchantCommandList)
var.execute();
}
public void addUnEnchantCommand(Command c) { unEnchantCommandList.add(c); }
public void unEnchant() {
for (Command var : unEnchantCommandList)
var.execute();
}
public ArrayList<Command> getReplaceMoveToGraveyard() { return replaceMoveToGraveyardCommandList; }
public void addReplaceMoveToGraveyardCommand(Command c) { replaceMoveToGraveyardCommandList.add(c);}
public void replaceMoveToGraveyard()
{
for (Command var : replaceMoveToGraveyardCommandList)
var.execute();
}
public void addCycleCommand(Command c) { cycleCommandList.add(c); }
public void cycle() {
for (Command var : cycleCommandList)
var.execute();
}
public void setSickness(boolean b) {sickness = b;}
public boolean hasSickness()
{
if(getKeyword().contains("Haste"))
return false;
return sickness;
}
public void setRarity(String s) {rarity = s;}
public String getRarity() {return rarity;}
public void addDamage(int n)
{
if (this.getName().equals("Cho-Manno, Revolutionary"))
n = 0;
setDamage(getDamage() + n);
}
public void setDamage(int n)
{
if (this.getName().equals("Cho-Manno, Revolutionary"))
n = 0;
damage = n;
}
public int getDamage() {return damage;}
public void setAssignedDamage(int n) {assignedDamage = n;}
public int getAssignedDamage() {return assignedDamage;}
public void setImageName(String s) { imageName = s; }
public String getImageName()
{
if (!imageName.equals(""))
return imageName;
return name;
}
public String getName() {return name;}
public String getOwner() {return owner;}
public String getController(){return controller;}
public void setName(String s) {name = s; this.updateObservers();}
public void setOwner(String player) {owner = player;}
public void setController(String player){controller = player; this.updateObservers();}
public ArrayList<Card> getEquippedBy()
{
return equippedBy;
}
public void setEquippedBy(ArrayList<Card> list)
{
equippedBy = list;
}
public ArrayList<Card> getEquipping()
{
return equipping;
}
public void setEquipping(ArrayList<Card> list)
{
equipping = list;
}
public boolean isEquipped()
{
Card c[] = new Card[equippedBy.size()];
equippedBy.toArray(c);
return c.length != 0;
}
public boolean isEquipping()
{
Card c[] = new Card[equipping.size()];
equippedBy.toArray();
return c.length != 0;
}
public void addEquippedBy(Card c)
{
equippedBy.add(c);
this.updateObservers();
}
public void removeEquippedBy(Card c)
{
equippedBy.remove(c);
this.updateObservers();
}
public void addEquipping(Card c)
{
equipping.add(c);
this.updateObservers();
}
public void removeEquipping(Card c)
{
equipping.remove(c);
this.updateObservers();
}
public void equipCard(Card c) //equipment.equipCard(cardToBeEquipped);
{
equipping.add(c);
c.addEquippedBy(this);
this.equip();
}
public void unEquipCard(Card c) //equipment.unEquipCard(equippedCard);
{
this.unEquip();
equipping.remove(c);
c.removeEquippedBy(this);
}
public void unEquipAllCards()
{
for (int i=0; i<equippedBy.size();i++)
{
equippedBy.get(i).unEquipCard(this);
}
}
//
public ArrayList<Card> getEnchantedBy()
{
return enchantedBy;
}
public void setEnchantedBy(ArrayList<Card> list)
{
enchantedBy = list;
}
public ArrayList<Card> getEnchanting()
{
return enchanting;
}
public void setEnchanting(ArrayList<Card> list)
{
enchanting = list;
}
public boolean isEnchanted()
{
Card c[] = new Card[enchantedBy.size()];
enchantedBy.toArray(c);
return c.length != 0;
}
public boolean isEnchanting()
{
Card c[] = new Card[enchanting.size()];
enchantedBy.toArray();
return c.length != 0;
}
public void addEnchantedBy(Card c)
{
enchantedBy.add(c);
this.updateObservers();
}
public void removeEnchantedBy(Card c)
{
enchantedBy.remove(c);
this.updateObservers();
}
public void addEnchanting(Card c)
{
enchanting.add(c);
this.updateObservers();
}
public void removeEnchanting(Card c)
{
enchanting.remove(c);
this.updateObservers();
}
public void enchantCard(Card c)
{
enchanting.add(c);
c.addEnchantedBy(this);
this.enchant();
}
public void unEnchantCard(Card c)
{
this.unEnchant();
enchanting.remove(c);
c.removeEnchantedBy(this);
}
public void unEnchantAllCards()
{
for (int i=0; i<equippedBy.size();i++)
{
enchantedBy.get(i).unEnchantCard(this);
}
}
//array size might equal 0, will NEVER be null
public Card[] getAttachedCards()
{
Card c[] = new Card[attached.size()];
attached.toArray(c);
return c;
}
public boolean hasAttachedCards() {return getAttachedCards().length != 0;}
public void attachCard(Card c) {attached.add(c); this.updateObservers();}
public void unattachCard(Card c) {attached.remove(c); this.updateObservers();}
public void setType(ArrayList<String> a) {type = new ArrayList<String>(a);}
public void addType(String a) {type.add(a); this.updateObservers();}
public void removeType(String a) {type.remove(a); this.updateObservers();}
public ArrayList<String> getType() {return new ArrayList<String>(type);}
public void setPrevType(ArrayList<String> a) {prevType = new ArrayList<String>(a);}
public void addPrevType(String a) {prevType.add(a);}
public void removePrevType(String a) {prevType.remove(a);}
public ArrayList<String> getPrevType() {return new ArrayList<String>(prevType);}
//values that are printed on card
public int getBaseAttack() {return baseAttack;}
public int getBaseDefense() {return baseDefense;}
//values that are printed on card
public void setBaseAttack(int n) {baseAttack = n; this.updateObservers();}
public void setBaseDefense(int n) {baseDefense = n; this.updateObservers();}
public int getNetAttack()
{
int total = getBaseAttack();
total += getTempAttackBoost() + getSemiPermanentAttackBoost() + getOtherAttackBoost() + getCounters(Counters.P1P1)
- getCounters(Counters.M1M1);
return total;
}
public int getNetDefense()
{
int total = getBaseDefense();
total += getTempDefenseBoost() + getSemiPermanentDefenseBoost() + getOtherDefenseBoost() + getCounters(Counters.P1P1)
- getCounters(Counters.M1M1) - getCounters(Counters.P0M1);
return total;
}
public void setRandomPicture(int n) { randomPicture = n; }
public int getRandomPicture() { return randomPicture; }
//public int getAttack(){return attack;}
//for cards like Giant Growth, etc.
public int getTempAttackBoost() {return tempAttackBoost;}
public int getTempDefenseBoost() {return tempDefenseBoost;}
public void addTempAttackBoost(int n) {tempAttackBoost += n; this.updateObservers();}
public void addTempDefenseBoost(int n) {tempDefenseBoost += n; this.updateObservers();}
public void setTempAttackBoost(int n) {tempAttackBoost = n; this.updateObservers();}
public void setTempDefenseBoost(int n) {tempDefenseBoost = n; this.updateObservers();}
//for cards like Glorious Anthem, etc.
public int getSemiPermanentAttackBoost() {return semiPermanentAttackBoost;}
public int getSemiPermanentDefenseBoost() {return semiPermanentDefenseBoost;}
public void addSemiPermanentAttackBoost(int n) { semiPermanentAttackBoost += n;}
public void addSemiPermanentDefenseBoost(int n){ semiPermanentDefenseBoost += n;}
public void setSemiPermanentAttackBoost(int n){ semiPermanentAttackBoost = n;}
public void setSemiPermanentDefenseBoost(int n) { semiPermanentDefenseBoost = n;}
//for cards like Relentless Rats, Master of Etherium, etc.
public int getOtherAttackBoost() {return otherAttackBoost;}
public int getOtherDefenseBoost() {return otherDefenseBoost;}
public void addOtherAttackBoost(int n) { otherAttackBoost += n;}
public void addOtherDefenseBoost(int n){ otherDefenseBoost += n;}
public void setOtherAttackBoost(int n){ otherAttackBoost = n;}
public void setOtherDefenseBoost(int n) { otherDefenseBoost = n;}
//public void setAttack(int n) {attack = n; this.updateObservers();}
//public void setDefense(int n) {defense = n; this.updateObservers();}
public boolean isUntapped() {return ! tapped;}
public boolean isTapped() {return tapped;}
public void setTapped(boolean b) {tapped = b; updateObservers();}
public void tap() {setTapped(true);}
public void untap() {setTapped(false);}
//keywords are like flying, fear, first strike, etc...
public ArrayList<String> getKeyword()
{
ArrayList<String> a1 = new ArrayList<String>(getIntrinsicKeyword());
ArrayList<String> a2 = new ArrayList<String>(getExtrinsicKeyword());
a1.addAll(a2);
for(Ability_Mana sa : getManaAbility())
if(sa.isBasic())
a1.add(((Ability_Mana)sa).orig);
return a1;
}
//public void setKeyword(ArrayList a) {keyword = new ArrayList(a); this.updateObservers();}
//public void addKeyword(String s) {keyword.add(s); this.updateObservers();}
//public void removeKeyword(String s) {keyword.remove(s); this.updateObservers();}
//public int getKeywordSize() {return keyword.size();}
public String[] basics = {"Plains", "Island", "Swamp", "Mountain", "Forest"};
public ArrayList<String> getIntrinsicKeyword() {return new ArrayList<String>(intrinsicKeyword);}
public void setIntrinsicKeyword(ArrayList<String> a) {intrinsicKeyword = new ArrayList<String>(a); this.updateObservers();}
public void addIntrinsicKeyword(String s) {/*if (s.startsWith("tap: add")) manaAbility.add(new Ability_Mana(this, s){}); else*/ intrinsicKeyword.add(s);}
public void removeIntrinsicKeyword(String s) { intrinsicKeyword.remove(s); this.updateObservers();}
public int getIntrinsicKeywordSize() {return intrinsicKeyword.size(); }
public ArrayList<String> getExtrinsicKeyword() {return new ArrayList<String>(extrinsicKeyword);}
public void setExtrinsicKeyword(ArrayList<String> a) {extrinsicKeyword = new ArrayList<String>(a); this.updateObservers();}
public void addExtrinsicKeyword(String s) {
if(!getKeyword().contains(s)){
if (s.startsWith("tap: add")) manaAbility.add(new Ability_Mana(this, s)
{
private static final long serialVersionUID = 221124403788942412L;
});
else extrinsicKeyword.add(s);
}
}
public void removeExtrinsicKeyword(String s) {extrinsicKeyword.remove(s); this.updateObservers();}
public int getExtrinsicKeywordSize() {return extrinsicKeyword.size(); }
public ArrayList<String> getPrevIntrinsicKeyword() { return new ArrayList<String>(prevIntrinsicKeyword);}
public void setPrevIntrinsicKeyword(ArrayList<String> a) { prevIntrinsicKeyword = new ArrayList<String>(a); this.updateObservers();}
public void addPrevIntrinsicKeyword(String s) { prevIntrinsicKeyword.add(s);}
public void removePrevIntrinsicKeyword(String s) { prevIntrinsicKeyword.remove(s); this.updateObservers();}
public int getPrevIntrinsicKeywordSize() {return prevIntrinsicKeyword.size();}
public boolean isPermanent() {return !(isInstant() || isSorcery());}
public boolean isCreature() {return type.contains("Creature");}
public boolean isBasicLand() {return type.contains("Basic");}
public boolean isLand() {return type.contains("Land");}
public boolean isSorcery() {return type.contains("Sorcery");}
public boolean isInstant() {return type.contains("Instant") /*|| getKeyword().contains("Flash")*/;}
public boolean isArtifact() {return type.contains("Artifact");}
public boolean isEquipment() {return type.contains("Equipment");}
public boolean isPlaneswalker() {return type.contains("Planeswalker");}
public boolean isTribal() {return type.contains("Tribal");}
//global and local enchantments
public boolean isEnchantment() {return typeContains("Enchantment"); }
public boolean isLocalEnchantment() {return typeContains("Aura"); }
public boolean isAura() {return typeContains("Aura"); }
public boolean isGlobalEnchantment() {return typeContains("Enchantment") && (! isLocalEnchantment());}
private boolean typeContains(String s)
{
Iterator<?> it = this.getType().iterator();
while(it.hasNext())
if(it.next().toString().startsWith(s))
return true;
return false;
}
public void setUniqueNumber(int n) {uniqueNumber = n; this.updateObservers();}
public int getUniqueNumber() {return uniqueNumber;}
public boolean equals(Object o)
{
if(o instanceof Card)
{
Card c = (Card)o;
int a = getUniqueNumber();
int b = c.getUniqueNumber();
return (a == b);
}
return false;
}
public int hashCode()
{
return getUniqueNumber();
}
public String toString()
{
return this.getName() +" (" +this.getUniqueNumber() +")";
}
public boolean hasFlashback() {
return flashback;
}
public void setFlashback(boolean b)
{
flashback = b;
}
}

48
src/CardDetailUtil.java Normal file
View File

@@ -0,0 +1,48 @@
import javax.swing.*;
interface CardDetail
{
public void updateCardDetail(Card c);
}
public class CardDetailUtil
{
public static void updateCardDetail(Card card, JTextArea area, JPanel cardDetailPanel, JPanel picturePanel, JLabel label[])
{
if(card == null)
return;
//System.out.println("label length: " + label.length);
for(int i = 0; i < label.length; i++)
label[i].setText("");
area.setText("");
if(card.isLand())
label[0].setText(card.getName());
else
label[0].setText(card.getName() +" - " +card.getManaCost());
label[1].setText(GuiDisplayUtil.formatCardType(card));
if(card.isCreature())
{
String stats = "" +card.getNetAttack() +" / " +card.getNetDefense();
label[2].setText(stats);
}
if(card.isCreature())
label[3].setText("Damage: " +card.getDamage() +" Assigned Damage: " +card.getAssignedDamage());
String uniqueID = card.getUniqueNumber() +" ";
label[4].setText("Card ID " +uniqueID);
area.setText(card.getText());
cardDetailPanel.setBorder(GuiDisplayUtil.getBorder(card));
//picture
picturePanel.removeAll();
picturePanel.add(GuiDisplayUtil.getPicture(card));
picturePanel.revalidate();
}//updateCardDetail
}

41235
src/CardFactory.java Normal file

File diff suppressed because it is too large Load Diff

2381
src/CardFactoryUtil.java Normal file

File diff suppressed because it is too large Load Diff

216
src/CardList.java Normal file
View File

@@ -0,0 +1,216 @@
import java.util.*;
public class CardList implements Iterable<Card>
{
public Iterator<Card> iterator() {
return list.iterator();
}
private ArrayList<Card> list = new ArrayList<Card>();
//private LinkedList list = new LinkedList();
public CardList() {}
public CardList(Card c[]) { addAll(c);}
public CardList(Object c[]) {addAll(c);}
// cardColor is like "R" or "G", returns a new CardList that is a subset of current CardList
public CardList getColor(String cardColor)
{
CardList c = new CardList();
Card card;
for(int i = 0; i < size(); i++)
{
card = getCard(i);
if(0 < card.getManaCost().indexOf(cardColor))//hopefully this line works
c.add(getCard(i));
}
return c;
}//getColor()
public void reverse()
{
Collections.reverse(list);
}
public boolean equals(CardList a)
{
if(list.size() != a.size())
return false;
for(int i = 0; i < list.size(); i++)
if(! list.get(i).equals(a.get(i)))
return false;
return true;
}
//removes one copy of that card
public void remove(final String cardName)
{
CardList find = this.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return c.getName().equals(cardName);
}
});
if(0 < find.size())
this.remove(find.get(0));
else
throw new RuntimeException("CardList : remove(String cardname), error - card name not found: " +cardName +" - contents of Arraylist:" +list);
}//remove(String cardName)
public int size() {return list.size();}
public void add(Card c) {list.add(c);}
public void add(int n, Card c) {list.add(n, c);}
public boolean contains(Card c) {return list.contains(c);}
//probably remove getCard() in the future
public Card getCard(int index){return (Card)list.get(index);}
public Card get(int i) {return getCard(i);}
public void addAll(Object c[])
{
for(int i = 0; i < c.length; i++)
list.add((Card)c[i]);
}
public boolean containsName(Card c)
{
return containsName(c.getName());
}
public boolean containsName(String name)
{
for(int i = 0; i < size(); i++)
if(getCard(i).getName().equals(name))
return true;
return false;
}
//returns new subset of all the cards with the same name
public CardList getName(String name)
{
CardList c = new CardList();
for(int i = 0; i < size(); i++)
if(getCard(i).getName().equals(name))
c.add(getCard(i));
return c;
}
//cardType is like "Land" or "Goblin", returns a new CardList that is a subset of current CardList
public CardList getType(String cardType)
{
CardList c = new CardList();
Card card;
for(int i = 0; i < size(); i++)
{
card = getCard(i);
if(card.getType().contains(cardType) ||
( (card.isCreature() || (card.isTribal() && !cardType.equals("Creature")) ) && !cardType.equals("Legendary") && !cardType.equals("Planeswalker") && !cardType.equals("Basic") &&
!cardType.equals("Enchantment") && !cardType.equals("Land") && !cardType.equals("Sorcery") && !cardType.equals("Instant") &&
!cardType.equals("Artifact") && !cardType.equals("Plains") && !cardType.equals("Mountain") && !cardType.equals("Island") &&
!cardType.equals("Forest") && !cardType.equals("Swamp") && card.getKeyword().contains("Changeling") ) )//changelings, see Lorwyn FAQ
c.add(getCard(i));
}
return c;
}//getType()
public CardList filter(CardListFilter f)
{
CardList c = new CardList();
for(int i = 0; i < size(); i++)
if(f.addCard(getCard(i)))
c.add(getCard(i));
return c;
}
public final Card[] toArray()
{
Card[] c = new Card[list.size()];
list.toArray(c);
return c;
}
public String toString() {return list.toString();}
public boolean isEmpty() {return list.isEmpty();}
public Card remove(int i) {return (Card)list.remove(i);}
public void remove(Card c) {list.remove(c);}
public void clear() {list.clear();}
public void shuffle()
{
Collections.shuffle(list, MyRandom.random);
Collections.shuffle(list, MyRandom.random);
Collections.shuffle(list, MyRandom.random);
}
public void sort(Comparator<Card> c) {Collections.sort(list, c);}
public CardList getValidCards(String Restrictions[])
{
CardList tmpList = new CardList(toArray());
CardList retList = new CardList();
for (int i=0;i<Restrictions.length;i++)
{
String incR[] = Restrictions[i].split("\\."); // Inclusive restrictions are Card types
if (! incR[0].equals("Permanent")) // Since the cards don't actually say "Permanent"
tmpList = getType(incR[0]);
if (incR.length > 1)
{
final String excR = incR[1];
tmpList = tmpList.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
boolean r = true;
String exR[] = excR.split("\\+"); // Exclusive Restrictions are ...
for (int j=0;j<exR.length;j++)
{
if (exR[j].contains("White") || // ... Card colors
exR[j].contains("Blue") ||
exR[j].contains("Black") ||
exR[j].contains("Red") ||
exR[j].contains("Green") ||
exR[j].contains("Colorless"))
if (exR[j].startsWith("non"))
r = r && (! CardUtil.getColors(c).contains(exR[j].substring(3).toLowerCase()));
else
r = r && (CardUtil.getColors(c).contains(exR[j].toLowerCase()));
else if (exR[j].contains("MultiColor")) // ... Card is multicolored
if (exR[j].startsWith("non"))
r = r && (CardUtil.getColors(c).size() == 1);
else
r = r && (CardUtil.getColors(c).size() > 1);
else if (exR[j].contains("with")) // ... Card keywords
if (exR[j].startsWith("without"))
r = r && (! c.getKeyword().contains(exR[j].substring(7)));
else
r = r && (c.getKeyword().contains(exR[j].substring(4)));
//TODO: converted mana cost
//TODO: tapped
//TODO: enchanted
//TODO: enchanting
//TODO: token
//TODO: counters
else
if (exR[j].startsWith("non")) // ... Other Card types
r = r && (! c.getType().contains(exR[j].substring(3)));
else
r = r && (c.getType().contains(exR[j]));
}
return r;
}
});
}
retList.addAll(tmpList.toArray());
}
return retList;
}//getValidCards
}

4
src/CardListFilter.java Normal file
View File

@@ -0,0 +1,4 @@
public interface CardListFilter
{
public boolean addCard(Card c);
}

183
src/CardListUtil.java Normal file
View File

@@ -0,0 +1,183 @@
import java.util.*;
public class CardListUtil
{
public static CardList filterToughness(CardList in, int atLeastToughness)
{
CardList out = new CardList();
for(int i = 0; i < in.size(); i++)
if(in.get(i).getNetDefense() <= atLeastToughness)
out.add(in.get(i));
return out;
}
//the higher the defense the better
@SuppressWarnings("unchecked") // Comparator needs <type>
public static void sortDefense(CardList list)
{
Comparator com = new Comparator()
{
public int compare(Object a1, Object b1)
{
Card a = (Card)a1;
Card b = (Card)b1;
return b.getNetDefense() - a.getNetDefense();
}
};
list.sort(com);
}//sortDefense()
//the higher the attack the better
@SuppressWarnings("unchecked") // Comparator needs type
public static void sortAttack(CardList list)
{
Comparator com = new Comparator()
{
public int compare(Object a1, Object b1)
{
Card a = (Card)a1;
Card b = (Card)b1;
if (CombatUtil.isDoranInPlay())
return b.getNetDefense() - a.getNetDefense();
else
return b.getNetAttack() - a.getNetAttack();
}
};
list.sort(com);
}//sortAttack()
//the lower the attack the better
@SuppressWarnings("unchecked") // Comparator needs <type>
public static void sortAttackLowFirst(CardList list)
{
Comparator com = new Comparator()
{
public int compare(Object a1, Object b1)
{
Card a = (Card)a1;
Card b = (Card)b1;
if (CombatUtil.isDoranInPlay())
return a.getNetDefense() - b.getNetDefense();
else
return a.getNetAttack() - b.getNetAttack();
}
};
list.sort(com);
}//sortAttackLowFirst()
public static void sortNonFlyingFirst(CardList list)
{
sortFlying(list);
list.reverse();
}//sortNonFlyingFirst
//the creature with flying are better
@SuppressWarnings("unchecked") // Comparator needs <type>
public static void sortFlying(CardList list)
{
Comparator com = new Comparator()
{
public int compare(Object a1, Object b1)
{
Card a = (Card)a1;
Card b = (Card)b1;
if(a.getKeyword().contains("Flying") && b.getKeyword().contains("Flying"))
return 0;
else if(a.getKeyword().contains("Flying"))
return -1;
else if(b.getKeyword().contains("Flying"))
return 1;
return 0;
}
};
list.sort(com);
}//sortFlying()
@SuppressWarnings("unchecked") // Comparator needs <type>
public static void sortCMC(CardList list)
{
Comparator com = new Comparator()
{
public int compare(Object a1, Object b1)
{
Card a = (Card)a1;
Card b = (Card)b1;
int cmcA = CardUtil.getConvertedManaCost(a.getManaCost());
int cmcB = CardUtil.getConvertedManaCost(b.getManaCost());
if (cmcA == cmcB)
return 0;
if (cmcA > cmcB)
return -1;
if (cmcB > cmcA)
return 1;
return 0;
}
};
list.sort(com);
}//sortCMC
public static CardList getColor(CardList list, final String color)
{
return list.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return CardUtil.getColor(c).equals(color);
}
});
}//getColor()
public static CardList getGoldCards(CardList list)
{
return list.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return CardUtil.getColors(c).size() >= 2;
}
});
}
public static int sumAttack(CardList c)
{
int attack = 0;
for(int i = 0; i < c.size(); i++){
if(c.get(i).isCreature() && (!c.get(i).hasFirstStrike() || (c.get(i).hasDoubleStrike() && c.get(i).hasFirstStrike())) ) {
if (!CombatUtil.isDoranInPlay())
attack += c.get(i).getNetAttack();
else if(CombatUtil.isDoranInPlay())
attack += c.get(i).getNetDefense();
}
}
//System.out.println("Total attack: " +attack);
return attack;
}//sumAttack()
public static int sumFirstStrikeAttack(CardList c)
{
int attack = 0;
for(int i = 0; i < c.size(); i++){
if(c.get(i).isCreature() && (c.get(i).hasFirstStrike() || c.get(i).hasDoubleStrike())) {
if (!CombatUtil.isDoranInPlay())
attack += c.get(i).getNetAttack();
else if(CombatUtil.isDoranInPlay())
attack += c.get(i).getNetDefense();
}
}
System.out.println("Total First Strike attack: " +attack);
return attack;
}//sumFirstStrikeAttack()
}

20
src/CardPanel.java Normal file
View File

@@ -0,0 +1,20 @@
import javax.swing.*;
public class CardPanel extends JPanel
{
private static final long serialVersionUID = 509877513760665415L;
private Card card;
public CardPanel(Card card)
{
this.card = card;
}
public Card getCard()
{
return card;
}
//~
public CardPanel connectedCard;
//~
}

184
src/CardUtil.java Normal file
View File

@@ -0,0 +1,184 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
public class CardUtil
{
public final static Random r = new Random();
public static int getRandomIndex(Object[] o)
{
if(o == null || o.length == 0)
throw new RuntimeException("CardUtil : getRandomIndex() argument is null or length is 0");
return r.nextInt(o.length);
}
public static Card getRandom(Card[] o)
{
return o[getRandomIndex(o)];
}
public static int getRandomIndex(SpellAbilityList list)
{
if(list == null || list.size() == 0)
throw new RuntimeException("CardUtil : getRandomIndex(SpellAbilityList) argument is null or length is 0");
return r.nextInt(list.size());
}
public static int getRandomIndex(CardList c)
{return r.nextInt(c.size());}
//returns Card Name (unique number) attack/defense
//example: Big Elf (12) 2/3
public static String toText(Card c)
{
return c.getName() +" (" +c.getUniqueNumber() +") " +c.getNetAttack() +"/" +c.getNetDefense();
}
public static Card[] toCard(Collection<Card> col)
{
Object o[] = col.toArray();
Card c[] = new Card[o.length];
for(int i = 0; i < c.length; i++)
{
Object swap = o[i];
if(swap instanceof Card)
c[i] = (Card)o[i];
else
throw new RuntimeException("CardUtil : toCard() invalid class, should be Card - " +o[i].getClass() +" - toString() - " +o[i].toString());
}
return c;
}
public static Card[] toCard(ArrayList<Card> list)
{
Card[] c = new Card[list.size()];
list.toArray(c);
return c;
}
public static ArrayList<Card> toList(Card c[])
{
ArrayList<Card> a = new ArrayList<Card>();
for(int i = 0; i < c.length; i++)
a.add(c[i]);
return a;
}
//returns "G", longColor is Constant.Color.Green and the like
public static String getShortColor(String longColor)
{
Map<String,String> map = new HashMap<String,String>();
map.put(Constant.Color.Black, "B");
map.put(Constant.Color.Blue , "U");
map.put(Constant.Color.Green, "G");
map.put(Constant.Color.Red , "R");
map.put(Constant.Color.White, "W");
Object o = map.get(longColor);
if(o == null)
throw new RuntimeException("CardUtil : getShortColor() invalid argument - " +longColor);
return (String)o;
}
//returns something like Constant.Color.Green or something
public static String getColor(Card c)
{
String manaCost = c.getManaCost();
if(-1 != manaCost.indexOf("G"))
return Constant.Color.Green;
else if(-1 != manaCost.indexOf("W"))
return Constant.Color.White;
else if(-1 != manaCost.indexOf("B"))
return Constant.Color.Black;
else if(-1 != manaCost.indexOf("U"))
return Constant.Color.Blue;
else if(-1 != manaCost.indexOf("R"))
return Constant.Color.Red;
else
return Constant.Color.Colorless;
}
public static ArrayList<String> getColors(Card c)
{
String m = c.getManaCost();
Set<String> colors = new HashSet<String>();
for(int i = 0; i < m.length(); i++)
{
switch(m.charAt(i))
{
case ' ': break;
case 'G': colors.add(Constant.Color.Green); break;
case 'W': colors.add(Constant.Color.White); break;
case 'B': colors.add(Constant.Color.Black); break;
case 'U': colors.add(Constant.Color.Blue); break;
case 'R': colors.add(Constant.Color.Red); break;
}
}
if(colors.isEmpty())
colors.add(Constant.Color.Colorless);
return new ArrayList<String>(colors);
}
public static boolean hasCardName(String cardName, ArrayList<Card> list)
{
Card c;
boolean b = false;
for(int i = 0; i < list.size(); i++)
{
c = (Card)list.get(i);
if(c.getName().equals(cardName))
{
b = true;
break;
}
}
return b;
}//hasCardName()
//probably should put this somewhere else, but not sure where
static public int getConvertedManaCost(SpellAbility sa)
{
return getConvertedManaCost(sa.getManaCost());
}
static public int getConvertedManaCost(String manaCost)
{
//see if the mana cost is all colorless, like "2", "0", or "12"
if(manaCost.equals(""))
return 0;
if (!manaCost.matches(".*[A-Z]+.*"))
{
try{
return Integer.parseInt(manaCost);
}
catch(NumberFormatException ex) { ErrorViewer.showError(ex); }
}
//see if mana cost is colored and colorless like "2 B" or "1 U U"
StringTokenizer tok = new StringTokenizer(manaCost);
int cost = 0;
try{
//get the int from the mana cost like "1 U", get the 1
cost = Integer.parseInt(tok.nextToken());
//count colored mana cost
cost += tok.countTokens();
return cost;
}
//catches in case the cost has no colorless mana requirements like "U U"
catch(NumberFormatException ex) {}
//the mana cost is all colored mana like "U" or "B B B"
tok = new StringTokenizer(manaCost);
return tok.countTokens();
}
}

409
src/Combat.java Normal file
View File

@@ -0,0 +1,409 @@
import java.util.*;
public class Combat
{
//key is attacker Card
//value is CardList of blockers
private Map<Card,CardList> map = new HashMap<Card,CardList>();
private Set<Card> blocked = new HashSet<Card>();
private HashMap<Card,CardList> unblockedMap = new HashMap<Card,CardList>();
private int attackingDamage;
private int defendingDamage;
private int defendingFirstStrikeDamage;
//private int trampleDamage;
//private int trampleFirstStrikeDamage;
private String attackingPlayer;
private String defendingPlayer;
private int declaredAttackers;
private Card planeswalker;
public Combat() {reset();}
public void reset()
{
planeswalker = null;
map.clear();
blocked.clear();
unblockedMap.clear();
attackingDamage = 0;
defendingDamage = 0;
defendingFirstStrikeDamage = 0;
declaredAttackers = 0;
attackingPlayer = "";
defendingPlayer = "";
}
public void setPlaneswalker(Card c){planeswalker = c;}
public Card getPlaneswalker() {return planeswalker;}
public int getDeclaredAttackers() { return declaredAttackers;}
public void setAttackingPlayer(String player) {attackingPlayer = player;}
public void setDefendingPlayer(String player) {defendingPlayer = player;}
public String getAttackingPlayer() {return attackingPlayer;}
public String getDefendingPlayer() {return defendingPlayer;}
//relates to defending player damage
public int getDefendingDamage() {return defendingDamage;}
public int getDefendingFirstStrikeDamage() {return defendingFirstStrikeDamage;}
public void setDefendingDamage()
{
defendingDamage = 0;
CardList att = new CardList(getAttackers());
//sum unblocked attackers' power
for(int i = 0; i < att.size(); i++) {
if(! isBlocked(att.get(i))) {
int damageDealt = att.get(i).getNetAttack();
if (CombatUtil.isDoranInPlay())
damageDealt = att.get(i).getNetDefense();
//if the creature has first strike do not do damage in the normal combat phase
if(!att.get(i).hasFirstStrike() || (att.get(i).hasFirstStrike() && att.get(i).hasDoubleStrike()) )
defendingDamage += damageDealt;
}
}
}
public void setDefendingFirstStrikeDamage()
{
defendingFirstStrikeDamage = 0;
CardList att = new CardList(getAttackers());
//sum unblocked attackers' power
for(int i = 0; i < att.size(); i++) {
if(! isBlocked(att.get(i))) {
int damageDealt = att.get(i).getNetAttack();
if (CombatUtil.isDoranInPlay())
damageDealt = att.get(i).getNetDefense();
//if the creature has first strike or double strike do damage in the first strike combat phase
if(att.get(i).hasFirstStrike() || att.get(i).hasDoubleStrike()){
defendingFirstStrikeDamage += damageDealt;
}
}
}
}
public void addDefendingDamage(int n) {defendingDamage += n;}
public void addDefendingFirstStrikeDamage(int n) {defendingFirstStrikeDamage += n;}
public void addAttackingDamage(int n) {attackingDamage += n;}
public int getAttackingDamage() {return attackingDamage;}
public void addAttacker(Card c) {map.put(c, new CardList()); declaredAttackers++;}
public void resetAttackers() {map.clear();}
public Card[] getAttackers()
{
CardList out = new CardList();
Iterator<Card> it = map.keySet().iterator();
//int i = 0; //unused
while(it.hasNext()) {
out.add((Card)it.next());
}
return out.toArray();
}//getAttackers()
public boolean isBlocked(Card attacker) {return blocked.contains(attacker);}
public void addBlocker(Card attacker, Card blocker)
{
blocked.add(attacker);
getList(attacker).add(blocker);
CombatUtil.checkBlockedAttackers(attacker, blocker);
}
public void resetBlockers()
{
reset();
CardList att = new CardList(getAttackers());
for(int i = 0; i < att.size(); i++)
addAttacker(att.get(i));
}
public CardList getAllBlockers()
{
CardList att = new CardList(getAttackers());
CardList block = new CardList();
for(int i = 0; i < att.size(); i++)
block.addAll(getBlockers(att.get(i)).toArray());
return block;
}//getAllBlockers()
public CardList getBlockers(Card attacker) {return new CardList(getList(attacker).toArray());
}
private CardList getList(Card attacker) {return (CardList)map.get(attacker);}
public void removeFromCombat(Card c)
{
//is card an attacker?
CardList att = new CardList(getAttackers());
if(att.contains(c))
map.remove(c);
else//card is a blocker
{
for(int i = 0; i < att.size(); i++)
if(getBlockers(att.get(i)).contains(c))
getList(att.get(i)).remove(c);
}
}//removeFromCombat()
public void verifyCreaturesInPlay()
{
CardList all = new CardList();
all.addAll(getAttackers());
all.addAll(getAllBlockers().toArray());
for(int i = 0; i < all.size(); i++)
if(! AllZone.GameAction.isCardInPlay(all.get(i)))
removeFromCombat(all.get(i));
}//verifyCreaturesInPlay()
//set Card.setAssignedDamage() for all creatures in combat
//also assigns player damage by setPlayerDamage()
public void setAssignedFirstStrikeDamage()
{
setDefendingFirstStrikeDamage();
CardList block;
CardList attacking = new CardList(getAttackers());
for(int i = 0; i < attacking.size(); i++)
{
block = getBlockers(attacking.get(i));
//attacker always gets all blockers' attack
AllZone.GameAction.setAssignedDamage(attacking.get(i), block, CardListUtil.sumFirstStrikeAttack(block));
//attacking.get(i).setAssignedDamage(CardListUtil.sumFirstStrikeAttack(block));
if(block.size() == 0)//this damage is assigned to a player by setPlayerDamage()
{
//GameActionUtil.executePlayerCombatDamageEffects(attacking.get(i));
addUnblockedAttacker(attacking.get(i));
}
else if(block.size() == 1)
{
if(attacking.get(i).hasFirstStrike() || attacking.get(i).hasDoubleStrike()){
int damageDealt = attacking.get(i).getNetAttack();
if (CombatUtil.isDoranInPlay())
damageDealt = attacking.get(i).getNetDefense();
//block.get(0).setAssignedDamage(damageDealt);
CardList cl = new CardList();
cl.add(attacking.get(i));
AllZone.GameAction.setAssignedDamage(block.get(0), cl , damageDealt);
//trample
int trample = damageDealt - block.get(0).getNetDefense();
if(attacking.get(i).getKeyword().contains("Trample") && 0 < trample)
{
this.addDefendingFirstStrikeDamage(trample);
//System.out.println("First Strike trample damage: " + trample);
}
}
}//1 blocker
else if(getAttackingPlayer().equals(Constant.Player.Computer))
{
if(attacking.get(i).hasFirstStrike() || attacking.get(i).hasDoubleStrike()){
int damageDealt = attacking.get(i).getNetAttack();
if (CombatUtil.isDoranInPlay())
damageDealt = attacking.get(i).getNetDefense();
setAssignedFirstStrikeDamage(attacking.get(i), block, damageDealt);
}
}
else//human
{
if(attacking.get(i).hasFirstStrike() || attacking.get(i).hasDoubleStrike()){
//GuiDisplay2 gui = (GuiDisplay2) AllZone.Display;
int damageDealt = attacking.get(i).getNetAttack();
if (CombatUtil.isDoranInPlay())
damageDealt = attacking.get(i).getNetDefense();
AllZone.Display.assignDamage(attacking.get(i),block, damageDealt);
//System.out.println("setAssignedFirstStrikeDmg called for:" + damageDealt + " damage.");
}
}
}//for
//should first strike affect the following?
if(getPlaneswalker() != null)
{
//System.out.println("defendingDmg (setAssignedFirstStrikeDamage) :" +defendingFirstStrikeDamage);
planeswalker.setAssignedDamage(defendingFirstStrikeDamage);
defendingFirstStrikeDamage = 0;
}
}//setAssignedFirstStrikeDamage()
private void setAssignedFirstStrikeDamage(Card attacker, CardList list, int damage)
{
CardListUtil.sortAttack(list);
Card c;
for(int i = 0; i < list.size(); i++)
{
c = list.get(i);
if(c.getKillDamage() <= damage)
{
damage -= c.getKillDamage();
CardList cl = new CardList();
cl.add(attacker);
AllZone.GameAction.setAssignedDamage(c, cl, c.getKillDamage());
//c.setAssignedDamage(c.getKillDamage());
}
}//for
}//setAssignedFirstStrikeDamage()
//set Card.setAssignedDamage() for all creatures in combat
//also assigns player damage by setPlayerDamage()
public void setAssignedDamage()
{
setDefendingDamage();
CardList block;
CardList attacking = new CardList(getAttackers());
for(int i = 0; i < attacking.size(); i++)
{
if(!attacking.get(i).hasFirstStrike() || (attacking.get(i).hasFirstStrike() && attacking.get(i).hasDoubleStrike() )){
block = getBlockers(attacking.get(i));
//attacker always gets all blockers' attack
//attacking.get(i).setAssignedDamage(CardListUtil.sumAttack(block));
AllZone.GameAction.setAssignedDamage(attacking.get(i), block, CardListUtil.sumAttack(block));
if(block.size() == 0)//this damage is assigned to a player by setPlayerDamage()
{
//GameActionUtil.executePlayerCombatDamageEffects(attacking.get(i));
addUnblockedAttacker(attacking.get(i));
}
else if(block.size() == 1)
{
int damageDealt = attacking.get(i).getNetAttack();
if (CombatUtil.isDoranInPlay())
damageDealt = attacking.get(i).getNetDefense();
//block.get(0).setAssignedDamage(damageDealt);
CardList cl = new CardList();
cl.add(attacking.get(i));
AllZone.GameAction.setAssignedDamage(block.get(0), cl , damageDealt);
//trample
int trample = damageDealt - block.get(0).getNetDefense();
if(attacking.get(i).getKeyword().contains("Trample") && 0 < trample) {
this.addDefendingDamage(trample);
//System.out.println("Reg trample damage: " + trample);
}
}//1 blocker
else if(getAttackingPlayer().equals(Constant.Player.Computer))
{
int damageDealt = attacking.get(i).getNetAttack();
if (CombatUtil.isDoranInPlay())
damageDealt = attacking.get(i).getNetDefense();
setAssignedDamage(attacking.get(i),block, damageDealt);
}
else//human
{
//GuiDisplay2 gui = (GuiDisplay2) AllZone.Display;
int damageDealt = attacking.get(i).getNetAttack();
if (CombatUtil.isDoranInPlay())
damageDealt = attacking.get(i).getNetDefense();
AllZone.Display.assignDamage(attacking.get(i), block, damageDealt);
//System.out.println("setAssignedDmg called for:" + damageDealt + " damage.");
}
}//if !hasFirstStrike ...
//hacky code, to ensure surviving non-first-strike blockers will hit first strike attackers:
else {
block = getBlockers(attacking.get(i));
//System.out.println("block size: " + block.size());
if( (attacking.get(i).hasFirstStrike() || attacking.get(i).hasDoubleStrike()) )
{
int blockerDamage = 0;
for(int j=0; j < block.size(); j++)
{
blockerDamage += block.get(j).getNetAttack();
}
//attacking.get(i).setAssignedDamage(blockerDamage);
AllZone.GameAction.setAssignedDamage(attacking.get(i), block , blockerDamage);
}
}
}//for
//should first strike affect the following?
if(getPlaneswalker() != null)
{
//System.out.println("defendingDmg (setAssignedDamage): " + defendingDamage);
planeswalker.setAssignedDamage(defendingDamage);
defendingDamage = 0;
}
}//assignDamage()
private void setAssignedDamage(Card attacker, CardList list, int damage)
{
CardListUtil.sortAttack(list);
Card c;
for(int i = 0; i < list.size(); i++)
{
c = list.get(i);
//if(!c.hasFirstStrike() || (c.hasFirstStrike() && c.hasDoubleStrike()) ){
if(c.getKillDamage() <= damage)
{
damage -= c.getKillDamage();
CardList cl = new CardList();
cl.add(attacker);
AllZone.GameAction.setAssignedDamage(c, cl, c.getKillDamage());
//c.setAssignedDamage(c.getKillDamage());
}
//}
}//for
}//assignDamage()
public Card[] getUnblockedAttackers()
{
CardList out = new CardList();
Iterator<Card> it = unblockedMap.keySet().iterator();
while(it.hasNext()){ //only add creatures without firstStrike to this list.
Card c = (Card)it.next();
if(!c.hasFirstStrike()){
out.add(c);
}
}
return out.toArray();
}//getUnblockedAttackers()
public Card[] getUnblockedFirstStrikeAttackers()
{
CardList out = new CardList();
Iterator<Card> it = unblockedMap.keySet().iterator();
while(it.hasNext()){ //only add creatures without firstStrike to this list.
Card c = (Card)it.next();
if(c.hasFirstStrike() || c.hasDoubleStrike()){
out.add(c);
}
}
return out.toArray();
}//getUnblockedAttackers()
public void addUnblockedAttacker(Card c)
{
unblockedMap.put(c, new CardList());
}
}//Class Combat
/*
if(cr only has 1 blocker)
assign damage to attacker and blocker
else attacking play is computer
attacker.assignDamage(sum blockers' attack)
Combat.assignDamage(blockers, attack.getAttack())
else //human
attacker.assignDamage(sum blockers' attack)
guiDisplay.assignDamage(blockers, attack.getAtack())
*/

183
src/CombatPlaneswalker.java Normal file
View File

@@ -0,0 +1,183 @@
import java.util.*;
public class CombatPlaneswalker
{
//key is attacker Card
//value is CardList of blockers
private Map<Card,CardList> map = new HashMap<Card,CardList>();
private Set<Card> blocked = new HashSet<Card>();
private int attackingDamage;
private int defendingDamage;
private String attackingPlayer;
private String defendingPlayer;
private Card planeswalker;
public CombatPlaneswalker() {reset();}
public void reset()
{
planeswalker = null;
map.clear();
blocked.clear();
attackingDamage = 0;
defendingDamage = 0;
attackingPlayer = "";
defendingPlayer = "";
}
public void setPlaneswalker(Card c){planeswalker = c;}
public Card getPlaneswalker() {return planeswalker;}
public void setAttackingPlayer(String player) {attackingPlayer = player;}
public void setDefendingPlayer(String player) {defendingPlayer = player;}
public String getAttackingPlayer() {return attackingPlayer;}
public String getDefendingPlayer() {return defendingPlayer;}
//relates to defending player damage
public int getDefendingDamage() {return defendingDamage;}
public void setDefendingDamage()
{
defendingDamage = 0;
CardList att = new CardList(getAttackers());
//sum unblocked attackers' power
for(int i = 0; i < att.size(); i++)
if(! isBlocked(att.get(i)))
defendingDamage += att.get(i).getNetAttack();
}
public void addDefendingDamage(int n) {defendingDamage += n;}
public void addAttackingDamage(int n) {attackingDamage += n;}
public int getAttackingDamage() {return attackingDamage;}
public void addAttacker(Card c) {map.put(c, new CardList());}
public void resetAttackers() {map.clear();}
public Card[] getAttackers()
{
CardList out = new CardList();
Iterator<Card> it = map.keySet().iterator();
while(it.hasNext())
out.add((Card)it.next());
return out.toArray();
}//getAttackers()
public boolean isBlocked(Card attacker) {return blocked.contains(attacker);}
public void addBlocker(Card attacker, Card blocker)
{
blocked.add(attacker);
getList(attacker).add(blocker);
}
public void resetBlockers()
{
reset();
CardList att = new CardList(getAttackers());
for(int i = 0; i < att.size(); i++)
addAttacker(att.get(i));
}
public CardList getAllBlockers()
{
CardList att = new CardList(getAttackers());
CardList block = new CardList();
for(int i = 0; i < att.size(); i++)
block.addAll(getBlockers(att.get(i)).toArray());
return block;
}//getAllBlockers()
public CardList getBlockers(Card attacker) {return new CardList(getList(attacker).toArray());}
private CardList getList(Card attacker) {return (CardList)map.get(attacker);}
public void removeFromCombat(Card c)
{
//is card an attacker?
CardList att = new CardList(getAttackers());
if(att.contains(c))
map.remove(c);
else//card is a blocker
{
for(int i = 0; i < att.size(); i++)
if(getBlockers(att.get(i)).contains(c))
getList(att.get(i)).remove(c);
}
}//removeFromCombat()
public void verifyCreaturesInPlay()
{
CardList all = new CardList();
all.addAll(getAttackers());
all.addAll(getAllBlockers().toArray());
for(int i = 0; i < all.size(); i++)
if(! AllZone.GameAction.isCardInPlay(all.get(i)))
removeFromCombat(all.get(i));
}//verifyCreaturesInPlay()
//set Card.setAssignedDamage() for all creatures in combat
//also assigns player damage by setPlayerDamage()
public void setAssignedDamage()
{
setDefendingDamage();
CardList block;
CardList attacking = new CardList(getAttackers());
for(int i = 0; i < attacking.size(); i++)
{
block = getBlockers(attacking.get(i));
//attacker always gets all blockers' attack
AllZone.GameAction.setAssignedDamage(attacking.get(i), block, CardListUtil.sumAttack(block));
//attacking.get(i).setAssignedDamage(CardListUtil.sumAttack(block));
if(block.size() == 0)//this damage is assigned to a player by setPlayerDamage()
;
else if(block.size() == 1)
{
block.get(0).setAssignedDamage(attacking.get(i).getNetAttack());
//trample
int trample = attacking.get(i).getNetAttack() - block.get(0).getNetDefense();
if(attacking.get(i).getKeyword().contains("Trample") && 0 < trample)
this.addDefendingDamage(trample);
trample = block.get(0).getNetAttack() - attacking.get(i).getNetDefense();
if(block.get(0).getKeyword().contains("Trample") && 0 < trample)
this.addAttackingDamage(trample);
}//1 blocker
else if(getAttackingPlayer().equals(Constant.Player.Computer))
{
setAssignedDamage(block, attacking.get(i).getNetAttack());
}
else//human
{
GuiDisplay2 gui = (GuiDisplay2) AllZone.Display;
gui.assignDamage(attacking.get(i), block, attacking.get(i).getNetAttack());
}
}//for
planeswalker.setAssignedDamage(defendingDamage);
defendingDamage = 0;
}//assignDamage()
private void setAssignedDamage(CardList list, int damage)
{
CardListUtil.sortAttack(list);
Card c;
for(int i = 0; i < list.size(); i++)
{
c = list.get(i);
if(c.getKillDamage() <= damage)
{
damage -= c.getKillDamage();
c.setAssignedDamage(c.getKillDamage());
}
}//for
}//assignDamage()
}

1288
src/CombatUtil.java Normal file

File diff suppressed because it is too large Load Diff

10
src/Command.java Normal file
View File

@@ -0,0 +1,10 @@
public interface Command extends java.io.Serializable
{
public static Command Blank = new Command() {
private static final long serialVersionUID = 2689172297036001710L;
public void execute() {}};
public void execute();
}

4
src/CommandArgs.java Normal file
View File

@@ -0,0 +1,4 @@
public interface CommandArgs extends java.io.Serializable
{
public void execute(Object o);
}

26
src/CommandList.java Normal file
View File

@@ -0,0 +1,26 @@
import java.util.*;
public class CommandList implements java.io.Serializable, Command
{
private static final long serialVersionUID = -1532687201812613302L;
private ArrayList<Command> a = new ArrayList<Command>();
//bug fix, when token is pumped up like with Giant Growth
//and Sorceress Queen targets token, the effects need to be done
//in this order, weird I know, DO NOT CHANGE THIS
public void add(Command c) {a.add(0,c);}
public Command get(int i) {return (Command) a.get(i);}
public Command remove(int i) {return (Command)a.remove(i);}
public int size() {return a.size();}
public void clear() {a.clear();}
public void execute()
{
for(int i = 0; i < size(); i++)
get(i).execute();
}
}

4
src/CommandReturn.java Normal file
View File

@@ -0,0 +1,4 @@
public interface CommandReturn
{
public Object execute();
}

15
src/Computer.java Normal file
View File

@@ -0,0 +1,15 @@
public interface Computer
{
//must shuffle this
public Card[] getLibrary();
public void main1();
public void declare_attackers_before(); //can play Instants and Abilities
public void declare_attackers();
public void declare_blockers();//this is called after when the Human or Computer blocks
public void declare_blockers_after();//can play Instants and Abilities
public void main2();
public void end_of_turn();//end of Human's turn
public void stack_not_empty();
}

132
src/ComputerAI_Burn.java Normal file
View File

@@ -0,0 +1,132 @@
//import java.util.*;
import javax.swing.SwingUtilities;
public class ComputerAI_Burn implements Computer {
private volatile boolean playLand = true;
public void main1() {
if(playLand) {
playLand = false;
ComputerUtil.playLand();
}
Runnable run = new Runnable() {
public void run() {
synchronized(ComputerAI_Burn.this) {
if(AllZone.Stack.size() == 0) {
SpellAbility[] all = ComputerUtil.getSpellAbility();
for(int i = 0; i < all.length; i++) {
if(ComputerUtil.canPayCost(all[i]) && all[i].canPlay()) {
if(all[i].isSpell()) AllZone.Computer_Hand.remove(all[i].getSourceCard());
if(all[i] instanceof Ability_Tap) {
all[i].getSourceCard().tap();
}
ComputerUtil.payManaCost(all[i]);
String name = all[i].getSourceCard().getName();
if(name.equals("Shock") || name.equals("Lightning Bolt") || name.equals("Char")) all[i].setTargetPlayer(Constant.Player.Human);
else all[i].chooseTargetAI();
AllZone.Stack.add(all[i]);
return;
}
}//for
if(AllZone.Phase.is(Constant.Phase.Main1, Constant.Player.Computer)) {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn.runnable) = true; Note: this is untested, did it work?");
AllZone.Phase.setNeedToNextPhase(true);
}
}//if
}//synchronized
}//run()
};//Runnable
try {
SwingUtilities.invokeLater(run);
} catch(Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("ComputerAI_Burn : main1() error, " + ex);
}
}//main1()
public void main2() {
playLand = true;
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn.main2) = true; Note, this is untested, did it work?");
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_attackers_before()
{
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_attackers() {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn.declare_attackers) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_blockers() {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn.declare_blockers()) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_blockers_after() {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn.declare_blockers_after()) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
//end of Human's turn
public void end_of_turn() {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn.end_of_turn()) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
//must shuffle this
public Card[] getLibrary() {
CardFactory cf = AllZone.CardFactory;
CardList library = new CardList();
for(int i = 0; i < 4; i++) {
library.add(cf.getCard("Lightning Bolt", Constant.Player.Computer));
library.add(cf.getCard("Shock", Constant.Player.Computer));
library.add(cf.getCard("Pyroclasm", Constant.Player.Computer));
}
for(int i = 0; i < 3; i++) {
library.add(cf.getCard("Nevinyrral's Disk", Constant.Player.Computer));
library.add(cf.getCard("Lava Spike", Constant.Player.Computer));
}
for(int i = 0; i < 2; i++) {
library.add(cf.getCard("Hidetsugu's Second Rite", Constant.Player.Computer));
library.add(cf.getCard("Char", Constant.Player.Computer));
library.add(cf.getCard("Flamebreak", Constant.Player.Computer));
library.add(cf.getCard("Mox Ruby", Constant.Player.Computer));
}
// library.add(cf.getCard("Tanglebloom", Constant.Player.Computer));
for(int i = 0; i < 14; i++)
library.add(cf.getCard("Mountain", Constant.Player.Computer));
if(library.size() != 40)
throw new RuntimeException("ComputerAI_Burn : getLibrary() error, library size is " + library.size());
return library.toArray();
}
public void stack_not_empty() {
//same as Input.stop() method
//ends the method
//different than methods because this isn't a phase like Main1 or Declare Attackers
AllZone.InputControl.resetInput();
AllZone.InputControl.updateObservers();
}
}

176
src/ComputerAI_Burn2.java Normal file
View File

@@ -0,0 +1,176 @@
//import java.util.*;
import javax.swing.SwingUtilities;
public class ComputerAI_Burn2 implements Computer {
private volatile boolean playLand = true;
public void main1() {
if(playLand) {
playLand = false;
ComputerUtil.playLand();
Card c[] = AllZone.Computer_Hand.getCards();
if(c.length != 0) {
// System.out.print("hand - ");
// for(int i = 0; i < c.length; i++)
// System.out.print(c[i] +" ");
// System.out.println();
}
}
Runnable run = new Runnable() {
@SuppressWarnings("null")
public void run() {
synchronized(ComputerAI_Burn2.this) {
if(AllZone.Stack.size() == 0
&& AllZone.Phase.is(Constant.Phase.Main1, Constant.Player.Computer)) {
SpellAbilityList list = null; //Move3.getBestMove();
if(list.toString().trim().length() != 0) {
// System.out.println("Spell List - " +list);
}
if(list.size() != 0) {
SpellAbility sa = list.get(0);
if(ComputerUtil.canPlay(sa) && sa.canPlay()) {
if(sa.isSpell()) {
AllZone.Computer_Hand.remove(sa.getSourceCard());
sa.getSourceCard().comesIntoPlay();
}
if(sa instanceof Ability_Tap) sa.getSourceCard().tap();
ComputerUtil.payManaCost(sa);
AllZone.Stack.add(sa);
} else throw new RuntimeException("ComputerAI_Burn2 error, cannot pay for spell "
+ sa.getSourceCard() + " is spell? " + sa.isSpell() + " sa.canPlayAI()-"
+ sa.canPlayAI() + " sa.canPlay()-" + sa.canPlay()
+ " CardUtil.getConvertedManaCost(sa)-" + CardUtil.getConvertedManaCost(sa)
+ " ComputerUtil.getAvailableMana().size()-"
+ ComputerUtil.getAvailableMana().size());
}//list.size != 0
if(AllZone.Stack.size() == 0
&& AllZone.Phase.is(Constant.Phase.Main1, Constant.Player.Computer)) {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn2.running) = true; Note, this is untested, did it work?");
AllZone.Phase.setNeedToNextPhase(true);
}
}//if
}//synchronized
}//run()
};//Runnable
try {
SwingUtilities.invokeLater(run);
// Thread thread = new Thread(run);
// thread.start();
} catch(Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("ComputerAI_Burn : main1() error, " + ex);
}
}//main1()
public void main2() {
playLand = true;
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn2.main2) = true; Note, this is not tested, did it work?");
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_attackers_before()
{
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_attackers() {
final Combat c = ComputerUtil.getAttackers();
c.setAttackingPlayer(AllZone.Combat.getAttackingPlayer());
c.setDefendingPlayer(AllZone.Combat.getDefendingPlayer());
AllZone.Combat = c;
Card[] att = c.getAttackers();
for(int i = 0; i < att.length; i++)
att[i].tap();
AllZone.Computer_Play.updateObservers();
CombatUtil.showCombat();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn2.declare_attackers) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_blockers() {
Combat c = ComputerUtil.getBlockers();
c.setAttackingPlayer(AllZone.Combat.getAttackingPlayer());
c.setDefendingPlayer(AllZone.Combat.getDefendingPlayer());
AllZone.Combat = c;
CombatUtil.showCombat();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn2.declare_blockers) = true");
AllZone.Phase.setNeedToNextPhase(true);
//System.out.println(Arrays.asList(c.getAttackers()));
//System.out.println(Arrays.asList(c.getBlockers()));
}
public void declare_blockers_after() {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn2.declre_blockers_after) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
//end of Human's turn
public void end_of_turn() {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Burn2.end_of_turn) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
//must shuffle this
public Card[] getLibrary() {
CardFactory cf = AllZone.CardFactory;
CardList library = new CardList();
for(int i = 0; i < 4; i++) {
library.add(cf.getCard("Lightning Bolt", Constant.Player.Computer));
library.add(cf.getCard("Shock", Constant.Player.Computer));
library.add(cf.getCard("Steel Wall", Constant.Player.Computer));
}
for(int i = 0; i < 3; i++) {
library.add(cf.getCard("Char", Constant.Player.Computer));
library.add(cf.getCard("Shock", Constant.Player.Computer));
// library.add(cf.getCard("Nevinyrral's Disk", Constant.Player.Computer));
}
for(int i = 0; i < 2; i++) {
library.add(cf.getCard("Pyroclasm", Constant.Player.Computer));
// library.add(cf.getCard("Hidetsugu's Second Rite", Constant.Player.Computer));
// library.add(cf.getCard("Char", Constant.Player.Computer));
library.add(cf.getCard("Flamebreak", Constant.Player.Computer));
}
library.add(cf.getCard("Lava Spike", Constant.Player.Computer));
// library.add(cf.getCard("Tanglebloom", Constant.Player.Computer));
for(int i = 0; i < 17; i++)
library.add(cf.getCard("Mountain", Constant.Player.Computer));
if(library.size() != 40)
throw new RuntimeException("ComputerAI_Burn : getLibrary() error, library size is " + library.size());
return library.toArray();
}
public void stack_not_empty() {
//same as Input.stop() method
//ends the method
//different than methods because this isn't a phase like Main1 or Declare Attackers
AllZone.InputControl.resetInput();
AllZone.InputControl.updateObservers();
}
}

304
src/ComputerAI_General.java Normal file
View File

@@ -0,0 +1,304 @@
import static forge.error.ErrorViewer.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.TreeSet;
public class ComputerAI_General implements Computer {
private boolean playLand = true;
private Collection<Card> playMain1Cards;
@SuppressWarnings("unchecked")
// TreeSet type safety
public ComputerAI_General() {
//try to reduce the number of comparisons
playMain1Cards = new TreeSet(getMain1PlayHand());
}
public void main1() {
if(playLand) {
playLand = false;
ComputerUtil.playLand();
for(String effect:AllZone.StateBasedEffects.getStateBasedMap().keySet()) {
Command com = GameActionUtil.commands.get(effect);
com.execute();
}
GameActionUtil.executeCardStateEffects();
}
// AllZone.Phase.nextPhase();
playCards(Constant.Phase.Main1);
}//main1()
public void main2() {
playLand = true;
playCards(Constant.Phase.Main2);
}
private void playCards(final String phase) {
SpellAbility[] sp = phase.equals(Constant.Phase.Main1)? getMain1():getMain2();
boolean nextPhase = ComputerUtil.playCards(sp);
if(nextPhase) {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_General.playCards) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
}//playCards()
private ArrayList<String> getMain1PlayHand() {
ArrayList<String> play = new ArrayList<String>();
play.add("Man-o'-War");
play.add("Fire Imp");
play.add("Flametongue Kavu");
play.add("Briarhorn");
play.add("Inner-Flame Acolyte");
play.add("Keening Banshee");
play.add("Aggressive Urge");
play.add("Amnesia");
play.add("Angelic Blessing");
play.add("Ashes to Ashes");
play.add("Beacon of Destruction");
play.add("Blinding Light");
play.add("Brute Force");
play.add("Cackling Flames");
play.add("Char");
play.add("Control Magic");
play.add("Crib Swap");
play.add("Dark Banishing");
play.add("Devour in Shadow");
play.add("Do or Die");
play.add("Douse in Gloom");
play.add("Echoing Decay");
play.add("Echoing Truth");
play.add("Elvish Fury");
play.add("Epic Proportions");
play.add("Erratic Explosion");
play.add("Expunge");
play.add("Faceless Butcher");
play.add("Feral Lightning");
play.add("Firebolt");
play.add("Flamebreak");
play.add("Gaea's Anthem");
play.add("Giant Growth");
play.add("Glorious Anthem");
play.add("Hex");
play.add("Hidetsugu's Second Rite");
play.add("Hymn to Tourach");
play.add("Ichor Slick");
play.add("Infest");
play.add("Inspirit");
play.add("Kamahl, Pit Fighter");
play.add("Kjeldoran War Cry");
play.add("Lightning Bolt");
play.add("Might of Oaks");
play.add("Nameless Inversion");
play.add("Needle Storm");
play.add("Oblivion Ring");
play.add("Oubliette");
play.add("Path of Anger's Flame");
play.add("Peel from Reality");
play.add("Pestilence");
play.add("Plague Wind");
play.add("Pongify");
play.add("Primal Boost");
play.add("Psionic Blast");
play.add("Pyrohemia");
play.add("Repulse");
play.add("Saltblast");
play.add("Shock");
play.add("Shriekmaw");
play.add("Sower of Temptation");
play.add("Strangling Soot");
play.add("Sunlance");
play.add("Swords to Plowshares");
play.add("Take Possession");
play.add("Tendrils of Corruption");
play.add("Terror");
play.add("Threaten");
play.add("Tribal Flames");
play.add("Tromp the Domains");
play.add("Volcanic Hammer");
play.add("Wildsize");
play.add("Wings of Velis Vel");
play.add("Wit's End");
play.add("Wrap in Vigor");
return play;
}//getMain1PlayCards()
private SpellAbility[] getMain1() {
//Card list of all cards to consider
CardList hand = new CardList(AllZone.Computer_Hand.getCards());
hand = hand.filter(new CardListFilter() {
public boolean addCard(Card c) {
Collection<Card> play = playMain1Cards;
if(c.isLand()) return false;
if(play.contains(c.getName()) || (c.isCreature() && c.getKeyword().contains("Haste"))) return true;
return false;
}
});
CardList all = new CardList();
all.addAll(hand.toArray());
all.addAll(AllZone.Computer_Play.getCards());
return getPlayable(all);
}//getMain1()
private SpellAbility[] getMain2() {
//Card list of all cards to consider
CardList all = new CardList();
all.addAll(AllZone.Computer_Hand.getCards());
all.addAll(AllZone.Computer_Play.getCards());
all.addAll(CardFactoryUtil.getFlashbackCards(Constant.Player.Computer).toArray());
all = all.filter(new CardListFilter() {
public boolean addCard(Card c) {
if(c.isLand()) return false;
return true;
}
});
return getPlayable(all);
}//getMain2()
/**
* Returns the spellAbilities from the card list that the computer is able to play
*/
private SpellAbility[] getPlayable(CardList l) {
ArrayList<SpellAbility> spellAbility = new ArrayList<SpellAbility>();
for(Card c:l)
for(SpellAbility sa:c.getSpellAbility())
//This try/catch should fix the "computer is thinking" bug
try {
if(sa.canPlayAI() && ComputerUtil.canPayCost(sa)) spellAbility.add(sa);
} catch(Exception ex) {
showError(ex, "There is an error in the card code for %s:%n", c.getName(), ex.getMessage());
}
return spellAbility.toArray(new SpellAbility[spellAbility.size()]);
}
public void declare_attackers_before()
{
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_attackers() {
final Combat c = ComputerUtil.getAttackers();
c.setAttackingPlayer(AllZone.Combat.getAttackingPlayer());
c.setDefendingPlayer(AllZone.Combat.getDefendingPlayer());
//check for planeswalker
Card walker = AllZone.GameAction.getPlaneswalker(Constant.Player.Human);
if(walker != null && MyRandom.random.nextBoolean()) {
c.setPlaneswalker(walker);
AllZone.pwCombat = c;
} else AllZone.Combat = c;
Card[] att = c.getAttackers();
for(int i = 0; i < att.length; i++) {
if(!att[i].getKeyword().contains("Vigilance")) att[i].tap();
System.out.println("Computer just assigned " + att[i].getName() + " as an attacker.");
}
AllZone.Computer_Play.updateObservers();
CombatUtil.showCombat();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_General.declare_attackers) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_blockers() {
CardList blockers = new CardList(AllZone.Computer_Play.getCards());
Combat combat = getCombat(AllZone.pwCombat.getAttackers(), blockers);
combat.setPlaneswalker(AllZone.pwCombat.getPlaneswalker());
AllZone.pwCombat = combat;
CardList remove = AllZone.pwCombat.getAllBlockers();
for(int i = 0; i < remove.size(); i++)
blockers.remove(remove.get(i));
AllZone.Combat = getCombat(AllZone.Combat.getAttackers(), blockers);
CombatUtil.showCombat();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_General) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
private Combat getCombat(Card[] attackers, CardList availableBlockers) {
ComputerUtil_Block2 com = new ComputerUtil_Block2(attackers, availableBlockers.toArray(),
AllZone.Computer_Life.getLife());
Combat c = com.getBlockers();
c.setAttackingPlayer(AllZone.Combat.getAttackingPlayer());
c.setDefendingPlayer(AllZone.Combat.getDefendingPlayer());
return c;
}
public void declare_blockers_after() {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_General) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
//end of Human's turn
public void end_of_turn() {
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_General.end_of_turn) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
//must shuffle this
public Card[] getLibrary() {
//CardFactory cf = AllZone.CardFactory;
CardList library = new CardList();
/*
for(int i = 0; i < 10; i++)
{
library.add(cf.getCard("Kodama's Reach", Constant.Player.Computer));
library.add(cf.getCard("Forest", Constant.Player.Computer));
}
*/
return library.toArray();
}
public void stack_not_empty() {
//same as Input.stop() method
//ends the method
//different than methods because this isn't a phase like Main1 or Declare Attackers
// ComputerUtil.playCards(); this allows computer to play sorceries when it shouldn't
AllZone.InputControl.resetInput();
AllZone.InputControl.updateObservers();
}
}

83
src/ComputerAI_Input.java Normal file
View File

@@ -0,0 +1,83 @@
public class ComputerAI_Input extends Input
{
private static final long serialVersionUID = -3091338639571662216L;
private final Computer computer;
public ComputerAI_Input(Computer i_computer)
{
computer = i_computer;
}
//wrapper method that ComputerAI_StackNotEmpty class calls
//ad-hoc way for ComptuerAI_StackNotEmpty to get to the Computer class
public void stackNotEmpty()
{
computer.stack_not_empty();
}
public void showMessage()
{
ButtonUtil.disableAll();
AllZone.Display.showMessage("Phase: " +AllZone.Phase.getPhase() +"\nComputer is thinking");
think();
}//getMessage();
private void think()
{
final String phase = AllZone.Phase.getPhase();
if(phase.equals(Constant.Phase.Main1))
{
computer.main1();
}
else if (phase.equals(Constant.Phase.Combat_Declare_Attackers_InstantAbility))
{
computer.declare_attackers_before();
}
else if(phase.equals(Constant.Phase.Combat_Declare_Attackers))
{
computer.declare_attackers();
}
else if(phase.equals(Constant.Phase.Combat_Declare_Blockers_InstantAbility))
{
computer.declare_blockers_after();
}
else if(phase.equals(Constant.Phase.Main2))
{
computer.main2();
}
else if(phase.equals(Constant.Phase.At_End_Of_Turn))
{
AllZone.EndOfTurn.executeAt();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Input) = true");
AllZone.Phase.setNeedToNextPhase(true);
//Do not updateObservers here, do it in nextPhase
//AllZone.InputControl.updateObservers();
}
else if(phase.equals(Constant.Phase.Until_End_Of_Turn))
{
AllZone.EndOfTurn.executeUntil();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Input.think(),phase.equals(Until_End_Of_Turn) = true");
AllZone.Phase.setNeedToNextPhase(true);
//do not updateObservers() here! Do it in nextPhase().
//AllZone.InputControl.updateObservers();
}
//takes place during the human's turn, like blocking etc...
else if(phase.equals(Constant.Phase.Combat_Declare_Blockers))
{
computer.declare_blockers();
}
else if(phase.equals(Constant.Phase.End_Of_Turn))
{
computer.end_of_turn();
}
}//think
}

140
src/ComputerAI_Rats2.java Normal file
View File

@@ -0,0 +1,140 @@
import java.util.*;
public class ComputerAI_Rats2 implements Computer
{
private boolean playLand = true;
private static Random random = new Random();
public void main1()
{
if(playLand)
{
playLand = false;
ComputerUtil.playLand();
}
// if(playActivatedAbilities() || playSorcery())
// return;
Card[] c = AllZone.Computer_Hand.getCards();
System.out.println("Computer Thinking " +new CardList(c));
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Rats2.main1) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void main2()
{
playLand = true;
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Rats2.main2) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_blockers()
{
if(random.nextBoolean() || AllZone.Computer_Life.getLife() < 10)
{
//presumes all creatures the Computer owns are the same size, because they are Relentless Rats
Card block[] = CardUtil.toCard(PlayerZoneUtil.getUntappedCreatures(AllZone.Computer_Play));
Card att[] = AllZone.Combat.getAttackers();
int blockIndex = 0;
for(int i = 0; i < att.length && blockIndex < block.length; i++)
{
if(att[i].getNetDefense() <= block[blockIndex].getNetAttack() &&
CombatUtil.canBlock(att[i], block[blockIndex]))
AllZone.Combat.addBlocker(att[i], block[blockIndex++]);
}
}
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Computer_AI_Rats2.declare_blockers) = true");
AllZone.Phase.setNeedToNextPhase(true);
}//declare_blockers()
public void declare_attackers_before()
{
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_attackers()
{
Card[] a = CardUtil.toCard(PlayerZoneUtil.getUntappedCreatures(AllZone.Computer_Play));
Card[] b = CardUtil.toCard(PlayerZoneUtil.getUntappedCreatures(AllZone.Human_Play));
//for(int i = 0; i <a.length; i++)
// System.out.println(a[i].getAttack());
if(b.length == 0)
{
Card[] att = a;
for(int i = 0; i < att.length; i++)
{
att[i].tap();
AllZone.Combat.addAttacker(att[i]);
}
}
else if(a.length != 0)
{
MoveAttack m = new MoveAttack(a, b, AllZone.Computer_Life.getLife(), AllZone.Human_Life.getLife());
m.max(m, 2, true);
Card[] att = m.getBestMove().getAttackers().toArray();
for(int i = 0; i < att.length; i++)
{
att[i].tap();
AllZone.Combat.addAttacker(att[i]);
}
}
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Rats2.declare_attackers) = true");
AllZone.Phase.setNeedToNextPhase(true);
}//declare_attackers()
public Card[] getLibrary()
{
ArrayList<Card> a = new ArrayList<Card>();
CardFactory cf = AllZone.CardFactory;
//computer library
for(int i = 0; i < 18; i++)
a.add(cf.getCard("Swamp", Constant.Player.Computer));
// for(int i = 0; i < 3; i++)
// a.add(cf.getCard("Steel Wall", Constant.Player.Computer));
for(int i = 0; i < 0;i ++)
{
a.add(cf.getCard("Nantuko Shade", Constant.Player.Computer));
a.add(cf.getCard("Hymn to Tourach", Constant.Player.Computer));
}
for(int i = 0; i < 2;i ++)
{
a.add(cf.getCard("Royal Assassin", Constant.Player.Computer));
}
while(a.size() < 40)
a.add(cf.getCard("Relentless Rats", Constant.Player.Computer));
return CardUtil.toCard(a);
}//getLibrary()
public void declare_blockers_after(){playInstantAndAbilities();}
public void end_of_turn() {playInstantAndAbilities();}
private void playInstantAndAbilities()
{
// if(playActivatedAbilities())
// return;
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Rats2.playInstantAndAbilities) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void stack_not_empty()
{
AllZone.InputControl.resetInput();
AllZone.InputControl.updateObservers();
}
}

View File

@@ -0,0 +1,10 @@
public class ComputerAI_StackNotEmpty extends Input
{
private static final long serialVersionUID = -3995969852275185353L;
public void showMessage()
{
AllZone.Display.showMessage("Phase: " +AllZone.Phase.getPhase() +"\nComputer is thinking");
AllZone.Computer.stackNotEmpty();
}
}

View File

@@ -0,0 +1,59 @@
public class ComputerAI_Testing implements Computer
{
//must shuffle this
public Card[] getLibrary() {return new Card[] {};}
public void stack_not_empty()
{
System.out.println("Computer: not empty");
//same as Input.stop() method
//ends the method
//different than methods because this isn't a phase like Main1 or Declare Attackers
AllZone.InputControl.resetInput();
AllZone.InputControl.updateObservers();
}
public void main1() {AllZone.Phase.nextPhase();}
public void declare_attackers_before()
{
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_attackers(){
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Testing.declare_attackers) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void declare_blockers(){
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Testing.declare_blockers) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
//can play Instants and Abilities
public void declare_blockers_after(){
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Testing.declare_blockers_after) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void main2(){
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Testing.main2) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
//end of Human's turn
public void end_of_turn(){
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(ComputerAI_Testing.end_of_turn) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
}

View File

@@ -0,0 +1,117 @@
public class ComputerAI_counterSpells {
public static void counter_Spell(SpellAbility sa)
{
if (sa.getSourceCard().isCreature())
counter_CreatureSpell(sa);
else
counter_NonCreatureSpell(sa);
}
public static void counter_CreatureSpell(SpellAbility sa)
{
if (!hasPlayableCounterSpells() && !hasPlayableCreatureCounterSpells())
return;
CardList counterSpells = new CardList();
if (hasPlayableCreatureCounterSpells())
counterSpells = getPlayableCreatureCounterSpells();
else
counterSpells = getPlayableCounterSpells();
boolean countered = false;
for (Card var:counterSpells)
{
if (countered)
break;
else if (CardUtil.getConvertedManaCost(var.getManaCost()) <= CardUtil.getConvertedManaCost(sa) ||
(var.getName().equals("Overwhelming Intellect") && CardUtil.getConvertedManaCost(sa) >= 3 ))
{
SpellAbility sp = var.getSpellAbility()[0];
//ComputerUtil.playNoStack(sp);
ComputerUtil.playStack(sp);
countered = true;
}
}
}
public static void counter_NonCreatureSpell(SpellAbility sa)
{
if (!hasPlayableCounterSpells())
return;
CardList counterSpells = new CardList();
counterSpells = getPlayableCounterSpells();
boolean countered = false;
for (Card var:counterSpells)
{
if (countered)
break;
else if (CardUtil.getConvertedManaCost(var.getManaCost()) <= CardUtil.getConvertedManaCost(sa))
{
SpellAbility sp = var.getSpellAbility()[0];
//ComputerUtil.playNoStack(sp);
ComputerUtil.playStack(sp);
countered = true;
}
}
}
public static boolean hasPlayableCounterSpells()
{
return getPlayableCounterSpells().size() > 0;
}
public static boolean hasPlayableCreatureCounterSpells()
{
return getPlayableCreatureCounterSpells().size() > 0;
}
public static CardList getPlayableCounterSpells()
{
PlayerZone hand = AllZone.getZone(Constant.Zone.Hand, Constant.Player.Computer);
CardList list = new CardList(hand.getCards());
list = list.filter(new CardListFilter()
{
public boolean addCard(Card c) {
if (c.getSpellAbility().length == 0)
return false;
SpellAbility sa = c.getSpellAbility()[0];
return c.getName().equals("Counterspell") || c.getName().equals("Cancel") ||
c.getName().equals("Remand") || c.getName().equals("Mystic Snake") ||
c.getName().equals("Absorb") || c.getName().equals("Undermine") ||
c.getName().equals("Punish Ignorance") || c.getName().equals("Dismiss") ||
c.getName().equals("Last Word")
&& ComputerUtil.canPayCost(sa);
}
});
return list;
}
public static CardList getPlayableCreatureCounterSpells()
{
PlayerZone hand = AllZone.getZone(Constant.Zone.Hand, Constant.Player.Computer);
CardList list = new CardList(hand.getCards());
list = list.filter(new CardListFilter()
{
public boolean addCard(Card c) {
if (c.getSpellAbility().length == 0)
return false;
SpellAbility sa = c.getSpellAbility()[0];
return c.getName().equals("Exclude") || c.getName().equals("Overwhelming Intellect") ||
c.getName().equals("Preemptive Strike") || c.getName().equals("False Summoning") ||
c.getName().equals("Essence Scatter") || c.getName().equals("Remove Soul")
&& ComputerUtil.canPayCost(sa);
}
});
return list;
}
}

382
src/ComputerUtil.java Normal file
View File

@@ -0,0 +1,382 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
//import java.util.HashMap;
//import java.util.Map;
import java.util.Random;
public class ComputerUtil
{
@SuppressWarnings("unused") // random
private static Random random = new Random();
//if return true, go to next phase
static public boolean playCards()
{
return playCards(getSpellAbility());
}
//if return true, go to next phase
static public boolean playCards(SpellAbility[] all)
{
//not sure "playing biggest spell" matters?
sortSpellAbilityByCost(all);
// MyRandom.shuffle(all);
for(int i = 0; i < all.length; i++)
{
if(canPayCost(all[i]) && all[i].canPlay() && all[i].canPlayAI())
{
if(all[i].isSpell() && AllZone.GameAction.isCardInZone(all[i].getSourceCard(),AllZone.Computer_Hand))
AllZone.Computer_Hand.remove(all[i].getSourceCard());
if(all[i] instanceof Ability_Tap)
all[i].getSourceCard().tap();
payManaCost(all[i]);
all[i].chooseTargetAI();
AllZone.Stack.add(all[i]);
return false;
}
}//while
return true;
}//playCards()
//this is used for AI's counterspells
final static public void playStack(SpellAbility sa)
{
if (canPayCost(sa))
{
if (AllZone.GameAction.isCardInZone(sa.getSourceCard(),AllZone.Computer_Hand))
AllZone.Computer_Hand.remove(sa.getSourceCard());
if (sa.getSourceCard().getKeyword().contains("Cantrip"))
AllZone.GameAction.drawCard(sa.getSourceCard().getController());
payManaCost(sa);
AllZone.Stack.add(sa);
}
}
final static public void playNoStack(SpellAbility sa)
{
if(canPayCost(sa))
{
if(sa.isSpell())
{
if (AllZone.GameAction.isCardInZone(sa.getSourceCard(),AllZone.Computer_Hand))
AllZone.Computer_Hand.remove(sa.getSourceCard());
//probably doesn't really matter anyways
//sa.getSourceCard().comesIntoPlay(); - messes things up, maybe for the future fix this
}
if(sa instanceof Ability_Tap)
sa.getSourceCard().tap();
if (sa.getSourceCard().getKeyword().contains("Cantrip"))
AllZone.GameAction.drawCard(sa.getSourceCard().getController());
payManaCost(sa);
sa.resolve();
//destroys creatures if they have lethal damage, etc..
AllZone.GameAction.checkStateEffects();
}
}//play()
//gets Spell's of cards in hand and Abilities of cards in play
//checks to see
//1. if canPlay() returns true, 2. can pay for mana
static public SpellAbility[] getSpellAbility()
{
CardList all = new CardList();
all.addAll(AllZone.Computer_Play.getCards());
all.addAll(AllZone.Computer_Hand.getCards());
all.addAll(CardFactoryUtil.getFlashbackCards(Constant.Player.Computer).toArray());
all = all.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
if(c.isBasicLand())
return false;
return true;
}
});
ArrayList<SpellAbility> spellAbility = new ArrayList<SpellAbility>();
for(int outer = 0; outer < all.size(); outer++)
{
SpellAbility[] sa = all.get(outer).getSpellAbility();
for(int i = 0; i < sa.length; i++)
if(sa[i].canPlayAI() && canPayCost(sa[i]) /*&& sa[i].canPlay()*/)
spellAbility.add(sa[i]);//this seems like it needs to be copied, not sure though
}
SpellAbility[] sa = new SpellAbility[spellAbility.size()];
spellAbility.toArray(sa);
return sa;
}
static public boolean canPlay(SpellAbility sa)
{
return sa.canPlayAI() && canPayCost(sa);
}
static public boolean canPayCost(SpellAbility sa)
{
if(sa.getManaCost().equals(("0")))
return true;
CardList land = getAvailableMana();
if(sa.getSourceCard().isLand() /*&& sa.isTapAbility()*/)
{
land.remove(sa.getSourceCard());
}
ManaCost cost = new ManaCost(sa.getManaCost());
ArrayList<String> colors = new ArrayList<String>();
for(int i = 0; i < land.size(); i++)
{
colors = getColors(land.get(i));
int once = 0;
for(int j =0; j < colors.size(); j++)
{
if(cost.isNeeded(colors.get(j)) && once == 0)
{
//System.out.println(j + " color:" +colors.get(j));
cost.subtractMana(colors.get(j));
System.out.println("thinking, I just subtracted " + colors.get(j) + ", cost is now: " + cost.toString());
once++;
}
if(cost.isPaid()) {
//System.out.println("Cost is paid.");
return true;
}
}
}
return false;
}//canPayCost()
static public void payManaCost(SpellAbility sa)
{
if(sa.getManaCost().equals(("0")))
return;
CardList land = getAvailableMana();
//this is to prevent errors for land cards that have abilities that cost mana.
if(sa.getSourceCard().isLand() /*&& sa.isTapAbility()*/)
{
land.remove(sa.getSourceCard());
}
ManaCost cost = new ManaCost(sa.getManaCost());
ArrayList<String> colors = new ArrayList<String>();
for(int i = 0; i < land.size(); i++)
{
colors = getColors(land.get(i));
for(int j = 0; j <colors.size();j++)
{
if(cost.isNeeded(colors.get(j)) && land.get(i).isUntapped())
{
land.get(i).tap();
cost.subtractMana(colors.get(j));
System.out.println("just subtracted " + colors.get(j) + ", cost is now: " + cost.toString());
}
if(cost.isPaid())
break;
}
}
if(! cost.isPaid())
throw new RuntimeException("ComputerUtil : payManaCost() cost was not paid for " + sa.getSourceCard().getName());
}//payManaCost()
//get the color that the land could produce
//Swamps produce Black
/* unused
public static String getColor(Card land)
{
Map<String,String> map = new HashMap<String,String>();
map.put("tap: add B", Constant.Color.Black);
map.put("tap: add W", Constant.Color.White);
map.put("tap: add G", Constant.Color.Green);
map.put("tap: add R", Constant.Color.Red);
map.put("tap: add U", Constant.Color.Blue);
map.put("tap: add 1", Constant.Color.Colorless);
//this fails on Vine Trellis and probably 9th Pain Lands
try{
Object o = land.getKeyword().get(0);
return map.get(o).toString();
}catch(Exception ex)//I hope this fixes "the problem" that I can't re-create
{
return Constant.Color.Colorless;
}
}
*/
public static ArrayList<String> getColors(Card land)
{
ArrayList<String> colors = new ArrayList<String>();
if (land.getKeyword().contains("tap: add B"))
colors.add(Constant.Color.Black);
if (land.getKeyword().contains("tap: add W"))
colors.add(Constant.Color.White);
if (land.getKeyword().contains("tap: add G"))
colors.add(Constant.Color.Green);
if (land.getKeyword().contains("tap: add R"))
colors.add(Constant.Color.Red);
if (land.getKeyword().contains("tap: add U"))
colors.add(Constant.Color.Blue);
if (land.getKeyword().contains("tap: add 1"))
colors.add(Constant.Color.Colorless);
return colors;
}
/*
//only works with mono-colored spells
static public void payManaCost(int convertedCost)
{
CardList land = getAvailableMana();
//converted colered mana requirements into colorless
ManaCost cost = new ManaCost("" +convertedCost);
Card c;
for(int i = 0; i < land.size(); i++)
{
if(cost.isPaid())
break;
land.get(i).tap();
cost.subtractMana(Constant.Color.Red);
}//for
if(! cost.isPaid())
throw new RuntimeException("ComputerUtil : payManaCost() cost was not paid");
}//payManaCost()
*/
static public CardList getAvailableMana()
{
CardList list = new CardList(AllZone.Computer_Play.getCards());
CardList mana = list.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
//if(c.isCreature() && c.hasSickness())
// return false;
for (Ability_Mana am : c.getBasicMana())
if (am.canPlay()) return true;
return false;
}
});//CardListFilter
CardList sortedMana = new CardList();
for (int i=0; i<mana.size();i++)
{
Card card = mana.get(i);
if (card.isBasicLand()){
sortedMana.add(card);
mana.remove(card);
}
}
for (int j=0; j<mana.size();j++)
{
sortedMana.add(mana.get(j));
}
return sortedMana;
}//getAvailableMana()
//plays a land if one is available
static public void playLand()
{
ArrayList<Card> landList = PlayerZoneUtil.getCardType(AllZone.Computer_Hand, "Land");
if(! landList.isEmpty())
{
AllZone.Computer_Hand.remove(landList.get(0));
AllZone.Computer_Play.add(landList.get(0));
AllZone.GameAction.checkStateEffects();
}
}
static public void untapDraw()
{
AllZone.GameAction.drawCard(Constant.Player.Computer);
CardList permanent = new CardList(AllZone.Computer_Play.getCards());
for(int i = 0; i < permanent.size(); i++)
permanent.get(i).untap();
}
static public CardList getPossibleAttackers()
{
CardList list = new CardList(AllZone.Computer_Play.getCards());
list = list.filter(new CardListFilter()
{
public boolean addCard(Card c) {
return c.isCreature() && CombatUtil.canAttack(c);
}
});
return list;
}
static public Combat getAttackers()
{
ComputerUtil_Attack2 att = new ComputerUtil_Attack2(
AllZone.Computer_Play.getCards(),
AllZone.Human_Play.getCards() , AllZone.Human_Life.getLife());
return att.getAttackers();
}
static public Combat getBlockers()
{
ComputerUtil_Block2 block = new ComputerUtil_Block2(
AllZone.Combat.getAttackers() ,
AllZone.Computer_Play.getCards(), AllZone.Computer_Life.getLife());
return block.getBlockers();
}
@SuppressWarnings("unchecked") // Comparator needs type
static void sortSpellAbilityByCost(SpellAbility sa[])
{
//sort from highest cost to lowest
//we want the highest costs first
Comparator c = new Comparator()
{
public int compare(Object a, Object b)
{
int a1 = CardUtil.getConvertedManaCost((SpellAbility)a);
int b1 = CardUtil.getConvertedManaCost((SpellAbility)b);
//puts creatures in front of spells
if(((SpellAbility)a).getSourceCard().isCreature())
a1 += 1;
if(((SpellAbility)b).getSourceCard().isCreature())
b1 += 1;
return b1 - a1;
}
};//Comparator
Arrays.sort(sa, c);
}//sortSpellAbilityByCost()
}

View File

@@ -0,0 +1,358 @@
import java.util.*;
//doesHumanAttackAndWin() uses the global variable AllZone.Computer_Life
public class ComputerUtil_Attack2
{
//possible attackers and blockers
private CardList attackers;
private CardList blockers;
private int blockerLife;
private Random random = new Random();
private final int randomInt = random.nextInt();
private CardList humanList; //holds human player creatures
private CardList computerList;//holds computer creatures
public ComputerUtil_Attack2(Card[] possibleAttackers, Card[] possibleBlockers, int blockerLife)
{
this(new CardList(possibleAttackers), new CardList(possibleBlockers), blockerLife);
}
public ComputerUtil_Attack2(CardList possibleAttackers, CardList possibleBlockers, int blockerLife)
{
humanList = new CardList(possibleBlockers.toArray());
humanList = humanList.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return c.isCreature();
}
});
computerList = new CardList(possibleAttackers.toArray());
computerList = computerList.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return c.isCreature();
}
});
attackers = getUntappedCreatures(possibleAttackers, true);
blockers = getUntappedCreatures(possibleBlockers , false);
this.blockerLife = blockerLife;
final ArrayList<String> valuable = new ArrayList<String>();
valuable.add("Kamahl, Pit Fighter");
valuable.add("Elvish Piper");
attackers = attackers.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return (0 < getAttack(c) || c.getName().equals("Guiltfeeder")) && ! valuable.contains(c.getName());
}
});
}//constructor
public CardList getUntappedCreatures(CardList in, final boolean checkCanAttack)
{
CardList list = new CardList(in.toArray());
list = list.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
boolean b = c.isCreature() && c.isUntapped();
if(checkCanAttack)
return b && CombatUtil.canAttack(c);
return b;
}
});
return list;
}//getUntappedCreatures()
//this checks to make sure that the computer player
//doesn't lose when the human player attacks
//this method is used by getAttackers()
public int getStartIndex()
{
CardListUtil.sortAttack(humanList);
for(int i = 0; i < computerList.size(); i++)
if(!doesHumanAttackAndWin(i))
return i;
return computerList.size();
}
//this uses a global variable, which isn't perfect
public boolean doesHumanAttackAndWin(int nBlockingCreatures)
{
int totalAttack = 0;
int stop = humanList.size() - nBlockingCreatures;
for(int i = 0; i < stop; i++)
totalAttack += getAttack(humanList.get(i));
//-3 so the computer will try to stay at 3 life
return (AllZone.Computer_Life.getLife() - 3) <= totalAttack;
}
private boolean doAssault()
{
//I think this is right but the assault code may still be a little off
CardListUtil.sortAttackLowFirst(attackers);
int totalAttack = 0;
//presumes the Human will block
for(int i = 0; i < (attackers.size() - blockers.size()); i++)
totalAttack += getAttack(attackers.get(i));
return blockerLife <= totalAttack;
}//doAssault()
public Combat getAttackers()
{
//if this method is called multiple times during a turn,
//it will always return the same value
//randomInt is used so that the computer doesn't always
//do the same thing on turn 3 if he had the same creatures in play
//I know this is a little confusing
random.setSeed(AllZone.Phase.getTurn() + randomInt);
Combat combat = new Combat();
for (int i=0; i<attackers.size();i++)
{
if (attackers.get(i).getKeyword().contains("This card attacks each turn if able."))
combat.addAttacker(attackers.get(i));
}
if (combat.getAttackers().length == 0 && (countExaltedCreatures() >= 3 ||
GameActionUtil.isRafiqInPlay(Constant.Player.Computer) ||
GameActionUtil.getBattleGraceAngels(Constant.Player.Computer) >= 2) && !doAssault())
{
int biggest = 0;
Card att = null;
for(int i=0; i<attackers.size();i++){
if (getAttack(attackers.get(i)) > biggest) {
biggest = getAttack(attackers.get(i));
att = attackers.get(i);
}
}
if (att!= null)
combat.addAttacker(att);
}
//do assault (all creatures attack) if the computer would win the game
//or if the computer has 4 creatures and the player has 1
else if(doAssault() || (humanList.size() == 1 && 3 < attackers.size()))
{
for(int i = 0; i < attackers.size(); i++)
combat.addAttacker(attackers.get(i));
}
else
{
Card bigDef;
Card bigAtt;
//should the computer randomly not attack with one attacker?
//this should only happen 10% of the time when the computer
//has at least 3 creatures
boolean notAttack = (Math.abs(random.nextInt(100)) <= 10);
if(notAttack && 3 <= attackers.size())
{
attackers.shuffle();
attackers.remove(0);
}
//this has to be before the sorting below
//because this sorts attackers
int i = getStartIndex(); //new
//so the biggest creature will usually attack
//I think this works, not sure, may have to change it
//sortNonFlyingFirst has to be done first, because it reverses everything
CardListUtil.sortNonFlyingFirst(attackers);
CardListUtil.sortAttackLowFirst(attackers);
for(; i < attackers.size(); i++)
{
bigAtt = getBiggestAttack(attackers.get(i));
bigDef = getBiggestDefense(attackers.get(i));
/*
System.out.println("bigDef: " + bigDef.getName());
System.out.println("attackers.get(i): " + attackers.get(i).getName());
if (CombatUtil.canDestroyBlocker(bigDef, attackers.get(i)))
System.out.println(attackers.get(i).getName() + " can destroy blocker " +bigDef.getName());
*/
//if attacker can destroy biggest blocker or
//biggest blocker cannot destroy attacker
if(CombatUtil.canDestroyBlocker(bigDef, attackers.get(i)) ||
(! CombatUtil.canDestroyAttacker(attackers.get(i), bigAtt))){
combat.addAttacker(attackers.get(i));
}
else if(attackers.get(i).getSacrificeAtEOT()){
combat.addAttacker(attackers.get(i));
}
}
}//getAttackers()
return combat;
}//getAttackers()
//returns 0/1 Card if no blockers found
public Card getBiggestAttack(Card attack)
{
CardListUtil.sortAttack(blockers);
for(int i = 0; i < blockers.size(); i++)
if(CombatUtil.canBlock(attack, blockers.get(i)))
return blockers.get(i);
return AllZone.CardFactory.getCard("Birds of Paradise", "");
}
//returns 1/1 Card if no blockers found
public Card getBiggestDefense(Card attack)
{
CardListUtil.sortDefense(blockers);
for(int i = 0; i < blockers.size(); i++)
if(CombatUtil.canBlock(attack, blockers.get(i)))
return blockers.get(i);
return AllZone.CardFactory.getCard("Elvish Piper", "");
}
public int countExaltedCreatures()
{
PlayerZone play = AllZone.getZone(Constant.Zone.Play, Constant.Player.Computer);
CardList list = new CardList();
list.addAll(play.getCards());
list = list.filter(new CardListFilter(){
public boolean addCard(Card c) {
return c.getKeyword().contains("Exalted");
}
});
return list.size();
}
public void assignDamage(CardList list, int damage)
{
CardListUtil.sortAttack(list);
int kill;
for(int i = 0; i < list.size(); i++)
{
kill = list.get(i).getKillDamage();
if(kill <= damage)
{
damage -= kill;
list.get(i).setAssignedDamage(kill);
}
}
}//assignDamage()
public int getAttack(Card c)
{
int n = c.getNetAttack();
if(CombatUtil.isDoranInPlay())
n = c.getNetDefense();
if(c.getKeyword().contains("Double Strike"))
n *= 2;
return n;
}
}
/*
//this returns the attacking power that is needed to destroy
//Card c and takes into account first and double strike
//
//Doran, the Siege Tower doesn't change a card's defense
//used by sortDefense()
private int getDefense(Card c)
{
int n = c.getNetDefense();
//is the defense is less than attack and the card has
//first or double strike?
if(hasStrike(c) && n < getAttack_FirstStrike(c))
n = getAttack_FirstStrike(c);
return n;
}
//does this card have first or double strike?
private boolean hasStrike(Card c)
{
return c.getKeyword.contains("First Strike") ||
c.getKeyword.contains("Double Strike")
}
//the higher the defense the better
@SuppressWarnings("unchecked") // Comparator needs <type>
private void sortDefense(CardList list)
{
Comparator com = new Comparator()
{
public int compare(Object a1, Object b1)
{
Card a = (Card)a1;
Card b = (Card)b1;
return getDefense(b) - getDefense(a);
}
};
list.sort(com);
}//sortDefense()
//use this method if you need to know about first strike
public int getAttack_FirstStrike(Card c)
{
int n = getAttack(c);
//adding 1 is a little bit hacky bit it shows
//that first strike is a little better
//than a average creature
if(c.getKeyword().contains("First Strike"))
n += 1;
return n;
}
//returns lowest attack first
private void sortAttackLowFirst(CardList list)
{
sortAttack(list);
list.reverse();
return list;
}
//the higher the attack the better
@SuppressWarnings("unchecked") // Comparator needs type
private void sortAttack(CardList list)
{
Comparator com = new Comparator()
{
public int compare(Object a1, Object b1)
{
Card a = (Card)a1;
Card b = (Card)b1;
return getAttack_FirstStrike(b) - getAttack_FirstStrike(a);
}
};
list.sort(com);
}//sortAttack()
*/

View File

@@ -0,0 +1,323 @@
import java.util.*;
public class ComputerUtil_Block2
{
private CardList attackers;
private CardList possibleBlockers;
private int blockersLife;
//making this static helped in testing
//random.nextBoolean() wasn't true 50% of the time
private static Random random = new Random();
private final int randomInt = random.nextInt();
public ComputerUtil_Block2(Card[] attackers, Card[] possibleBlockers, int blockerLife)
{
this(new CardList(attackers), new CardList(possibleBlockers), blockerLife);
}
public ComputerUtil_Block2(CardList in_attackers, CardList in_possibleBlockers, int in_blockersLife)
{
attackers = new CardList(in_attackers.toArray());
possibleBlockers = getUntappedCreatures(new CardList(in_possibleBlockers.toArray()));
//so the computer won't just have 1 life left
//the computer will try to stay at 3 life
blockersLife = in_blockersLife;
if(3 < blockersLife)
blockersLife -= 3;;
attackers.shuffle();
CardListUtil.sortAttackLowFirst(possibleBlockers);
possibleBlockers = removeValuableBlockers(possibleBlockers);
}
private CardList getUntappedCreatures(CardList list)
{
list = list.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return c.isCreature() && c.isUntapped();
}
});
return list;
}//getUntappedCreatures()
private CardList removeValuableBlockers(CardList in)
{
final String[] noBlock = {"Elvish Piper", "Urborg Syphon-Mage", "Sparksmith", "Royal Assassin", "Marble Titan", "Kamahl, Pit Fighter"};
CardList out = in.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
for(int i = 0; i < noBlock.length; i++)
if(c.getName().equals(noBlock[i]))
return false;
return true;
}
});//CardListFilter
return out;
}
//checks for flying and stuff like that
private CardList getPossibleBlockers(Card attacker)
{
CardList list = new CardList();
for(int i = 0; i < possibleBlockers.size(); i++)
if(CombatUtil.canBlock(attacker, possibleBlockers.get(i)))
list.add(possibleBlockers.get(i));
return list;
}
//finds a blocker that destroys the attacker, the blocker is not destroyed
//returns null if no blocker is found
Card safeSingleBlock(Card attacker)
{
CardList c = getPossibleBlockers(attacker);
for(int i = 0; i < c.size(); i++)
if(CombatUtil.canDestroyAttacker(attacker, c.get(i)) &&
(! CombatUtil.canDestroyBlocker(c.get(i), attacker)))
return c.get(i);
return null;
}//safeSingleBlock()
//finds a blocker, both the attacker and blocker are destroyed
//returns null if no blocker is found
Card tradeSingleBlock(Card attacker)
{
CardList c = getPossibleBlockers(attacker);
for(int i = 0; i < c.size(); i++)
if(CombatUtil.canDestroyAttacker(attacker, c.get(i)))
{
//do not block a non-flyer with a flyer
if((! c.get(i).getKeyword().contains("Flying")) || attacker.getKeyword().contains("Flying"))
return c.get(i);
}
return null;
}//tradeSingleBlock()
//finds a blocker, neither attacker and blocker are destroyed
//returns null if no blocker is found
Card shieldSingleBlock(Card attacker)
{
CardList c = getPossibleBlockers(attacker);
for(int i = 0; i < c.size(); i++)
if(! CombatUtil.canDestroyBlocker(c.get(i), attacker))
return c.get(i);
return null;
}//shieldSingleBlock()
//finds multiple blockers
//returns an array of size 0 if not multiple blocking
Card[] multipleBlock(Card attacker)
{
CardList c = getPossibleBlockers(attacker);
int defense = getDefense(attacker) - attacker.getDamage();
//if attacker cannot be destroyed
if(defense > CardListUtil.sumAttack(c))
return new Card[] {};
CardList block = new CardList();
c.shuffle();
while(defense > CardListUtil.sumAttack(block))
block.add(c.remove(0));
Card check[] = block.toArray();
//no single blockers, that should be handled somewhere else
if(check.length == 1)
return new Card[] {};
return check;
}//multipleBlock()
//finds a blocker, both the attacker lives and blockers dies
//returns null if no blocker is found
Card chumpSingleBlock(Card attacker)
{
if(blockersLife <= CardListUtil.sumAttack(attackers))
{
CardList c = getPossibleBlockers(attacker);
CardListUtil.sortAttackLowFirst(c);
if(! c.isEmpty())
return c.get(0);
}
return null;
}//tradeSingleBlock()
//force block if lethal damage somehow slips through checks (happens often with doublestrike)
Card forceBlock(Card attacker)
{
CardList c = getPossibleBlockers(attacker);
CardListUtil.sortAttackLowFirst(c);
if(! c.isEmpty())
return c.get(0);
return null;
}
private void testing(String s)
{
boolean print = false;
if(print)
System.out.println("combat testing: " +s);
}
private int sumUnblockedAttackers(Combat combat)
{
int sum = 0;
Card c[] = combat.getAttackers();
for(int i = 0; i < c.length; i++)
if(! combat.isBlocked(c[i]))
sum += getAttack(c[i]);
return sum;
}
public Combat getBlockers()
{
//if this method is called multiple times during a turn,
//it will always return the same value
//randomInt is used so that the computer doesn't always
//do the same thing on turn 3 if he had the same creatures in play
//I know this is a little confusing
random.setSeed(AllZone.Phase.getTurn() + randomInt);
Card c;
Combat combat = new Combat();
boolean shouldBlock;
//if this isn't done, the attackers are shown backwards 3,2,1,
//reverse the order here because below reverses the order again
attackers.reverse();
//add attackers to combat
//this has to be done before the code below because sumUnblockedAttackers()
//uses combat to get the attackers and total their power
for(int i = 0; i < attackers.size(); i++)
combat.addAttacker(attackers.get(i));
for(int i = 0; i < attackers.size(); i++)
{
boolean doubleStrike = false;
if(attackers.get(i).hasDoubleStrike() || attackers.get(i).getKeyword().contains("Double Strike"))
doubleStrike = true;
//the computer blocks 50% of the time or if the computer would lose the game
shouldBlock = random.nextBoolean() || blockersLife <= sumUnblockedAttackers(combat);
testing("shouldBlock - " +shouldBlock);
c = null;
//safe block - attacker dies, blocker lives
//if there is only one attacker it might be a trap
//if holding a Giant Growth and a 2/2 attacking into a 3/3
if(shouldBlock)
{
c = safeSingleBlock(attackers.get(i));
if(c != null)
testing("safe");
}
if(c == null && shouldBlock)
{
//shield block - attacker lives, blocker lives
c = shieldSingleBlock(attackers.get(i));
if(c != null)
testing("shield");
}
if(c == null && shouldBlock)
{
//trade block - attacker dies, blocker dies
c = tradeSingleBlock(attackers.get(i));
if(c != null)
testing("trading");
}
if(c == null && shouldBlock)
{
//chump block - attacker lives, blocker dies
c = chumpSingleBlock(attackers.get(i));
if(c != null)
testing("chumping");
}
if(c == null && doubleStrike && AllZone.Computer_Life.getLife() <= (getAttack(attackers.get(i))*2))
{
c = forceBlock(attackers.get(i));
if (c != null)
testing("forcing");
}
if(c != null)
{
//if (!c.getKeyword().contains("This card can block any number of creatures."))
possibleBlockers.remove(c);
combat.addBlocker(attackers.get(i), c);
}
//multiple blockers
if(c == null && shouldBlock)
{
Card[] m = multipleBlock(attackers.get(i));
for(int inner = 0; inner < m.length; inner++)
{
//to prevent a single flyer from blocking a single non-flyer
//tradeSingleBlock() checks for a flyer blocking a non-flyer also
if(m.length != 1)
{
possibleBlockers.remove(m[inner]);
combat.addBlocker(attackers.get(i), m[inner]);
}
}//for
}//if
}//for attackers
return combat;
}//getBlockers()
//Doran, the Siege Tower doesn't change a card's defense
public int getDefense(Card c)
{
return c.getNetDefense();
}
//this doesn't take into account first strike,
//use CombatUtil.canDestroyAttacker()
public int getAttack(Card c)
{
int n = c.getNetAttack();
if(CombatUtil.isDoranInPlay())
n = c.getNetDefense();
if(c.getKeyword().contains("Double Strike"))
n *= 2;
return n;
}
}

23
src/Computer_Cleanup.java Normal file
View File

@@ -0,0 +1,23 @@
import java.util.Random;
public class Computer_Cleanup extends Input
{
private static final long serialVersionUID = -145924458598185438L;
public void showMessage()
{
Random r = new Random();
Card[] c = AllZone.Computer_Hand.getCards();
while(7 < c.length)
{
AllZone.GameAction.discard(c[r.nextInt(c.length)]);
c = AllZone.Computer_Hand.getCards();
}
CombatUtil.removeAllDamage();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Computer_Cleanup.showMessage()) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
}

13
src/Computer_Draw.java Normal file
View File

@@ -0,0 +1,13 @@
public class Computer_Draw extends Input
{
private static final long serialVersionUID = -815953053902719496L;
public void showMessage()
{
AllZone.GameAction.drawCard(Constant.Player.Computer);
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Computer_Draw.showMessage) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
}

162
src/Computer_Race.java Normal file
View File

@@ -0,0 +1,162 @@
public class Computer_Race
{
public boolean willWinRace(CardList attackList, int attackLife, CardList blockList, int blockLife)
{
return true;
}//willWinRace()
//if all of attackList attacked, and blockList goodBlocked(),
//what attackers would still be attacking?
public CardList getUnblocked(CardList attackList, CardList blockList)
{
//copy
attackList = new CardList(attackList.toArray());
blockList = new CardList(blockList.toArray());
//need to match smallest blocker with biggest attacker
CardListUtil.sortAttack(attackList);
CardListUtil.sortAttackLowFirst(blockList);
CardList unblocked = new CardList();
for(int i = 0; i < attackList.size(); i++)
{
Card attack = attackList.get(i);
CardList block = getPossibleBlockers(attack, blockList);
CardList check = goodBlock(attack, block);
if(check == null)
unblocked.add(attack);
else
for(int z = 0; z < check.size(); z++)
blockList.remove(check.get(z));
}
return unblocked;
}//getUnblocked()
//may return null
//null means there are no good blockers in blockList
//check for the 3 criteria below
//(attacker live and blocker live)
//(attacker die and blocker live)
//(attacker die and blocker die)
public CardList goodBlock(Card attacker, CardList blockList)
{
Card c;
CardList check;
c = safeSingleBlock(attacker, blockList);
check = checkGoodBlock(c);
if(check != null)
return check;
c = shieldSingleBlock(attacker, blockList);
check = checkGoodBlock(c);
if(check != null)
return check;
c = tradeSingleBlock(attacker, blockList);
check = checkGoodBlock(c);
if(check != null)
return check;
Card[] m = this.multipleBlock(attacker, blockList);
if(m.length != 0)
return new CardList(m);
return null;
}
//goodBlock() uses this method
public CardList checkGoodBlock(Card c)
{
if(c != null)
{
CardList list = new CardList();
list.add(c);
return list;
}
return null;
}//checkGoodBlock()
//(attacker dies, blocker lives)
//returns null if no blocker is found
Card safeSingleBlock(Card attacker, CardList blockList)
{
CardList c = blockList;
for(int i = 0; i < c.size(); i++)
if(CombatUtil.canDestroyAttacker(attacker, c.get(i)) &&
(! CombatUtil.canDestroyBlocker(c.get(i), attacker)))
return c.get(i);
return null;
}//safeSingleBlock()
//(attacker dies, blocker dies)
//returns null if no blocker is found
Card tradeSingleBlock(Card attacker, CardList blockList)
{
CardList c = blockList;
for(int i = 0; i < c.size(); i++)
if(CombatUtil.canDestroyAttacker(attacker, c.get(i)))
return c.get(i);
return null;
}//tradeSingleBlock()
//(attacker lives, blocker lives)
//returns null if no blocker is found
Card shieldSingleBlock(Card attacker, CardList blockList)
{
CardList c = blockList;
for(int i = 0; i < c.size(); i++)
if(! CombatUtil.canDestroyBlocker(c.get(i), attacker))
return c.get(i);
return null;
}//shieldSingleBlock()
//finds multiple blockers
//returns an array of size 0 if not multiple blocking
Card[] multipleBlock(Card attacker, CardList blockList)
{
CardList c = blockList;
int defense = attacker.getNetDefense() - attacker.getDamage();
//if attacker cannot be destroyed
if(defense > CardListUtil.sumAttack(c))
return new Card[] {};
CardList block = new CardList();
c.shuffle();
while(defense > CardListUtil.sumAttack(block))
block.add(c.remove(0));
Card check[] = block.toArray();
//no single blockers, that should be handled somewhere else
if(check.length == 1)
return new Card[] {};
return check;
}//multipleBlock()
//checks for flying and stuff like that
private CardList getPossibleBlockers(Card attacker, CardList blockList)
{
CardList list = new CardList();
for(int i = 0; i < blockList.size(); i++)
if(CombatUtil.canBlock(attacker, blockList.get(i)))
list.add(blockList.get(i));
return list;
}
}

179
src/Constant.java Normal file
View File

@@ -0,0 +1,179 @@
import javax.swing.ImageIcon;
public interface Constant
{
public static final String ProgramName = "MTG Forge - 10/2009 - http://mtgrares.blogspot.com";
//used to pass information between the GUI screens
public interface Runtime
{
public static final Deck[] HumanDeck = new Deck[1];
public static final Deck[] ComputerDeck = new Deck[1];
public static final String[] GameType = new String[1];
public static final WinLose WinLose = new WinLose();
public static final boolean[] smooth = new boolean[1];
public static final int[] width = new int[1];
public static final int[] height = new int[1];
}
public interface GameType
{
public static final String Constructed = "constructed";
public static final String Sealed = "sealed";
public static final String Draft = "draft";
}
public interface IO
{
//TODO: probably should read this from a file, or set from GUI
// public static final String baseDir = "c:\\Tim\\game testing\\";
public static final String deckFile = "all-decks2";
public static final String boosterDeckFile = "booster-decks";
public static final String imageBaseDir = "pics";
public static final String cardFile = "cards.txt";
public static final ImageIcon upIcon = new ImageIcon ("up.gif");
public static final ImageIcon downIcon = new ImageIcon ("down.gif");
public static final ImageIcon leftIcon = new ImageIcon ("left.gif");
public static final ImageIcon rightIcon = new ImageIcon("right.gif");
}
public interface Ability
{
public static final String Triggered = "Triggered";
public static final String Activated = "Activated";
}
public interface Phase
{
public static final String Untap = "Untap";
public static final String Upkeep = "Upkeep";
public static final String Draw = "Draw";
public static final String Main1 = "Main1";
//public static final String Begin_Combat = "Beginning of Combat";
public static final String Combat_Before_Declare_Attackers_InstantAbility = "Before Attack Phase - Play Instants and Abilities";
public static final String Combat_Declare_Attackers_InstantAbility = "Declare Attackers - Play Instants and Abilities";
public static final String Combat_Declare_Attackers = "Declare Attackers";
public static final String Combat_Declare_Blockers = "Declare Blockers";
public static final String Combat_Declare_Blockers_InstantAbility = "Declare Blockers - Play Instants and Abilities";
public static final String Combat_Damage = "Combat Damage";
public static final String Combat_FirstStrikeDamage = "First Strike Damage";
//public static final String End_Combat = "End of Combat";
public static final String Main2 = "Main2";
public static final String At_End_Of_Turn = "At End of Turn";
public static final String End_Of_Turn = "End of Turn";
public static final String Until_End_Of_Turn = "Until End of Turn";
public static final String Cleanup = "Cleanup";
}
public interface Zone
{
public static final String Hand = "Hand";
public static final String Library = "Library";
public static final String Graveyard = "Graveyard";
public static final String Play = "Play";
public static final String Removed_From_Play = "Removed from play";
//public static final String Stack = "Stack";
}
public interface Player
{
public static final String Human = "Human";
public static final String Computer = "Computer";
}
/*
public interface CardType
{
public static final String Artifact = "Artifact";
public static final String Creature = "Creature";
public static final String Enchantment = "Enchantment";
public static final String Aura = "Aura";
public static final String Instant = "Instant";
public static final String Land = "Land";
public static final String Legendary = "Legendary";
public static final String Sorcery = "Sorcery";
public static final String Basic = "Basic";
}
*/
public interface Color
{
public static final String Black = "black";
public static final String Blue = "blue";
public static final String Green = "green";
public static final String Red = "red";
public static final String White = "white";
public static final String Colorless = "colorless";
//color order "wubrg"
public static final String Colors[] =
{White, Blue, Black, Red, Green, Colorless};
public static final String onlyColors[] = {White, Blue, Black, Red, Green};
}
}//Constant
/*
public interface Keyword
{
public static final String Swampwalk = "Swampwalk";
public static final String Plainswalk = "Plainswalk";
public static final String Forestwalk = "Forestwalk";
public static final String Islandwalk = "Islandwalk";
public static final String Mountainwalk = "Mountainwalk";
public static final String Flying = "Flying";
public static final String Fear = "Fear";
public static final String Vigilance = "Vigilance";
public static final String Double_Strike = "Double Strike";
public static final String First_Strike = "First Strike";
public static final String Haste = "Haste";
public static final String Indestructable = "Indestructable";
public static final String Landwalk = "Landwalk";
public static final String Protection = "Protection";
public static final String Regeneration = "Regeneration";
public static final String Trample = "Trample";
}
// mirrodin block abilities
public static final String Affinity = "affinity";
public static final String Modular = "modular";
public static final String Sunburst = "sunburst";
//onslaught block
public static final String Cycling = "cycling";
public static final String Land_Cycling = "land cycling";
public static final String Morph = "morph";
/*
public static final int Landwalk_Forest = 9;
public static final int Landwalk_Island = 10;
public static final int Landwalk_Plain = 11;
public static final int Landwalk__Swamp = 12;
public static final int Landwalk_Mountain = 13;
public static final int Protection_Red = 14;
public static final int Protection_Black = 15;
public static final int Protection_White = 16;
public static final int Protection_Blue = 17;
public static final int Protection_Green = 18;
public static final int Protection_Artifact = 19;
//taken from Mirror Golem
public static final int Protection_Creature = 20;
public static final int Protection_Enchantment = 21;
public static final int Protection_Instant = 22;
public static final int Protection_Land = 23;
public static final int Protection_Sorcery = 24;
public static final int Affinity_Artifact = 29;
public static final int Affinity_Forest = 30;
public static final int Affinity_Plain = 31;
public static final int Affinity_Swamp = 32;
public static final int Affinity_Island = 33;
public static final int Affinity_Moutain = 34;
}
*/

76
src/Deck.java Normal file
View File

@@ -0,0 +1,76 @@
import java.util.*;
public class Deck implements java.io.Serializable
{
private static final long serialVersionUID = -2188987217361601903L;
//gameType is from Constant.GameType, like Constant.GameType.Regular
private String deckType;
private boolean isRegular;
private boolean isSealed;
private boolean isDraft;
private ArrayList<String> main = new ArrayList<String>();
private ArrayList<String> sideboard = new ArrayList<String>();
//very important, do NOT change this
private String name = "";
//gameType is from Constant.GameType, like Constant.GameType.Regular
public Deck(String gameType)
{
deckType = gameType;
setDeckType(gameType);
}
public String getDeckType() {return deckType;}
//can only call this method ONCE
private final void setDeckType(String deckType)
{
if(isRegular || isSealed || isDraft)
throw new RuntimeException("Deck : setDeckType() error, deck type has already been set");
if(deckType.equals(Constant.GameType.Constructed))
isRegular = true;
else if(deckType.equals(Constant.GameType.Sealed))
isSealed = true;
else if(deckType.equals(Constant.GameType.Draft))
isDraft = true;
else
throw new RuntimeException("Deck : setDeckType() error, invalid deck type - " +deckType);
}
public void setName(String s) {name = s;}
public String getName() {return name;}//may return null
public void addMain(String cardName) {main.add(cardName);}
public int countMain() {return main.size();}
public String getMain(int index) {return main.get(index).toString();}
public String removeMain(int index) {return main.remove(index).toString();}
public void addSideboard(String cardName) {sideboard.add(cardName);}
public int countSideboard() {return sideboard.size();}
public String getSideboard(int index) {return sideboard.get(index).toString();}
public String removeSideboard(int index) {return sideboard.remove(index).toString();}
public boolean isDraft() {return isDraft;}
public boolean isSealed() {return isSealed;}
public boolean isRegular() {return isRegular;}
public int hashcode() {return getName().hashCode();}
public String toString() {return getName();}
}
class DeckSort implements Comparator<Object>
{
public int compare(Object a, Object b)
{
String a1 = ((Deck)a).getName();
String b1 = ((Deck)b).getName();
return a1.compareTo(b1);
}
}

203
src/DeckIO.java Normal file
View File

@@ -0,0 +1,203 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import forge.error.ErrorViewer;
//reads and write Deck objects
public class DeckIO {
private final File file;
private ArrayList<Deck> deckList = new ArrayList<Deck>();
//key is String of the humans deck
//data is Deck[] size of 8
//humans deck is Deck[0]
private Map<String, Deck[]> boosterMap = new HashMap<String, Deck[]>();
public static void main(String[] args) {
Deck[] deck = new Deck[8];
for(int i = 0; i < deck.length; i++) {
deck[i] = new Deck(Constant.GameType.Draft);
deck[i].setName("" + i);
}
deck[0].addMain("Lantern Kami");
//DeckIO io = new DeckIO("booster-decks");
// io.writeBoosterDeck(deck);
// io.close();
// io.deleteBoosterDeck("0");
// System.out.println(io.getBoosterDecks().keySet().size());
// io.close();
}
public DeckIO(String filename) {
this(new File(filename));
}
public DeckIO(File file) {
this.file = file;
readFile();
}
public boolean isUnique(String deckName) {
Deck d;
for(int i = 0; i < deckList.size(); i++) {
d = deckList.get(i);
if(d.getName().equals(deckName)) return false;
}
return true;
}
public boolean isUniqueDraft(String deckName) {
ArrayList<String> key = new ArrayList<String>(boosterMap.keySet());
for(int i = 0; i < key.size(); i++) {
if(key.get(i).equals(deckName)) return false;
}
return true;
}
public boolean hasName(String deckName) {
ArrayList<String> string = new ArrayList<String>();
for(int i = 0; i < deckList.size(); i++)
string.add(deckList.get(i).toString());
Iterator<String> it = boosterMap.keySet().iterator();
while(it.hasNext())
string.add(it.next().toString());
return string.contains(deckName);
}
public Deck readDeck(String deckName) {
return deckList.get(findDeckIndex(deckName));
}
private int findDeckIndex(String deckName) {
int n = -1;
for(int i = 0; i < deckList.size(); i++)
if((deckList.get(i)).getName().equals(deckName)) n = i;
if(n == -1) throw new RuntimeException("DeckIO : findDeckIndex() error, deck name not found - " + deckName);
return n;
}
public void writeDeck(Deck deck) {
if(deck.getDeckType().equals(Constant.GameType.Draft)) throw new RuntimeException(
"DeckIO : writeDeck() error, deck type is Draft");
deckList.add(deck);
}
public void deleteDeck(String deckName) {
deckList.remove(findDeckIndex(deckName));
}
public Deck[] readBoosterDeck(String deckName) {
if(!boosterMap.containsKey(deckName)) throw new RuntimeException(
"DeckIO : readBoosterDeck() error, deck name not found - " + deckName);
return boosterMap.get(deckName);
}
public void writeBoosterDeck(Deck[] deck) {
checkBoosterDeck(deck);
boosterMap.put(deck[0].toString(), deck);
}//writeBoosterDeck()
public void deleteBoosterDeck(String deckName) {
if(!boosterMap.containsKey(deckName)) throw new RuntimeException(
"DeckIO : deleteBoosterDeck() error, deck name not found - " + deckName);
boosterMap.remove(deckName);
}
private void checkBoosterDeck(Deck[] deck) {
if(deck == null || deck.length != 8 || deck[0].getName().equals("")
|| (!deck[0].getDeckType().equals(Constant.GameType.Draft))) {
throw new RuntimeException("DeckIO : checkBoosterDeck() error, invalid deck");
}
// for(int i = 0; i < deck.length; i++)
// if(deck[i].getName().equals(""))
// throw new RuntimeException("DeckIO : checkBoosterDeck() error, deck does not have name - " +deck[i].getName());
}//checkBoosterDeck()
public Deck[] getDecks() {
Deck[] out = new Deck[deckList.size()];
deckList.toArray(out);
return out;
}
public Map<String, Deck[]> getBoosterDecks() {
return new HashMap<String, Deck[]>(boosterMap);
}
public void close() {
writeFile();
}
@SuppressWarnings("unchecked")
// ArrayList and Map have unchecked casts
private void readFile() {
try {
//~
// Shouldn't ever get here, but just in case...
if(file == null) {
return;
}
//~
if(!file.exists()) return;
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
deckList = (ArrayList<Deck>) in.readObject();
boosterMap = (Map<String, Deck[]>) in.readObject();
in.close();
} catch(Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("DeckIO : read() error, " + ex);
}
}
private void writeFile() {
try {
//~
if(file == null) {
return;
}
//~
if(!file.exists()) file.createNewFile();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(deckList);
out.writeObject(boosterMap);
out.flush();
out.close();
} catch(Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("DeckIO : write() error, " + ex.getMessage());
}
}
}//DeckIO

114
src/DefaultPlayerZone.java Normal file
View File

@@ -0,0 +1,114 @@
import java.util.*;
public class DefaultPlayerZone extends PlayerZone implements java.io.Serializable
{
private static final long serialVersionUID = -5687652485777639176L;
private ArrayList<Card> cards = new ArrayList<Card>();
private String zoneName;
private String playerName;
private boolean update = true;
public DefaultPlayerZone(String zone, String player)
{
zoneName = zone;
playerName = player;
}
//************ BEGIN - these methods fire updateObservers() *************
public void add(Object o)
{
/*
if (is("Graveyard"))
System.out.println("GRAAAAAAAAAAAAAAAVE");
*/
Card c = (Card)o;
if (is("Graveyard")
&& c.getKeyword().contains("When this card is put into a graveyard from anywhere, reveal this card and shuffle it into its owner's library instead."))
{
PlayerZone lib = AllZone.getZone(Constant.Zone.Library, c.getOwner());
lib.add(c);
AllZone.GameAction.shuffle(c.getOwner());
return;
}
c.addObserver(this);
c.setTurnInZone(AllZone.Phase.getTurn());
cards.add((Card)c);
update();
}
public void update(Observable ob, Object object)
{
this.update();
}
public void add(Card c, int index)
{
cards.add(index, c);
c.setTurnInZone(AllZone.Phase.getTurn());
update();
}
public void remove(Object c)
{
//TODO: put leaves play checks here
cards.remove((Card)c);
update();
}
public void remove(int index)
{
cards.remove(index);
update();
}
public void setCards(Card c[])
{
cards = new ArrayList<Card>(Arrays.asList(c));
update();
}
//removes all cards
public void reset()
{
cards.clear();
update();
}
//************ END - these methods fire updateObservers() *************
public boolean is(String zone)
{
return zone.equals(zoneName);
}
public boolean is(String zone, String player)
{
return (zone.equals(zoneName) && player.equals(playerName));
}
public String getPlayer()
{
return playerName;
}
public String getZone()
{
return zoneName;
}
public int size()
{
return cards.size();
}
public Card get(int index)
{
return (Card)cards.get(index);
}
public Card[] getCards()
{
Card c[] = new Card[cards.size()];
cards.toArray(c);
return c;
}
public void update()
{
if(update)
updateObservers();
}
public void setUpdate(boolean b) {update = b;}
public boolean getUpdate() {return update;}
}

18
src/Display.java Normal file
View File

@@ -0,0 +1,18 @@
public interface Display {
public <T> T getChoice(String message, T[] choices);
public <T> T getChoiceOptional(String message, T[] choices);
public void showMessage(String s);
public MyButton getButtonOK();
public MyButton getButtonCancel();
// public void showStatus(String message);
public void showCombat(String message);
public void setVisible(boolean b);
public boolean stopEOT();
//assigns combat damage, used by Combat.setAssignedDamage()
public void assignDamage(Card attacker, CardList blockers, int damage);
}

65
src/EndOfTurn.java Normal file
View File

@@ -0,0 +1,65 @@
//import java.util.*;
//handles "until end of turn" and "at end of turn" commands from cards
public class EndOfTurn implements java.io.Serializable
{
private static final long serialVersionUID = -3656715295379727275L;
private CommandList at = new CommandList();
private CommandList until = new CommandList();
public void addAt(Command c) {at.add(c);}
public void addUntil(Command c) {until.add(c);}
public void executeAt()
{
//Pyrohemia and Pestilence
CardList all = new CardList();
all.addAll(AllZone.Human_Play.getCards());
all.addAll(AllZone.Computer_Play.getCards());
CardList creature = all.getType("Creature");
if(creature.isEmpty())
{
CardList sacrifice = new CardList();
sacrifice.addAll(all.getName("Pyrohemia").toArray());
sacrifice.addAll(all.getName("Pestilence").toArray());
for(int i = 0; i < sacrifice.size(); i++)
AllZone.GameAction.sacrifice(sacrifice.get(i));
}
GameActionUtil.removeExaltedEffects();
GameActionUtil.removeAttackedBlockedThisTurn();
AllZone.StateBasedEffects.rePopulateStateBasedList();
PlayerZone cz = AllZone.getZone(Constant.Zone.Removed_From_Play, Constant.Player.Computer);
PlayerZone hz = AllZone.getZone(Constant.Zone.Removed_From_Play, Constant.Player.Human);
CardList c = new CardList(cz.getCards());
CardList h = new CardList(hz.getCards());
System.out.println("number of cards in compy removed zone: " + c.size());
System.out.println("number of cards in human removed zone: " + h.size());
execute(at);
}//executeAt()
public void executeUntil() {execute(until);}
public int sizeAt() {return at.size();}
public int sizeUntil() {return until.size();}
private void execute(CommandList c)
{
int length = c.size();
for(int i = 0; i < length; i++)
c.remove(0).execute();
}
}

120
src/ErrorViewer.java Normal file
View File

@@ -0,0 +1,120 @@
/**
* ErrorViewer.java
*
* Created on 02.08.2009
*/
import static javax.swing.JOptionPane.*;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
* The class ErrorViewer. Enables showing and saving error messages that occured in forge.
*
* @version V1.0 02.08.2009
* @author Clemens Koza
*/
public class ErrorViewer {
private static JFileChooser c;
/**
* Shows an error dialog taking the exception's message as the error message.
*/
public static void showError(Throwable ex) {
showError(ex, null);
}
/**
* Shows an error dialog creating the error message by a formatting operation.
*/
public static void showError(Throwable ex, String format, Object... args) {
if(ex == null) return;
showError(ex, String.format(format, args));
}
/**
* Shows an error dialog with the specified error message.
*/
public static void showError(final Throwable ex, String message) {
if(ex == null) return;
//As the first action, write to standard err for console debugging
if(message != null) System.err.println(message);
ex.printStackTrace();
final StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println("An error has occured. You can copy/paste this message or save it to a file.");
pw.println("Please report this, plus what you tried to do, to:");
pw.println("\thttp://www.slightlymagic.net/forum/viewforum.php?f=26");
pw.println("If you don't want to register an account, you can mail it directly to");
pw.println("\tmtgrares@yahoo.com");
pw.println();
pw.println(message != null? message:ex.getMessage());
pw.println();
pw.println("Detailed error trace:");
ex.printStackTrace(pw);
final JTextArea area = new JTextArea(sw.toString());
area.setFont(new Font("Monospace", Font.PLAIN, 10));
area.setEditable(false);
area.setLineWrap(true);
area.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(area);
Dimension dim = scroll.getPreferredSize();
dim.width = 500;
scroll.setPreferredSize(dim);
JButton save = new JButton("Save...");
save.addActionListener(new ActionListener() {
//@Override
public void actionPerformed(ActionEvent e) {
if(c == null) c = new JFileChooser();
File f;
for(int i = 0;; i++) {
String name = String.format("%TF-%02d-%s.txt", System.currentTimeMillis(), i,
ex.getClass().getSimpleName());
f = new File(name);
if(!f.exists()) break;
}
c.setSelectedFile(f);
c.showSaveDialog(null);
f = c.getSelectedFile();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(area.getText());
bw.close();
} catch(IOException ex) {
showError(ex, "There was an error during saving, sorry!");
}
}
});
//Button is not modified, String gets the automatic listener to hide the dialog
Object[] options = {save, "Close"};
JOptionPane pane = new JOptionPane(scroll, ERROR_MESSAGE, DEFAULT_OPTION, null, options, options[1]);
JDialog dlg = pane.createDialog("Error");
dlg.setVisible(true);
dlg.dispose();
}
}

90
src/ExternalPanel.java Normal file
View File

@@ -0,0 +1,90 @@
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* ExternalPanel.java
*
* Created on 13.08.2009
*/
/**
* The class ExternalPanel. A panel with which some other component can be shown in an external window.
*
* @version V0.0 13.08.2009
* @author Clemens Koza
*/
public class ExternalPanel extends JPanel {
private static final long serialVersionUID = 9098962430872706173L;
private Component child, head;
private JFrame frame;
public ExternalPanel(Component child) {
this(child, BorderLayout.EAST);
}
public ExternalPanel(Component child, String side) {
super(new BorderLayout());
add(this.child = child);
JButton b = new JButton();
b.setPreferredSize(new Dimension(6, 6));
b.setToolTipText("Click to move component into an extra Window");
b.addActionListener(new ExternListener());
head = b;
setHeadSide(side);
}
public void setHeadSide(String side) {
remove(head);
add(head, side);
}
@Override
protected void addImpl(Component comp, Object constraints, int index) {
if(comp != child && comp != head) throw new IllegalArgumentException();
super.addImpl(comp, constraints, index);
}
private final class ExternListener extends WindowAdapter implements ActionListener {
private void bringOut() {
frame = new JFrame();
frame.addWindowListener(this);
frame.addWindowStateListener(this);
frame.add(child);
frame.getRootPane().setPreferredSize(child.getSize());
frame.pack();
frame.setVisible(true);
validate();
repaint();
}
private void bringIn() {
add(child);
frame.dispose();
frame = null;
validate();
repaint();
}
public void actionPerformed(ActionEvent e) {
if(frame == null) bringOut();
else bringIn();
}
@Override
public void windowClosing(WindowEvent e) {
bringIn();
}
}
}

70
src/FileUtil.java Normal file
View File

@@ -0,0 +1,70 @@
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import forge.error.ErrorViewer;
public class FileUtil {
public static boolean doesFileExist(String filename) {
File f = new File(filename);
return f.exists();
}
public static void writeFile(String filename, List<String> data) {
writeFile(new File(filename), data);
}
//writes each element of ArrayList on a separate line
//this is used to write a file of Strings
//this will create a new file if needed
//if filename already exists, it is deleted
public static void writeFile(File file, List<String> data) {
try {
Collections.sort(data);
BufferedWriter io = new BufferedWriter(new FileWriter(file));
for(int i = 0; i < data.size(); i++)
io.write(data.get(i) + "\r\n");
io.flush();
io.close();
} catch(Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("FileUtil : writeFile() error, problem writing file - " + file + " : " + ex);
}
}//writeFile()
public static ArrayList<String> readFile(String filename) {
return readFile(new File(filename));
}
//reads line by line and adds each line to the ArrayList
//this will return blank lines as well
//if filename not found, returns an empty ArrayList
public static ArrayList<String> readFile(File file) {
ArrayList<String> list = new ArrayList<String>();
BufferedReader in;
try {
if(file == null || !file.exists()) return list;
in = new BufferedReader(new FileReader(file));
String line;
while((line = in.readLine()) != null)
list.add(line);
} catch(Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("FileUtil : readFile() error, " + ex);
}
return list;
}//readFile()
}

1259
src/GameAction.java Normal file

File diff suppressed because it is too large Load Diff

10853
src/GameActionUtil.java Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,297 @@
import java.util.*;
public class GenerateConstructedDeck
{
private String color1;
private String color2;
private Map<String,String> map = new HashMap<String,String>();
public GenerateConstructedDeck() {setupMap();}
private void setupMap()
{
map.put(Constant.Color.Black , "Swamp");
map.put(Constant.Color.Blue , "Island");
map.put(Constant.Color.Green , "Forest");
map.put(Constant.Color.Red , "Mountain");
map.put(Constant.Color.White , "Plains");
}
public CardList generateDeck()
{
CardList deck;
int check;
do{
deck = get2ColorDeck();
check = deck.getType("Creature").size();
}while(check < 16 || 24 < check);
addLand(deck);
if(deck.size() != 60)
throw new RuntimeException("GenerateConstructedDeck() : generateDeck() error, deck size it not 60, deck size is " +deck.size());
return deck;
}
//25 lands
private void addLand(CardList list)
{
Card land;
for(int i = 0; i < 13; i++)
{
land = AllZone.CardFactory.getCard(map.get(color1).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(map.get(color2).toString(), Constant.Player.Computer);
list.add(land);
}
}//addLand()
private CardList getCards()
{
return filterBadCards(AllZone.CardFactory.getAllCards());
}//getCards()
private CardList get2ColorDeck()
{
CardList deck = get2Colors(getCards());
CardList out = new CardList();
deck.shuffle();
//trim deck size down to 34 cards, presumes 26 land, for a total of 60 cards
for(int i = 0; i < 34 && i < deck.size(); i++)
out.add(deck.get(i));
return out;
}
private CardList get2Colors(CardList in)
{
int a;
int b;
do{
a = CardUtil.getRandomIndex(Constant.Color.onlyColors);
b = CardUtil.getRandomIndex(Constant.Color.onlyColors);
}while(a == b);//do not want to get the same color twice
color1 = Constant.Color.onlyColors[a];
color2 = Constant.Color.onlyColors[b];
CardList out = new CardList();
out.addAll(CardListUtil.getColor(in, color1).toArray());
out.addAll(CardListUtil.getColor(in, color2).toArray());
out.shuffle();
CardList artifact = in.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
//is this really a colorless artifact and not something
//wierd like Sarcomite Myr which is a colored artifact
return c.isArtifact() &&
CardUtil.getColors(c).contains(Constant.Color.Colorless) &&
!Gui_NewGame.removeArtifacts.isSelected();
}
});
out.addAll(artifact.toArray());
out = out.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
if(c.isCreature() &&
c.getNetAttack() <= 1 &&
Gui_NewGame.removeSmallCreatures.isSelected())
{
return false;
}
return true;
}
});
out = filterBadCards(out);
return out;
}
private CardList filterBadCards(CardList list)
{
//remove "bad" and multi-colored cards
final ArrayList<String> remove = new ArrayList<String>();
remove.add("Sarcomite Myr");
remove.add("Force of Savagery");
remove.add("Darksteel Colossus");
remove.add("Jokulhaups");
remove.add("Steel Wall");
remove.add("Ornithopter");
remove.add("Amnesia");
remove.add("Battle of Wits");
remove.add("Ashes to Ashes");
remove.add("Haunted Angel");
remove.add("Sky Swallower");
remove.add("Magus of the Library");
remove.add("The Unspeakable");
remove.add("Wall of Kelp");
remove.add("Incendiary Command");
remove.add("Memnarch");
remove.add("Plague Wind");
remove.add("Klaas, Elf Friend");
remove.add("Delirium Skeins");
remove.add("Undying Beast");
remove.add("Wit's End");
remove.add("Blinding Light");
remove.add("Hymn to Tourach");
//not fully implemented:
remove.add("Aether Membrane");
remove.add("Arashi, the Sky Asunder");
remove.add("Hand of Cruelty");
remove.add("Hand of Honor");
//useless, or combo cards:
remove.add("Aluren");
remove.add("Conspiracy");
remove.add("Crucible of Fire");
remove.add("Verduran Enchantress");
remove.add("Enchantress's Presence");
remove.add("Mesa Enchantress");
remove.add("Moat");
remove.add("Magus of the Moat");
remove.add("Relentless Rats");
remove.add("Vedalken Archmage");
remove.add("Hatching Plans");
remove.add("Sensation Gorger");
//semi useless
remove.add("Wren's Run Packmaster");
remove.add("Nova Chaser");
remove.add("Supreme Exemplar");
remove.add("Goblin Ringleader");
remove.add("Sylvan Messenger");
remove.add("Tromp the Domains");
remove.add("Legacy Weapon");
//cards the AI cannot play (effectively):
remove.add("Sensei's Divining Top");
remove.add("Standstill");
//remove.add("Counterspell");
//remove.add("Exclude");
//remove.add("False Summoning");
//remove.add("Essence Scatter");
//remove.add("Preemptive Strike");
//remove.add("Punish Ignorance");
//remove.add("Remand");
//remove.add("Mystic Snake");
//remove.add("Absorb");
//remove.add("Undermine");
//remove.add("Overwhelming Intellect");
remove.add("AEther Vial");
remove.add("Covetous Dragon");
remove.add("Terramorphic Expanse");
remove.add("Earthcraft");
remove.add("Burst of Speed");
remove.add("Magnify");
remove.add("Nature's Cloak");
remove.add("Resuscitate");
remove.add("Shield Wall");
remove.add("Solidarity");
remove.add("Steadfastness");
remove.add("Tortoise Formation");
//manapool stuff:
remove.add("Dark Ritual");
remove.add("Seething Song");
remove.add("Sol Ring");
remove.add("Gaea's Cradle");
remove.add("Priest of Titania");
remove.add("Tolarian Academy");
remove.add("Serra's Sanctum");
remove.add("Basalt Monolith");
remove.add("Grim Monolith");
remove.add("Black Lotus");
remove.add("Composite Golem");
remove.add("Thran Dynamo");
remove.add("Elvish Archdruid");
remove.add("Sunglasses of Urza");
remove.add("Ceta Discple");
remove.add("Agent of Stromgald");
remove.add("Apprentice Wizard");
remove.add("Azorius Signet");
remove.add("Bog Initiate");
remove.add("Boros Signet");
remove.add("Celestial Prism");
remove.add("Dimir Signet");
remove.add("Fire Sprites");
remove.add("Fyndhorn Elder");
remove.add("Gilded Lotus");
remove.add("Golgari Signet");
remove.add("Greenweaver Druid");
remove.add("Gruul Signet");
remove.add("Helionaut");
remove.add("Izzet Signet");
remove.add("Knotvine Mystic");
remove.add("Mana Cylix");
remove.add("Mana Prism");
remove.add("Nantuko Elder");
remove.add("Nomadic Elf");
remove.add("Orochi Leafcaller");
remove.add("Orzhov Signet");
remove.add("Prismatic Lens");
remove.add("Rakdos Signet");
remove.add("Sea Scryer");
remove.add("Selesnya Signet");
remove.add("Simic Signet");
remove.add("Sisay's Ring");
remove.add("Skyshroud Elf");
remove.add("Ur-Golem's Eye");
remove.add("Viridian Acolyte");
remove.add("Worn Powerstone");
final ArrayList<Card> goodLand = new ArrayList<Card>();
//goodLand.add("Faerie Conclave");
//goodLand.add("Forbidding Watchtower");
//goodLand.add("Treetop Village");
CardList out = list.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
ArrayList<String> list = CardUtil.getColors(c);
if (list.size() == 2)
{
if (!(list.contains(color1) && list.contains(color2)))
return false;
}
return CardUtil.getColors(c).size() <= 2 && //only dual colored gold cards
!c.isLand() && //no land
!remove.contains(c.getName()) || //OR very important
goodLand.contains(c.getName());
}
});
return out;
}//filterBadCards()
public static void main(String[] args)
{
GenerateConstructedDeck g = new GenerateConstructedDeck();
for(int i = 0; i < 50; i++)
{
CardList c = g.generateDeck();
System.out.println(c.getType("Creature").size() +" - " +c.size());
}
System.exit(1);
}//main
}

View File

@@ -0,0 +1,557 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class GenerateConstructedMultiColorDeck
{
private String color1;
private String color2;
private String color3;
private String color4;
private String color5;
private Map<String,String> map = new HashMap<String,String>();
private Map<String, String[]> multiMap = new HashMap<String, String[]>();
public GenerateConstructedMultiColorDeck()
{
setupBasicLandMap();
setupMultiMap();
}
private void setupBasicLandMap()
{
map.put(Constant.Color.Black , "Swamp");
map.put(Constant.Color.Blue , "Island");
map.put(Constant.Color.Green , "Forest");
map.put(Constant.Color.Red , "Mountain");
map.put(Constant.Color.White , "Plains");
}
private void setupMultiMap()
{
multiMap.put(Constant.Color.Black + Constant.Color.Blue, new String[] {"Underground Sea", "Watery Grave"});
multiMap.put(Constant.Color.Black + Constant.Color.Green, new String[] {"Bayou", "Overgrown Tomb"});
multiMap.put(Constant.Color.Black + Constant.Color.Red , new String[]{"Badlands", "Blood Crypt"});
multiMap.put(Constant.Color.Black + Constant.Color.White, new String[] {"Scrubland", "Godless Shrine"});
multiMap.put(Constant.Color.Blue + Constant.Color.Black, new String[] {"Underground Sea", "Watery Grave"});
multiMap.put(Constant.Color.Blue + Constant.Color.Green, new String[] {"Tropical Island", "Breeding Pool"});
multiMap.put(Constant.Color.Blue +Constant.Color.Red, new String[]{"Volcanic Island", "Steam Vents"});
multiMap.put(Constant.Color.Blue +Constant.Color.White, new String[] {"Tundra", "Hallowed Fountain"});
multiMap.put(Constant.Color.Green +Constant.Color.Black, new String[] {"Bayou", "Overgrown Tomb"});
multiMap.put(Constant.Color.Green +Constant.Color.Blue, new String[] {"Tropical Island", "Breeding Pool"});
multiMap.put(Constant.Color.Green +Constant.Color.Red , new String[]{"Taiga", "Stomping Ground"});
multiMap.put(Constant.Color.Green +Constant.Color.White, new String[] {"Savannah", "Temple Garden"});
multiMap.put(Constant.Color.Red +Constant.Color.Black, new String[] {"Badlands", "Blood Crypt"});
multiMap.put(Constant.Color.Red +Constant.Color.Blue, new String[] {"Volcanic Island", "Steam Vents"});
multiMap.put(Constant.Color.Red +Constant.Color.Green, new String[]{"Taiga", "Stomping Ground"});
multiMap.put(Constant.Color.Red +Constant.Color.White, new String[] {"Plateau", "Sacred Foundry"});
multiMap.put(Constant.Color.White +Constant.Color.Black, new String[] {"Scrubland", "Godless Shrine"});
multiMap.put(Constant.Color.White +Constant.Color.Blue, new String[] {"Tundra", "Hallowed Fountain"});
multiMap.put(Constant.Color.White +Constant.Color.Green, new String[]{"Savannah", "Temple Garden"});
multiMap.put(Constant.Color.White +Constant.Color.Red , new String[] {"Plateau", "Sacred Foundry"});
}
public CardList generate3ColorDeck()
{
CardList deck;
int check;
do{
deck = get3ColorDeck();
check = deck.getType("Creature").size();
}while(check < 16 || 24 < check);
addLand(deck, 3);
if(deck.size() != 60)
throw new RuntimeException("GenerateConstructedDeck() : generateDeck() error, deck size it not 60, deck size is " +deck.size());
return deck;
}
public CardList generate5ColorDeck()
{
CardList deck;
/*
int check;
do{
deck = get5ColorDeck();
check = deck.getType("Creature").size();
}while(check < 15 || 25 < check);
*/
deck = get5ColorDeck();
addLand(deck, 5);
if(deck.size() != 61)
throw new RuntimeException("GenerateConstructedDeck() : generateDeck() error, deck size it not 60, deck size is " +deck.size());
return deck;
}
private void addLand(CardList list, int colors)
{
if (colors==3)
{
int numberBasic = 2;
Card land;
for(int i = 0; i < numberBasic; i++)
{
land = AllZone.CardFactory.getCard(map.get(color1).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(map.get(color2).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(map.get(color3).toString(), Constant.Player.Computer);
list.add(land);
}
int numberDual = 4;
for (int i = 0; i < numberDual;i++)
{
land = AllZone.CardFactory.getCard(multiMap.get(color1+color2)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color1+color3)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color2+color3)[0], Constant.Player.Computer);
list.add(land);
}
for (int i=0; i<2;i++)
{
land = AllZone.CardFactory.getCard(multiMap.get(color1+color2)[1], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color1+color3)[1], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color2+color3)[1], Constant.Player.Computer);
list.add(land);
}
}
else if (colors == 5)
{
int numberBasic = 1;
Card land;
for(int i = 0; i < numberBasic; i++)
{
land = AllZone.CardFactory.getCard(map.get(color1).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(map.get(color2).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(map.get(color3).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(map.get(color4).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(map.get(color5).toString(), Constant.Player.Computer);
list.add(land);
}
int numberDual = 2;
for (int i = 0; i < numberDual;i++)
{
land = AllZone.CardFactory.getCard(multiMap.get(color1+color2)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color1+color3)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color1+color4)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color1+color5)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color2+color3)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color2+color4)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color2+color5)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color3+color4)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color3+color5)[0], Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(multiMap.get(color4+color5)[0], Constant.Player.Computer);
list.add(land);
}
}
}//addLand()
private CardList getCards(int colors)
{
return filterBadCards(AllZone.CardFactory.getAllCards(), colors);
}//getCards()
private CardList get3ColorDeck()
{
CardList deck = get3Colors(getCards(3));
CardList out = new CardList();
deck.shuffle();
//trim deck size down to 36 cards, presumes 24 land, for a total of 60 cards
for(int i = 0; i < 36 && i < deck.size(); i++)
out.add(deck.get(i));
return out;
}
private CardList get5ColorDeck()
{
CardList deck = get5Colors(getCards(5));
CardList out = new CardList();
deck.shuffle();
//trim deck size down to 36 cards, presumes 24 land, for a total of 60 cards
for(int i = 0; i < 36 && i < deck.size(); i++)
out.add(deck.get(i));
return out;
}
private CardList get3Colors(CardList in)
{
int a;
int b;
int c;
a = CardUtil.getRandomIndex(Constant.Color.onlyColors);
do{
b = CardUtil.getRandomIndex(Constant.Color.onlyColors);
c = CardUtil.getRandomIndex(Constant.Color.onlyColors);
}while(a == b || a == c || b == c );//do not want to get the same color thrice
color1 = Constant.Color.onlyColors[a];
color2 = Constant.Color.onlyColors[b];
color3 = Constant.Color.onlyColors[c];
CardList out = new CardList();
out.addAll(CardListUtil.getColor(in, color1).toArray());
out.addAll(CardListUtil.getColor(in, color2).toArray());
out.addAll(CardListUtil.getColor(in, color3).toArray());
out.shuffle();
CardList artifact = in.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
//is this really a colorless artifact and not something
//wierd like Sarcomite Myr which is a colored artifact
return c.isArtifact() &&
CardUtil.getColors(c).contains(Constant.Color.Colorless) &&
!Gui_NewGame.removeArtifacts.isSelected();
}
});
out.addAll(artifact.toArray());
out = out.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
if(c.isCreature() &&
c.getNetAttack() <= 1 &&
Gui_NewGame.removeSmallCreatures.isSelected())
{
return false;
}
return true;
}
});
out = filterBadCards(out, 3);
return out;
}
private CardList get5Colors(CardList in)
{
color1 = Constant.Color.Black;
color2 = Constant.Color.Blue;
color3 = Constant.Color.Green;
color4 = Constant.Color.Red;
color5 = Constant.Color.White;
CardList out = new CardList();
/*
out.addAll(CardListUtil.getColor(in, color1).toArray());
out.addAll(CardListUtil.getColor(in, color2).toArray());
out.addAll(CardListUtil.getColor(in, color3).toArray());
out.addAll(CardListUtil.getColor(in, color4).toArray());
out.addAll(CardListUtil.getColor(in, color5).toArray());
*/
out.addAll(CardListUtil.getGoldCards(in).toArray());
out.shuffle();
CardList artifact = in.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
//is this really a colorless artifact and not something
//wierd like Sarcomite Myr which is a colored artifact
return c.isArtifact() &&
CardUtil.getColors(c).contains(Constant.Color.Colorless) &&
!Gui_NewGame.removeArtifacts.isSelected();
}
});
out.addAll(artifact.toArray());
out = out.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
if(c.isCreature() &&
c.getNetAttack() <= 1 &&
Gui_NewGame.removeSmallCreatures.isSelected())
{
return false;
}
return true;
}
});
out = filterBadCards(out, 3);
return out;
}
private CardList filterBadCards(CardList list, int colors)
{
//remove "bad" and multi-colored cards
final ArrayList<String> remove = new ArrayList<String>();
remove.add("Sarcomite Myr");
remove.add("Force of Savagery");
remove.add("Darksteel Colossus");
remove.add("Jokulhaups");
remove.add("Steel Wall");
remove.add("Ornithopter");
remove.add("Amnesia");
remove.add("Battle of Wits");
remove.add("Ashes to Ashes");
remove.add("Haunted Angel");
remove.add("Sky Swallower");
remove.add("Magus of the Library");
remove.add("The Unspeakable");
remove.add("Wall of Kelp");
remove.add("Incendiary Command");
remove.add("Memnarch");
remove.add("Plague Wind");
remove.add("Klaas, Elf Friend");
remove.add("Delirium Skeins");
remove.add("Undying Beast");
remove.add("Wit's End");
remove.add("Blinding Light");
remove.add("Hymn to Tourach");
//not fully implemented:
remove.add("Aether Membrane");
remove.add("Arashi, the Sky Asunder");
remove.add("Hand of Cruelty");
remove.add("Hand of Honor");
//useless, or combo cards:
remove.add("Aluren");
remove.add("Conspiracy");
remove.add("Crucible of Fire");
remove.add("Verduran Enchantress");
remove.add("Enchantress's Presence");
remove.add("Mesa Enchantress");
remove.add("Moat");
remove.add("Magus of the Moat");
remove.add("Relentless Rats");
remove.add("Vedalken Archmage");
remove.add("Hatching Plans");
remove.add("Sensation Gorger");
//semi useless
remove.add("Wren's Run Packmaster");
remove.add("Nova Chaser");
remove.add("Supreme Exemplar");
remove.add("Goblin Ringleader");
remove.add("Sylvan Messenger");
remove.add("Tromp the Domains");
remove.add("Legacy Weapon");
//cards the AI cannot play (effectively):
remove.add("Sensei's Divining Top");
remove.add("Standstill");
//remove.add("Counterspell");
//remove.add("Exclude");
//remove.add("False Summoning");
//remove.add("Essence Scatter");
//remove.add("Preemptive Strike");
//remove.add("Punish Ignorance");
//remove.add("Remand");
//remove.add("Mystic Snake");
//remove.add("Absorb");
//remove.add("Undermine");
//remove.add("Overwhelming Intellect");
remove.add("AEther Vial");
remove.add("Covetous Dragon");
remove.add("Terramorphic Expanse");
remove.add("Earthcraft");
remove.add("Burst of Speed");
remove.add("Magnify");
remove.add("Nature's Cloak");
remove.add("Resuscitate");
remove.add("Shield Wall");
remove.add("Solidarity");
remove.add("Steadfastness");
remove.add("Tortoise Formation");
//manapool stuff:
remove.add("Dark Ritual");
remove.add("Seething Song");
remove.add("Sol Ring");
remove.add("Gaea's Cradle");
remove.add("Priest of Titania");
remove.add("Tolarian Academy");
remove.add("Serra's Sanctum");
remove.add("Basalt Monolith");
remove.add("Grim Monolith");
remove.add("Black Lotus");
remove.add("Composite Golem");
remove.add("Thran Dynamo");
remove.add("Elvish Archdruid");
remove.add("Sunglasses of Urza");
remove.add("Ceta Discple");
remove.add("Agent of Stromgald");
remove.add("Apprentice Wizard");
remove.add("Azorius Signet");
remove.add("Bog Initiate");
remove.add("Boros Signet");
remove.add("Celestial Prism");
remove.add("Dimir Signet");
remove.add("Fire Sprites");
remove.add("Fyndhorn Elder");
remove.add("Gilded Lotus");
remove.add("Golgari Signet");
remove.add("Greenweaver Druid");
remove.add("Gruul Signet");
remove.add("Helionaut");
remove.add("Izzet Signet");
remove.add("Knotvine Mystic");
remove.add("Mana Cylix");
remove.add("Mana Prism");
remove.add("Nantuko Elder");
remove.add("Nomadic Elf");
remove.add("Orochi Leafcaller");
remove.add("Orzhov Signet");
remove.add("Prismatic Lens");
remove.add("Rakdos Signet");
remove.add("Sea Scryer");
remove.add("Selesnya Signet");
remove.add("Simic Signet");
remove.add("Sisay's Ring");
remove.add("Skyshroud Elf");
remove.add("Ur-Golem's Eye");
remove.add("Viridian Acolyte");
remove.add("Worn Powerstone");
final ArrayList<Card> goodLand = new ArrayList<Card>();
//goodLand.add("Faerie Conclave");
//goodLand.add("Forbidding Watchtower");
//goodLand.add("Treetop Village");
CardList out = new CardList();
if (colors == 3)
{
out = list.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
ArrayList<String> list = CardUtil.getColors(c);
if (list.size() == 3)
{
if (!list.contains(color1) || !list.contains(color2) || !list.contains(color3))
return false;
}
else if (list.size() == 2)
{
if (!(list.contains(color1) && list.contains(color2)) &&
!(list.contains(color1) && list.contains(color3)) &&
!(list.contains(color2) && list.contains(color3)))
return false;
}
return CardUtil.getColors(c).size() <= 3 &&
!c.isLand() && //no land
!remove.contains(c.getName()) || //OR very important
goodLand.contains(c.getName());
}
});
}
else if (colors == 5)
{
out = list.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return CardUtil.getColors(c).size() >= 2 && //only get multicolored cards
!c.isLand() && //no land
!remove.contains(c.getName()) || //OR very important
goodLand.contains(c.getName());
}
});
}
return out;
}//filterBadCards()
public static void main(String[] args)
{
GenerateConstructedMultiColorDeck g = new GenerateConstructedMultiColorDeck();
for(int i = 0; i < 10; i++)
{
System.out.println("***GENERATING DECK***");
CardList c = g.generate3ColorDeck();
System.out.println(c.getType("Creature").size() +" - " +c.size());
for (int j=0; j<c.size();j++ ){
System.out.println(c.get(j).getName());
}
System.out.println("***DECK GENERATED***");
}
System.exit(1);
}//main
}

212
src/GenerateDraftDeck.java Normal file
View File

@@ -0,0 +1,212 @@
import java.util.*;
public class GenerateDraftDeck
{
private static Map<String,String> map = new HashMap<String,String>();
static
{
map.put(Constant.Color.Black , "Swamp");
map.put(Constant.Color.Blue , "Island");
map.put(Constant.Color.Green , "Forest");
map.put(Constant.Color.Red , "Mountain");
map.put(Constant.Color.White , "Plains");
}
public static void main(String[] args)
{
CardList cardPool = new CardList();
ReadBoosterPack booster = new ReadBoosterPack();
for(int outer = 0; outer < 10000; outer++)
{
cardPool.clear();
for(int i = 0; i < 21; i++)
cardPool.addAll(booster.getBoosterPack().toArray());
makeDeck7(cardPool);
if(cardPool.size() != 205)
{
System.out.println(cardPool.size() +" should be ");
break;
}
}//for outer
}
//Deck[] size is 7
public static Deck[] makeDeck7(CardList cardPool)
{
Deck[] out = new Deck[5];
//int index = 0; // unused
for(int i = 0; i < out.length; i++)
out[i] = makeAndTestDeck(cardPool);
test(out);
return out;
}//makeDeck7()
public static void test(Deck[] deck)
{
for(int i = 0; i < deck.length; i++)
{
if(deck[i] == null || deck[i].countMain() != 40)
throw new RuntimeException("GenerateDraftDeck : test() error, deck is wrong");
}
}
//returned Deck may be null
//this method changes cardPool, and takes cards out of it
//the remaining cards in cardPool are unused
public static Deck makeAndTestDeck(CardList cardPool)
{
CardList test = makeDeck(cardPool, 11, Constant.GameType.Draft);
if(test == null)
{
for(int i = 0; i < 100; i++)
test = makeDeck(cardPool, 11, Constant.GameType.Draft);
}
if(test == null)
return null;
//convert CardList into Deck
//remove cards from cardPool
Deck out = new Deck(Constant.GameType.Draft);
for(int i = 0; i < test.size(); i++)
{
cardPool.remove(test.get(i));
out.addMain(test.get(i).getName());
}
return out;
}//makeAndTestDeck()
public static CardList makeDeck(CardList cardPool, int minCreatureCount, String gameType)
{
CardList test = null;
boolean pass = false;
for(int i = 0; i < 5; i++)
{
test = make2ColorDeck(new CardList(cardPool.toArray()));
if(minCreatureCount <= test.getType("Creature").size())
{
pass = true;
break;
}
}//for
if((! pass) || (test.size() != 40))
return null;
return test;
}//makeDeck()
private static CardList make2ColorDeck(CardList in)
{
final ArrayList<String> remove = new ArrayList<String>();
remove.add("Force of Savagery");
remove.add("Darksteel Colossus");
remove.add("Jokulhaups");
remove.add("Steel Wall");
remove.add("Ornithopter");
remove.add("Sarcomite Myr");
in = in.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return CardUtil.getColors(c).size() == 1 && !remove.contains(c.getName());
}
});
String[] color = get2Colors();
CardList out = new CardList();
out.addAll(CardListUtil.getColor(in, color[0]).toArray());
out.addAll(CardListUtil.getColor(in, color[1]).toArray());
CardList trim = new CardList();
for(int i = 0; i < 22 && i < out.size(); i++)
trim.add(out.get(i));
addLand(trim, color);
return trim;
}
//the 2 colors will be different
private static String[] get2Colors()
{
int a;
int b;
do{
a = CardUtil.getRandomIndex(Constant.Color.onlyColors);
b = CardUtil.getRandomIndex(Constant.Color.onlyColors);
}while(a == b);//do not want to get the same color twice
String color1 = Constant.Color.onlyColors[a];
String color2 = Constant.Color.onlyColors[b];
return new String[] {color1, color2};
}//get2Colors()
private static void addLand(CardList list, String[] color)
{
Card land;
for(int i = 0; i < 9; i++)
{
land = AllZone.CardFactory.getCard(map.get(color[0]).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(map.get(color[1]).toString(), Constant.Player.Computer);
list.add(land);
}
}//addLand()
}
/*
import java.util.*;
public class GenerateSealedDeck
{
private String color1;
private String color2;
public CardList generateDeck()
{
CardList deck;
do{
deck = get2ColorDeck();
}while(deck.getType("Creature").size() < 16);
addLand(deck);
if(deck.size() != 40)
throw new RuntimeException("GenerateSealedDeck() : generateDeck() error, deck size it not 40, deck size is " +deck.size());
return deck;
}
private CardList get2ColorDeck()
{
ReadBoosterPack booster = new ReadBoosterPack();
CardList deck;
do{
deck = get2Colors(booster.getBoosterPack5());
}while(deck.size() < 22);
CardList out = new CardList();
deck.shuffle();
//trim deck size down to 22 cards, presumes 18 land
for(int i = 0; i < 22; i++)
out.add(deck.get(i));
return out;
}
}
*/

151
src/GenerateSealedDeck.java Normal file
View File

@@ -0,0 +1,151 @@
import java.util.*;
public class GenerateSealedDeck
{
private String color1;
private String color2;
private Map<String,String> map = new HashMap<String,String>();
public GenerateSealedDeck() {setupMap();}
private void setupMap()
{
map.put(Constant.Color.Black , "Swamp");
map.put(Constant.Color.Blue , "Island");
map.put(Constant.Color.Green , "Forest");
map.put(Constant.Color.Red , "Mountain");
map.put(Constant.Color.White , "Plains");
}
public CardList generateDeck()
{
CardList deck;
do{
deck = get2ColorDeck();
}while(deck.getType("Creature").size() < 12 || 16 < deck.getType("Creature").size());
addLand(deck);
if(deck.size() != 40)
throw new RuntimeException("GenerateSealedDeck() : generateDeck() error, deck size it not 40, deck size is " +deck.size());
return deck;
}
private void addLand(CardList list)
{
Card land;
for(int i = 0; i < 9; i++)
{
land = AllZone.CardFactory.getCard(map.get(color1).toString(), Constant.Player.Computer);
list.add(land);
land = AllZone.CardFactory.getCard(map.get(color2).toString(), Constant.Player.Computer);
list.add(land);
}
}//addLand()
private CardList get2ColorDeck()
{
ReadBoosterPack booster = new ReadBoosterPack();
CardList deck;
do{
deck = get2Colors(booster.getBoosterPack5());
}while(deck.size() < 22);
CardList out = new CardList();
deck.shuffle();
//trim deck size down to 22 cards, presumes 18 land
for(int i = 0; i < 22 && i < deck.size(); i++)
out.add(deck.get(i));
return out;
}
private CardList get2Colors(CardList in)
{
int a;
int b;
do{
a = CardUtil.getRandomIndex(Constant.Color.onlyColors);
b = CardUtil.getRandomIndex(Constant.Color.onlyColors);
}while(a == b);//do not want to get the same color twice
color1 = Constant.Color.onlyColors[a];
color2 = Constant.Color.onlyColors[b];
CardList out = new CardList();
out.addAll(CardListUtil.getColor(in, color1).toArray());
out.addAll(CardListUtil.getColor(in, color2).toArray());
CardList artifact = in.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
//is this really a colorless artifact and not something
//wierd like Sarcomite Myr which is a colored artifact
return c.isArtifact() &&
CardUtil.getColors(c).contains(Constant.Color.Colorless) &&
!Gui_NewGame.removeArtifacts.isSelected();
}
});
out.addAll(artifact.toArray());
out = out.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
if(c.isCreature() &&
c.getNetAttack() <= 1 &&
Gui_NewGame.removeSmallCreatures.isSelected())
{
return false;
}
return true;
}
});
out = filterBadCards(out);
return out;
}
private CardList filterBadCards(CardList list)
{
//remove "bad" and multi-colored cards
final ArrayList<String> remove = new ArrayList<String>();
remove.add("Force of Savagery");
remove.add("Darksteel Colossus");
remove.add("Jokulhaups");
remove.add("Steel Wall");
remove.add("Ornithopter");
remove.add("Sarcomite Myr");
CardList out = list.filter(new CardListFilter()
{
public boolean addCard(Card c)
{
return CardUtil.getColors(c).size() == 1 && !remove.contains(c.getName());
}
});
return out;
}//filterBadCards()
public static void main(String[] args)
{
GenerateSealedDeck g = new GenerateSealedDeck();
for(int i = 0; i < 100; i++)
{
System.out.println(i);
g.generateDeck();
}
/*
for(int i = 0; i < 10; i++)
{
CardList c = g.generateDeck();
System.out.println(c.getType("Creature").size());
}
*/
}
}

313
src/GuiDisplay.java Normal file
View File

@@ -0,0 +1,313 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class GuiDisplay extends JFrame {
private static final long serialVersionUID = -7044669689870299753L;
private JScrollPane jScrollPane1 = new JScrollPane();
private JTextArea messageArea = new JTextArea();
private JPanel buttonPanel = new JPanel();
private FlowLayout flowLayout1 = new FlowLayout();
private JPanel jPanel2 = new JPanel();
private JLabel oppLifeLabel = new JLabel();
private BorderLayout borderLayout1 = new BorderLayout();
private JPanel jPanel3 = new JPanel();
private BorderLayout borderLayout2 = new BorderLayout();
private JScrollPane jScrollPane3 = new JScrollPane();
private JPanel jPanel4 = new JPanel();
private BorderLayout borderLayout3 = new BorderLayout();
private JLabel playerLifeLabel = new JLabel();
@SuppressWarnings("unused")
// border1
private Border border1;
private JPanel jPanel5 = new JPanel();
private JScrollPane jScrollPane4 = new JScrollPane();
private JPanel jPanel6 = new JPanel();
private GridLayout gridLayout1 = new GridLayout();
private JPanel oppLandPanel = new JPanel();
private JPanel oppCreaturePanel = new JPanel();
private JPanel playerCreaturePanel = new JPanel();
private JPanel playerLandPanel = new JPanel();
private JPanel playerHandPanel = new JPanel();
private JLabel jLabel3 = new JLabel();
private JPanel jPanel12 = new JPanel();
private GridLayout gridLayout2 = new GridLayout();
private JPanel jPanel13 = new JPanel();
private JPanel jPanel14 = new JPanel();
private JPanel jPanel15 = new JPanel();
private JPanel jPanel16 = new JPanel();
private JPanel jPanel17 = new JPanel();
private JLabel jLabel4 = new JLabel();
private JLabel jLabel5 = new JLabel();
private JLabel jLabel6 = new JLabel();
private JLabel jLabel7 = new JLabel();
private JLabel jLabel8 = new JLabel();
private JPanel jPanel18 = new JPanel();
private JLabel jLabel9 = new JLabel();
private JPanel jPanel19 = new JPanel();
private Border border2;
private TitledBorder titledBorder1;
private BorderLayout borderLayout4 = new BorderLayout();
private JLabel jLabel11 = new JLabel();
private JLabel jLabel12 = new JLabel();
private JLabel playerHandLabel = new JLabel();
private JLabel playerLibraryLabel = new JLabel();
private JLabel playerGraveLabel = new JLabel();
private JScrollPane jScrollPane2 = new JScrollPane();
private JLabel jLabel18 = new JLabel();
private JLabel jLabel19 = new JLabel();
private JLabel jLabel20 = new JLabel();
private JLabel oppHandLabel = new JLabel();
private JLabel oppLibraryLabel = new JLabel();
private JLabel oppGraveLabel = new JLabel();
private JPanel stackPanel = new JPanel();
private GridLayout gridLayout3 = new GridLayout();
private JPanel jPanel9 = new JPanel();
private JPanel picturePanel = new JPanel();
private JTextArea combatArea = new JTextArea();
private GridLayout gridLayout4 = new GridLayout();
private JPanel jPanel7 = new JPanel();
private GridLayout gridLayout5 = new GridLayout();
private JLabel cdLabel1 = new JLabel();
private JLabel cdLabel2 = new JLabel();
private JLabel cdLabel3 = new JLabel();
private JLabel cdLabel4 = new JLabel();
private JLabel cdLabel5 = new JLabel();
private JScrollPane jScrollPane5 = new JScrollPane();
private JTextArea cdArea = new JTextArea();
public static void main(String[] args) {
GuiDisplay g = new GuiDisplay();
//Use both so that when "un"maximizing, the frame isn't tiny
g.setSize(1024, 740);
g.setExtendedState(Frame.MAXIMIZED_BOTH);
g.setVisible(true);
}
public GuiDisplay() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
}
private void jbInit() throws Exception {
border1 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
border2 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder1 = new TitledBorder(border2, "Stack");
this.getContentPane().setLayout(null);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
buttonPanel.setBorder(BorderFactory.createEtchedBorder());
buttonPanel.setBounds(new Rectangle(12, 105, 214, 38));
buttonPanel.setLayout(flowLayout1);
jPanel2.setBorder(new TitledBorder(
BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)), "Computer"));
jPanel2.setBounds(new Rectangle(137, 149, 89, 78));
jPanel2.setLayout(borderLayout1);
oppLifeLabel.setFont(new java.awt.Font("Dialog", 0, 47));
oppLifeLabel.setToolTipText("Click here to target the computer");
oppLifeLabel.setHorizontalAlignment(SwingConstants.CENTER);
oppLifeLabel.setText("20");
jPanel3.setBorder(new TitledBorder(
BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)), "Combat"));
jPanel3.setBounds(new Rectangle(6, 401, 230, 169));
jPanel3.setLayout(borderLayout2);
jPanel4.setBorder(new TitledBorder(
BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)), "Human"));
jPanel4.setBounds(new Rectangle(154, 604, 90, 83));
jPanel4.setLayout(borderLayout3);
playerLifeLabel.setFont(new java.awt.Font("Dialog", 0, 47));
playerLifeLabel.setToolTipText("Click here to target yourself");
playerLifeLabel.setHorizontalAlignment(SwingConstants.CENTER);
playerLifeLabel.setText("20");
jScrollPane3.setBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)));
jPanel5.setBounds(new Rectangle(776, 12, 214, 663));
jPanel5.setLayout(gridLayout3);
jPanel6.setLayout(gridLayout1);
gridLayout1.setHgap(10);
gridLayout1.setRows(5);
gridLayout1.setVgap(10);
oppLandPanel.setBorder(BorderFactory.createEtchedBorder());
oppLandPanel.setToolTipText("Computer\'s Land");
oppCreaturePanel.setBorder(BorderFactory.createEtchedBorder());
oppCreaturePanel.setToolTipText("Computer\'s Creatures");
playerHandPanel.setBorder(BorderFactory.createEtchedBorder());
playerHandPanel.setToolTipText("Cards in your hand");
playerCreaturePanel.setBorder(BorderFactory.createEtchedBorder());
playerCreaturePanel.setToolTipText("Your Creatures");
playerLandPanel.setBorder(BorderFactory.createEtchedBorder());
playerLandPanel.setToolTipText("Your Land");
jLabel3.setFont(new java.awt.Font("Dialog", 0, 18));
jLabel3.setText("Hand: ");
jLabel3.setBounds(new Rectangle(39, 608, 60, 28));
jPanel12.setToolTipText("Mana Pool");
jPanel12.setBounds(new Rectangle(1, 571, 246, 30));
jPanel12.setLayout(gridLayout2);
gridLayout2.setColumns(6);
gridLayout2.setHgap(5);
gridLayout2.setRows(0);
jLabel4.setFont(new java.awt.Font("Dialog", 0, 16));
jLabel4.setHorizontalAlignment(SwingConstants.CENTER);
jLabel4.setText("10");
jPanel13.setBackground(Color.white);
jLabel5.setFont(new java.awt.Font("Dialog", 0, 16));
jLabel5.setForeground(Color.white);
jLabel5.setText("10");
jPanel14.setBackground(Color.black);
jPanel14.setForeground(Color.white);
jPanel15.setBackground(Color.blue);
jPanel15.setToolTipText("");
jLabel6.setFont(new java.awt.Font("Dialog", 0, 16));
jLabel6.setForeground(Color.white);
jLabel6.setText("10");
jLabel7.setFont(new java.awt.Font("Dialog", 0, 16));
jLabel7.setForeground(Color.white);
jLabel7.setText("10");
jPanel16.setBackground(Color.red);
jLabel8.setFont(new java.awt.Font("Dialog", 0, 16));
jLabel8.setForeground(Color.white);
jLabel8.setText("10");
jPanel17.setBackground(Color.gray);
jLabel9.setFont(new java.awt.Font("Dialog", 0, 16));
jLabel9.setText("10");
jPanel18.setBackground(Color.green);
jScrollPane4.setBounds(new Rectangle(244, 12, 525, 685));
jScrollPane1.setBounds(new Rectangle(12, 6, 214, 91));
jPanel19.setBorder(titledBorder1);
jPanel19.setBounds(new Rectangle(6, 233, 230, 169));
jPanel19.setLayout(borderLayout4);
jLabel11.setFont(new java.awt.Font("Dialog", 0, 18));
jLabel11.setText("Library: ");
jLabel11.setBounds(new Rectangle(39, 639, 71, 23));
jLabel12.setFont(new java.awt.Font("Dialog", 0, 18));
jLabel12.setText("Grave: ");
jLabel12.setBounds(new Rectangle(39, 664, 60, 26));
playerHandLabel.setFont(new java.awt.Font("Dialog", 0, 18));
playerHandLabel.setHorizontalAlignment(SwingConstants.RIGHT);
playerHandLabel.setText("7");
playerHandLabel.setBounds(new Rectangle(91, 608, 32, 28));
playerLibraryLabel.setFont(new java.awt.Font("Dialog", 0, 18));
playerLibraryLabel.setHorizontalAlignment(SwingConstants.RIGHT);
playerLibraryLabel.setText("32");
playerLibraryLabel.setBounds(new Rectangle(91, 639, 32, 23));
playerGraveLabel.setFont(new java.awt.Font("Dialog", 0, 18));
playerGraveLabel.setHorizontalAlignment(SwingConstants.RIGHT);
playerGraveLabel.setText("2");
playerGraveLabel.setBounds(new Rectangle(91, 664, 32, 26));
jScrollPane2.setBorder(BorderFactory.createEtchedBorder());
jLabel18.setFont(new java.awt.Font("Dialog", 0, 18));
jLabel18.setText("Hand:");
jLabel18.setBounds(new Rectangle(28, 152, 66, 20));
jLabel19.setFont(new java.awt.Font("Dialog", 0, 18));
jLabel19.setText("Library:");
jLabel19.setBounds(new Rectangle(28, 181, 70, 20));
jLabel20.setFont(new java.awt.Font("Dialog", 0, 18));
jLabel20.setText("Grave:");
jLabel20.setBounds(new Rectangle(28, 210, 76, 20));
oppHandLabel.setFont(new java.awt.Font("Dialog", 0, 18));
oppHandLabel.setHorizontalAlignment(SwingConstants.RIGHT);
oppHandLabel.setText("6");
oppHandLabel.setBounds(new Rectangle(59, 152, 55, 20));
oppLibraryLabel.setFont(new java.awt.Font("Dialog", 0, 18));
oppLibraryLabel.setHorizontalAlignment(SwingConstants.RIGHT);
oppLibraryLabel.setText("30");
oppLibraryLabel.setBounds(new Rectangle(59, 181, 55, 20));
oppGraveLabel.setFont(new java.awt.Font("Dialog", 0, 18));
oppGraveLabel.setHorizontalAlignment(SwingConstants.RIGHT);
oppGraveLabel.setText("2");
oppGraveLabel.setBounds(new Rectangle(59, 210, 55, 20));
gridLayout3.setColumns(1);
gridLayout3.setRows(2);
gridLayout3.setVgap(5);
picturePanel.setBorder(BorderFactory.createEtchedBorder());
jPanel9.setBorder(BorderFactory.createEtchedBorder());
jPanel9.setLayout(gridLayout4);
gridLayout4.setColumns(1);
gridLayout4.setRows(2);
jPanel7.setLayout(gridLayout5);
gridLayout5.setColumns(1);
gridLayout5.setRows(5);
cdArea.setLineWrap(true);
cdArea.setWrapStyleWord(true);
cdLabel4.setHorizontalAlignment(SwingConstants.LEFT);
cdLabel1.setHorizontalAlignment(SwingConstants.CENTER);
cdLabel2.setHorizontalAlignment(SwingConstants.CENTER);
cdLabel3.setHorizontalAlignment(SwingConstants.CENTER);
cdLabel5.setHorizontalAlignment(SwingConstants.LEFT);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(buttonPanel, null);
this.getContentPane().add(jScrollPane4, null);
this.getContentPane().add(jPanel3, null);
jPanel3.add(jScrollPane3, BorderLayout.CENTER);
jPanel12.add(jPanel13, null);
jPanel13.add(jLabel4, null);
jPanel12.add(jPanel14, null);
jPanel14.add(jLabel5, null);
jPanel12.add(jPanel15, null);
jPanel15.add(jLabel6, null);
jPanel12.add(jPanel16, null);
jPanel16.add(jLabel7, null);
jPanel12.add(jPanel18, null);
jPanel18.add(jLabel9, null);
jPanel12.add(jPanel17, null);
jPanel17.add(jLabel8, null);
this.getContentPane().add(jLabel12, null);
this.getContentPane().add(playerHandLabel, null);
this.getContentPane().add(jLabel3, null);
this.getContentPane().add(jLabel11, null);
this.getContentPane().add(playerLibraryLabel, null);
this.getContentPane().add(playerGraveLabel, null);
this.getContentPane().add(jLabel19, null);
this.getContentPane().add(jLabel18, null);
this.getContentPane().add(oppHandLabel, null);
this.getContentPane().add(jLabel20, null);
this.getContentPane().add(oppLibraryLabel, null);
this.getContentPane().add(oppGraveLabel, null);
this.getContentPane().add(jPanel5, null);
this.getContentPane().add(jPanel2, null);
jPanel2.add(oppLifeLabel, BorderLayout.CENTER);
this.getContentPane().add(jPanel19, null);
jPanel19.add(jScrollPane2, BorderLayout.CENTER);
jScrollPane2.getViewport().add(stackPanel, null);
this.getContentPane().add(jPanel4, null);
jPanel4.add(playerLifeLabel, BorderLayout.CENTER);
this.getContentPane().add(jPanel12, null);
jScrollPane4.getViewport().add(jPanel6, null);
jPanel6.add(oppLandPanel, null);
jPanel6.add(oppCreaturePanel, null);
jPanel6.add(playerCreaturePanel, null);
jPanel6.add(playerLandPanel, null);
jPanel6.add(playerHandPanel, null);
jScrollPane1.getViewport().add(messageArea, null);
jPanel5.add(jPanel9, null);
jScrollPane3.getViewport().add(combatArea, null);
jPanel7.add(cdLabel1, null);
jPanel7.add(cdLabel2, null);
jPanel7.add(cdLabel3, null);
jPanel7.add(cdLabel4, null);
jPanel7.add(cdLabel5, null);
jPanel9.add(jPanel7, null);
jPanel9.add(jScrollPane5, null);
jPanel5.add(picturePanel, null);
jScrollPane5.getViewport().add(cdArea, null);
}
}

961
src/GuiDisplay2.java Normal file
View File

@@ -0,0 +1,961 @@
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import forge.gui.ListChooser;
import forge.properties.ForgeProps;
import forge.properties.NewConstants;
public class GuiDisplay2 extends javax.swing.JFrame implements Display, NewConstants {
private static final long serialVersionUID = 8974795337536720207L;
private GuiInput inputControl;
public static JCheckBoxMenuItem eotCheckboxForMenu = new JCheckBoxMenuItem("Stop at End of Turn", false);
public boolean stopEOT() {
return eotCheckboxForMenu.isSelected();
}
public GuiDisplay2() {
initComponents();
addObservers();
addListeners();
addMenu();
inputControl = new GuiInput();
}
@Override
public void setVisible(boolean visible) {
if(visible) {
//causes an error if put in the constructor, causes some random null pointer exception
AllZone.InputControl.updateObservers();
//Use both so that when "un"maximizing, the frame isn't tiny
setSize(1024, 740);
setExtendedState(Frame.MAXIMIZED_BOTH);
}
super.setVisible(visible);
}
public void assignDamage(Card attacker, CardList blockers, int damage) {
new Gui_MultipleBlockers(attacker, blockers, damage, this);
}
private void addMenu() {
JMenuItem humanGraveyard = new JMenuItem("View Graveyard");
humanGraveyard.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Card c[] = AllZone.Human_Graveyard.getCards();
if(AllZone.NameChanger.shouldChangeCardName()) c = AllZone.NameChanger.changeCard(c);
if(c.length == 0) AllZone.Display.getChoiceOptional("Player's Grave", new String[] {"no cards"});
else AllZone.Display.getChoiceOptional("Player's Grave", c);
}
});
JMenuItem computerGraveyard = new JMenuItem("Computer - View Graveyard");
computerGraveyard.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Card c[] = AllZone.Computer_Graveyard.getCards();
if(AllZone.NameChanger.shouldChangeCardName()) c = AllZone.NameChanger.changeCard(c);
if(c.length == 0) AllZone.Display.getChoiceOptional("Computer's Grave", new String[] {"no cards"});
else AllZone.Display.getChoiceOptional("Computer's Grave", c);
}
});
JMenuItem concedeGame = new JMenuItem("Concede Game");
concedeGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
dispose();
Constant.Runtime.WinLose.addLose();
new Gui_WinLose();
}
});
JMenuItem gameMenu = new JMenu("Menu");
gameMenu.add(humanGraveyard);
gameMenu.add(computerGraveyard);
// gameMenu.add(this.eotCheckboxForMenu); // The static field GuiDisplay2.eotCheckboxForMenu should be accessed in a static way
gameMenu.add(GuiDisplay2.eotCheckboxForMenu);
gameMenu.add(new JSeparator());
gameMenu.add(concedeGame);
JMenuBar menuBar = new JMenuBar();
menuBar.add(gameMenu);
menuBar.add(new MenuItem_HowToPlay());
this.setJMenuBar(menuBar);
}//addMenu()
public MyButton getButtonOK() {
MyButton ok = new MyButton() {
public void select() {
inputControl.selectButtonOK();
}
public boolean isSelectable() {
return okButton.isEnabled();
}
public void setSelectable(boolean b) {
okButton.setEnabled(b);
}
public String getText() {
return okButton.getText();
}
public void setText(String text) {
okButton.setText(text);
}
public void reset() {
okButton.setText("OK");
}
};
return ok;
}//getButtonOK()
public MyButton getButtonCancel() {
MyButton cancel = new MyButton() {
public void select() {
inputControl.selectButtonCancel();
}
public boolean isSelectable() {
return cancelButton.isEnabled();
}
public void setSelectable(boolean b) {
cancelButton.setEnabled(b);
}
public String getText() {
return cancelButton.getText();
}
public void setText(String text) {
cancelButton.setText(text);
}
public void reset() {
cancelButton.setText("Cancel");
}
};
return cancel;
}//getButtonCancel()
public void showCombat(String message) {
combatArea.setText(message);
}
public void showMessage(String s) {
messageArea.setText(s);
}
//returned Object could be null
public <T> T getChoiceOptional(String message, T[] choices) {
ListChooser<T> c = new ListChooser<T>(message, 0, 1, choices);
final JList list = c.getJList();
if(choices[0] instanceof Card) {
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent ev) {
if(list.getSelectedValue() instanceof Card) updateCardDetail((Card) list.getSelectedValue());
}
});
}
if(!c.show()) return null;
return c.getSelectedValue();
}//getChoiceOptional()
// returned Object will never be null
public <T> T getChoice(String message, T[] choices) {
ListChooser<T> c = new ListChooser<T>(message, 1, choices);
final JList list = c.getJList();
if(choices[0] instanceof Card) {
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent ev) {
if(list.getSelectedValue() instanceof Card) updateCardDetail((Card) list.getSelectedValue());
}
});
}
c.show();
return c.getSelectedValue();
}//getChoice()
private void addListeners() {
//mouse Card Detail
playerHandPanel.addMouseMotionListener(GuiDisplayUtil.getCardDetailMouse(this));
playerLandPanel.addMouseMotionListener(GuiDisplayUtil.getCardDetailMouse(this));
playerCreaturePanel.addMouseMotionListener(GuiDisplayUtil.getCardDetailMouse(this));
oppLandPanel.addMouseMotionListener(GuiDisplayUtil.getCardDetailMouse(this));
oppCreaturePanel.addMouseMotionListener(GuiDisplayUtil.getCardDetailMouse(this));
//opponent life mouse listener
oppLifeLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
inputControl.selectPlayer(Constant.Player.Computer);
}
});
//self life mouse listener
playerLifeLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
inputControl.selectPlayer(Constant.Player.Human);
}
});
//self play (land) ---- Mouse
playerLandPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Object o = playerLandPanel.getComponentAt(e.getPoint());
if(o instanceof CardPanel) {
CardPanel cardPanel = (CardPanel) o;
inputControl.selectCard(cardPanel.getCard(), AllZone.Human_Play);
}
}
});
//self play (no land) ---- Mouse
playerCreaturePanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Object o = playerCreaturePanel.getComponentAt(e.getPoint());
if(o instanceof CardPanel) {
CardPanel cardPanel = (CardPanel) o;
inputControl.selectCard(cardPanel.getCard(), AllZone.Human_Play);
}
}
});
//self hand ---- Mouse
playerHandPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Object o = playerHandPanel.getComponentAt(e.getPoint());
if(o instanceof CardPanel) {
CardPanel cardPanel = (CardPanel) o;
inputControl.selectCard(cardPanel.getCard(), AllZone.Human_Hand);
}
}
});
//*****************************************************************
//computer
//computer play (land) ---- Mouse
oppLandPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Object o = oppLandPanel.getComponentAt(e.getPoint());
if(o instanceof CardPanel) {
CardPanel cardPanel = (CardPanel) o;
inputControl.selectCard(cardPanel.getCard(), AllZone.Computer_Play);
}
}
});
//computer play (no land) ---- Mouse
oppCreaturePanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Object o = oppCreaturePanel.getComponentAt(e.getPoint());
if(o instanceof CardPanel) {
CardPanel cardPanel = (CardPanel) o;
inputControl.selectCard(cardPanel.getCard(), AllZone.Computer_Play);
}
}
});
}//addListener()
public void updateCardDetail(Card c) {
if(c == null) return;
cdLabel1.setText("");
cdLabel2.setText("");
cdLabel3.setText("");
cdLabel4.setText("");
cdLabel5.setText("");
cdArea.setText("");
//do not change the name of tokens
if(!(c.isToken() || c.getName().equals(""))) {
//change name, probably need to fix this
//cards that change creatures like Angelic Blessing don't show
//that the creature has flying, or Coastal Hornclaw's flying ability
//c = AllZone.CardFactory.copyCard(c);
if(AllZone.NameChanger.shouldChangeCardName()) c = AllZone.NameChanger.changeCard(c);
}
if(c.isLand()) cdLabel1.setText(c.getName());
else cdLabel1.setText(c.getName() + " - " + c.getManaCost());
cdLabel2.setText(GuiDisplayUtil.formatCardType(c));
if(c.isCreature()) {
String stats = "" + c.getNetAttack() + " / " + c.getNetDefense();
cdLabel3.setText(stats);
}
if(c.isCreature()) cdLabel4.setText("Damage: " + c.getDamage() + " Assigned Damage: "
+ c.getAssignedDamage());
if(c.isPlaneswalker()) cdLabel4.setText("Assigned Damage: " + c.getAssignedDamage());
String uniqueID = c.getUniqueNumber() + " ";
cdLabel5.setText("Card ID " + uniqueID);
this.cdArea.setText(c.getText());
cdPanel.setBorder(GuiDisplayUtil.getBorder(c));
//picture
picturePanel.removeAll();
picturePanel.add(GuiDisplayUtil.getPicture(c));
picturePanel.revalidate();
}//updateCardDetail()
private void addObservers() {
//Human Hand, Graveyard, and Library totals
{//make sure to not interfer with anything below, since this is a very long method
Observer o = new Observer() {
public void update(Observable a, Object b) {
playerHandLabel.setText("" + AllZone.Human_Hand.getCards().length);
playerGraveLabel.setText("" + AllZone.Human_Graveyard.getCards().length);
playerLibraryLabel.setText("" + AllZone.Human_Library.getCards().length);
}
};
AllZone.Human_Hand.addObserver(o);
AllZone.Human_Graveyard.addObserver(o);
AllZone.Human_Library.addObserver(o);
}
//opponent Hand, Graveyard, and Library totals
{//make sure to not interfer with anything below, since this is a very long method
Observer o = new Observer() {
public void update(Observable a, Object b) {
oppHandLabel.setText("" + AllZone.Computer_Hand.getCards().length);
oppGraveLabel.setText("" + AllZone.Computer_Graveyard.getCards().length);
oppLibraryLabel.setText("" + AllZone.Computer_Library.getCards().length);
}
};
AllZone.Computer_Hand.addObserver(o);
AllZone.Computer_Graveyard.addObserver(o);
AllZone.Computer_Library.addObserver(o);
}
//opponent life
oppLifeLabel.setText("" + AllZone.Computer_Life.getLife());
AllZone.Computer_Life.addObserver(new Observer() {
public void update(Observable a, Object b) {
int life = AllZone.Computer_Life.getLife();
oppLifeLabel.setText("" + life);
}
});
AllZone.Computer_Life.updateObservers();
//player life
playerLifeLabel.setText("" + AllZone.Human_Life.getLife());
AllZone.Human_Life.addObserver(new Observer() {
public void update(Observable a, Object b) {
int life = AllZone.Human_Life.getLife();
playerLifeLabel.setText("" + life);
}
});
AllZone.Human_Life.updateObservers();
//stack
AllZone.Stack.addObserver(new Observer() {
public void update(Observable a, Object b) {
stackPanel.removeAll();
MagicStack stack = AllZone.Stack;
int count = 1;
JLabel label;
for(int i = stack.size() - 1; 0 <= i; i--) {
String text = stack.peek(i).getStackDescription();
//change card name
if(AllZone.NameChanger.shouldChangeCardName()) {
Card c = stack.peek(i).getSourceCard();
text = AllZone.NameChanger.changeString(c, text);
}
label = new JLabel("" + (count++) + ". " + text);
//update card detail
final CardPanel cardPanel = new CardPanel(stack.peek(i).getSourceCard());
cardPanel.setLayout(new BorderLayout());
cardPanel.add(label);
cardPanel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent me) {
GuiDisplay2.this.updateCardDetail(cardPanel.getCard());
}//mouseMoved
});
stackPanel.add(cardPanel);
}
stackPanel.revalidate();
stackPanel.repaint();
}
});
AllZone.Stack.updateObservers();
//END, stack
//self hand
AllZone.Human_Hand.addObserver(new Observer() {
public void update(Observable a, Object b) {
PlayerZone pZone = (PlayerZone) a;
JPanel p = playerHandPanel;
p.removeAll();
Card c[] = pZone.getCards();
//change card names
if(AllZone.NameChanger.shouldChangeCardName()) {
AllZone.Human_Hand.setUpdate(false);
c = AllZone.NameChanger.changeCard(c);
AllZone.Human_Hand.setUpdate(true);
}
JPanel panel;
for(int i = 0; i < c.length; i++) {
panel = GuiDisplayUtil.getCardPanel(c[i]);
p.add(panel);
}
p.revalidate();
p.repaint();
}
});
AllZone.Human_Hand.updateObservers();
//END, self hand
//self play (land)
AllZone.Human_Play.addObserver(new Observer() {
public void update(Observable a, Object b) {
//PlayerZone pZone = (PlayerZone)a; //unused
JPanel p = playerLandPanel;
p.removeAll();
Card[] c = AllZone.Human_Play.getCards();
//change card names
if(AllZone.NameChanger.shouldChangeCardName()) {
AllZone.Human_Play.setUpdate(false);
c = AllZone.NameChanger.changeCard(c);
AllZone.Human_Play.setUpdate(true);
}
GuiDisplayUtil.setupLandPanel(p, c);
p.revalidate();
p.repaint();
}
});
AllZone.Human_Play.updateObservers();
//END - self play (only land)
//self play (no land)
AllZone.Human_Play.addObserver(new Observer() {
public void update(Observable a, Object b) {
//PlayerZone pZone = (PlayerZone)a; //unused
JPanel p = playerCreaturePanel;
p.removeAll();
Card[] c = AllZone.Human_Play.getCards();
//change card names
if(AllZone.NameChanger.shouldChangeCardName()) {
AllZone.Human_Play.setUpdate(false);
c = AllZone.NameChanger.changeCard(c);
AllZone.Human_Play.setUpdate(true);
}
GuiDisplayUtil.setupNoLandPanel(p, c);
p.revalidate();
p.repaint();
}
});
AllZone.Human_Play.updateObservers();
//END - self play (no land)
//computer play (no land)
AllZone.Computer_Play.addObserver(new Observer() {
public void update(Observable a, Object b) {
//PlayerZone pZone = (PlayerZone)a; //unused
JPanel p = oppCreaturePanel;
p.removeAll();
Card[] c = AllZone.Computer_Play.getCards();
//change card names
if(AllZone.NameChanger.shouldChangeCardName()) {
AllZone.Computer_Play.setUpdate(false);
c = AllZone.NameChanger.changeCard(c);
AllZone.Computer_Play.setUpdate(true);
}
GuiDisplayUtil.setupNoLandPanel(p, c);
p.revalidate();
p.repaint();
}
});
AllZone.Computer_Play.updateObservers();
//END - computer play (no land)
//computer play (land)
AllZone.Computer_Play.addObserver(new Observer() {
public void update(Observable a, Object b) {
//PlayerZone pZone = (PlayerZone)a; //unused
JPanel p = oppLandPanel;
p.removeAll();
Card[] c = AllZone.Computer_Play.getCards();
//change card names
if(AllZone.NameChanger.shouldChangeCardName()) {
AllZone.Computer_Play.setUpdate(false);
c = AllZone.NameChanger.changeCard(c);
AllZone.Computer_Play.setUpdate(true);
}
GuiDisplayUtil.setupLandPanel(p, c);
p.revalidate();
p.repaint();
}
});
AllZone.Computer_Play.updateObservers();
//END - computer play (only land)
}//addObservers()
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code.
* The content of this method is always regenerated by the Form Editor.
*/
private void initComponents()//GEN-BEGIN:initComponents
{
jMenuBar2 = new javax.swing.JMenuBar();
jScrollPane1 = new javax.swing.JScrollPane();
messageArea = new javax.swing.JTextArea();
jPanel1 = new javax.swing.JPanel();
cancelButton = new javax.swing.JButton();
okButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
stackPanel = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
combatArea = new javax.swing.JTextArea();
jPanel5 = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
jPanel6 = new javax.swing.JPanel();
oppLandPanel = new javax.swing.JPanel();
oppCreaturePanel = new javax.swing.JPanel();
playerCreaturePanel = new javax.swing.JPanel();
playerLandPanel = new javax.swing.JPanel();
playerHandPanel = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
oppLifeLabel = new javax.swing.JLabel();
jPanel7 = new javax.swing.JPanel();
playerLifeLabel = new javax.swing.JLabel();
cdPanel = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
cdLabel1 = new javax.swing.JLabel();
cdLabel2 = new javax.swing.JLabel();
cdLabel3 = new javax.swing.JLabel();
cdLabel4 = new javax.swing.JLabel();
cdLabel5 = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
jScrollPane5 = new javax.swing.JScrollPane();
cdArea = new javax.swing.JTextArea();
picturePanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
oppHandLabel = new javax.swing.JLabel();
oppLibraryLabel = new javax.swing.JLabel();
oppGraveLabel = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
playerHandLabel = new javax.swing.JLabel();
playerLibraryLabel = new javax.swing.JLabel();
playerGraveLabel = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
menuBar = new javax.swing.JMenu();
getContentPane().setLayout(null);
setTitle(ForgeProps.getLocalized(LANG.PROGRAM_NAME));
setFont(new java.awt.Font("Times New Roman", 0, 16));
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
messageArea.setEditable(false);
messageArea.setFont(getFont());
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
jScrollPane1.setViewportView(messageArea);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(10, 20, 290, 100);
jPanel1.setBorder(new javax.swing.border.EtchedBorder());
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
jPanel1.add(cancelButton);
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
if(AllZone.Phase.isNeedToNextPhase() == true) {
//for debugging: System.out.println("There better be no nextPhase in the stack.");
AllZone.Phase.setNeedToNextPhase(false);
AllZone.Phase.nextPhase();
}
}
});
jPanel1.add(okButton);
getContentPane().add(jPanel1);
jPanel1.setBounds(10, 130, 290, 40);
jScrollPane2.setBorder(new javax.swing.border.EtchedBorder());
stackPanel.setLayout(new java.awt.GridLayout(0, 1, 10, 10));
jScrollPane2.setViewportView(stackPanel);
getContentPane().add(jScrollPane2);
jScrollPane2.setBounds(10, 260, 290, 210);
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel2.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Combat"));
combatArea.setEditable(false);
combatArea.setFont(getFont());
combatArea.setLineWrap(true);
combatArea.setWrapStyleWord(true);
jScrollPane3.setViewportView(combatArea);
jPanel2.add(jScrollPane3, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel2);
jPanel2.setBounds(10, 480, 290, 120);
jPanel5.setLayout(new java.awt.BorderLayout());
jPanel5.setBorder(new javax.swing.border.EmptyBorder(new java.awt.Insets(1, 1, 1, 1)));
jPanel6.setLayout(new java.awt.GridLayout(5, 0, 10, 10));
oppLandPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
oppLandPanel.setBorder(new javax.swing.border.EtchedBorder());
jPanel6.add(oppLandPanel);
oppCreaturePanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
oppCreaturePanel.setBorder(new javax.swing.border.EtchedBorder());
jPanel6.add(oppCreaturePanel);
playerCreaturePanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
playerCreaturePanel.setBorder(new javax.swing.border.EtchedBorder());
jPanel6.add(playerCreaturePanel);
playerLandPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
playerLandPanel.setBorder(new javax.swing.border.EtchedBorder());
jPanel6.add(playerLandPanel);
playerHandPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
playerHandPanel.setBorder(new javax.swing.border.EtchedBorder());
jPanel6.add(playerHandPanel);
jScrollPane4.setViewportView(jPanel6);
jPanel5.add(jScrollPane4, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel5);
jPanel5.setBounds(320, 20, 460, 670);
jPanel3.setLayout(new java.awt.BorderLayout());
jPanel3.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Computer"));
oppLifeLabel.setFont(new java.awt.Font("MS Sans Serif", 0, 40));
oppLifeLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
oppLifeLabel.setText("19");
oppLifeLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jPanel3.add(oppLifeLabel, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel3);
jPanel3.setBounds(210, 170, 90, 90);
jPanel7.setLayout(new java.awt.BorderLayout());
jPanel7.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Player"));
playerLifeLabel.setFont(new java.awt.Font("MS Sans Serif", 0, 40));
playerLifeLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
playerLifeLabel.setText("19");
playerLifeLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jPanel7.add(playerLifeLabel, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel7);
jPanel7.setBounds(210, 600, 90, 90);
cdPanel.setLayout(new java.awt.GridLayout(2, 1, 0, 5));
cdPanel.setBorder(new javax.swing.border.EtchedBorder());
jPanel9.setLayout(new java.awt.GridLayout(5, 0, 0, 5));
cdLabel1.setFont(getFont());
cdLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
cdLabel1.setText("jLabel3");
jPanel9.add(cdLabel1);
cdLabel2.setFont(getFont());
cdLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
cdLabel2.setText("jLabel4");
jPanel9.add(cdLabel2);
cdLabel3.setFont(getFont());
cdLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
cdLabel3.setText("jLabel5");
jPanel9.add(cdLabel3);
cdLabel4.setFont(getFont());
cdLabel4.setText("jLabel6");
jPanel9.add(cdLabel4);
cdLabel5.setFont(getFont());
cdLabel5.setText("jLabel7");
jPanel9.add(cdLabel5);
cdPanel.add(jPanel9);
jPanel10.setLayout(new java.awt.BorderLayout());
cdArea.setFont(getFont());
cdArea.setLineWrap(true);
cdArea.setWrapStyleWord(true);
jScrollPane5.setViewportView(cdArea);
jPanel10.add(jScrollPane5, java.awt.BorderLayout.CENTER);
cdPanel.add(jPanel10);
getContentPane().add(cdPanel);
cdPanel.setBounds(790, 20, 230, 300);
picturePanel.setLayout(new java.awt.BorderLayout());
picturePanel.setBorder(new javax.swing.border.EtchedBorder());
getContentPane().add(picturePanel);
picturePanel.setBounds(790, 350, 230, 300);
jLabel1.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
jLabel1.setText("Library:");
getContentPane().add(jLabel1);
jLabel1.setBounds(60, 200, 70, 20);
jLabel2.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
jLabel2.setText("Hand:");
getContentPane().add(jLabel2);
jLabel2.setBounds(60, 170, 60, 20);
jLabel3.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
jLabel3.setText("Grave:");
getContentPane().add(jLabel3);
jLabel3.setBounds(60, 230, 70, 20);
oppHandLabel.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
oppHandLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
oppHandLabel.setText("7");
oppHandLabel.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
getContentPane().add(oppHandLabel);
oppHandLabel.setBounds(90, 170, 60, 20);
oppLibraryLabel.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
oppLibraryLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
oppLibraryLabel.setText("60");
oppLibraryLabel.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
getContentPane().add(oppLibraryLabel);
oppLibraryLabel.setBounds(90, 200, 60, 20);
oppGraveLabel.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
oppGraveLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
oppGraveLabel.setText("200");
oppGraveLabel.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
getContentPane().add(oppGraveLabel);
oppGraveLabel.setBounds(90, 230, 60, 20);
jLabel7.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
jLabel7.setText("Hand:");
getContentPane().add(jLabel7);
jLabel7.setBounds(60, 610, 60, 20);
jLabel8.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
jLabel8.setText("Library:");
getContentPane().add(jLabel8);
jLabel8.setBounds(60, 640, 60, 20);
jLabel9.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
jLabel9.setText("Grave:");
getContentPane().add(jLabel9);
jLabel9.setBounds(60, 670, 60, 20);
playerHandLabel.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
playerHandLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
playerHandLabel.setText("6");
playerHandLabel.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
getContentPane().add(playerHandLabel);
playerHandLabel.setBounds(90, 610, 60, 20);
playerLibraryLabel.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
playerLibraryLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
playerLibraryLabel.setText("54");
playerLibraryLabel.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
getContentPane().add(playerLibraryLabel);
playerLibraryLabel.setBounds(90, 640, 60, 20);
playerGraveLabel.setFont(new java.awt.Font("MS Sans Serif", 0, 18));
playerGraveLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
playerGraveLabel.setText("0");
playerGraveLabel.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
getContentPane().add(playerGraveLabel);
playerGraveLabel.setBounds(90, 670, 60, 20);
menuBar.setText("Menu");
jMenuBar1.add(menuBar);
setJMenuBar(jMenuBar1);
pack();
}//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed
{//GEN-HEADEREND:event_cancelButtonActionPerformed
inputControl.selectButtonCancel();
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_okButtonActionPerformed
{//GEN-HEADEREND:event_okButtonActionPerformed
inputControl.selectButtonOK();
}//GEN-LAST:event_okButtonActionPerformed
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt)//GEN-FIRST:event_exitForm
{
dispose();
Constant.Runtime.WinLose.addLose();
new Gui_WinLose();
}//GEN-LAST:event_exitForm
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JTextArea cdArea;
private javax.swing.JLabel cdLabel1;
private javax.swing.JLabel cdLabel2;
private javax.swing.JLabel cdLabel3;
private javax.swing.JLabel cdLabel4;
private javax.swing.JLabel cdLabel5;
public javax.swing.JPanel cdPanel;
private javax.swing.JTextArea combatArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JMenuBar jMenuBar1;
@SuppressWarnings("unused")
// jMenuBar2
private javax.swing.JMenuBar jMenuBar2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JMenu menuBar;
private javax.swing.JTextArea messageArea;
private javax.swing.JButton okButton;
private javax.swing.JPanel oppCreaturePanel;
private javax.swing.JLabel oppGraveLabel;
private javax.swing.JLabel oppHandLabel;
private javax.swing.JPanel oppLandPanel;
private javax.swing.JLabel oppLibraryLabel;
private javax.swing.JLabel oppLifeLabel;
private javax.swing.JPanel picturePanel;
private javax.swing.JPanel playerCreaturePanel;
private javax.swing.JLabel playerGraveLabel;
private javax.swing.JLabel playerHandLabel;
private javax.swing.JPanel playerHandPanel;
private javax.swing.JPanel playerLandPanel;
private javax.swing.JLabel playerLibraryLabel;
private javax.swing.JLabel playerLifeLabel;
private javax.swing.JPanel stackPanel;
// End of variables declaration//GEN-END:variables
}

1273
src/GuiDisplay3.java Normal file

File diff suppressed because it is too large Load Diff

894
src/GuiDisplayUtil.java Normal file
View File

@@ -0,0 +1,894 @@
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import forge.properties.ForgeProps;
import forge.properties.NewConstants;
public class GuiDisplayUtil implements NewConstants {
public static JPanel getCardPanel(Card c) {
return getCardPanel(c, c.getName());
}
public static JPanel getCardPanel(Card c, String name) {
JPanel panel = new CardPanel(c);
panel.setBorder(getBorder(c));
Image cardImage = ImageCache.getImage(c);
if(cardImage != null) {
panel.setLayout(new GridLayout(1, 1));
JLabel imageLabel = new JLabel();
if(c.isBasicLand()) {
String basicLandSuffix = "";
if(c.getRandomPicture() != 0) {
basicLandSuffix = Integer.toString(c.getRandomPicture());
name += basicLandSuffix;
}
} else if(c.isFaceDown()) name = "Morph";
if(c.isTapped()) {
cardImage = ImageUtil.getTappedImage(cardImage, name);
}
imageLabel.setIcon(new ImageIcon(cardImage));
panel.add(imageLabel);
} else {
panel.setLayout(new GridLayout(4, 1));
if(c.isFaceDown()) name = "Morph";
panel.add(new JLabel(name + " " + c.getManaCost()));
panel.add(new JLabel(formatCardType(c)));
JPanel p1 = new JPanel();
panel.add(p1);
JLabel tapLabel = new JLabel();
p1.add(tapLabel);
if(c.isTapped()) {
if(!c.isCreature()) {
panel.setLayout(new GridLayout(3, 1));
}
p1.setBackground(Color.white);
tapLabel.setText("Tapped");
}
String stats = c.getNetAttack() + " / " + c.getNetDefense();
if(c.isCreature()) panel.add(new JLabel(stats));
}
return panel;
}//getCardPanel(Card c, String name)
public static Border getBorder(Card card) {
Color color;
if(card.isArtifact()) color = Color.gray;
else if(CardUtil.getColor(card).equals(Constant.Color.Black) || card.getName().equals("Swamp")
|| card.getName().equals("Bog")) color = Color.black;
else if(CardUtil.getColor(card).equals(Constant.Color.Green) || card.getName().equals("Forest")
|| card.getName().equals("Grass")) color = new Color(0, 220, 39);
else if(CardUtil.getColor(card).equals(Constant.Color.White) || card.getName().equals("Plains")
|| card.getName().equals("White Sand")) color = Color.white;
else if(CardUtil.getColor(card).equals(Constant.Color.Red) || card.getName().equals("Mountain")
|| card.getName().equals("Rock")) color = Color.red;
else if(CardUtil.getColor(card).equals(Constant.Color.Blue) || card.getName().equals("Island")
|| card.getName().equals("Underwater")) color = Color.blue;
else color = Color.black;
if(CardUtil.getColors(card).size() != 1) {
color = Color.orange;
}
if(!card.isArtifact()) {
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
int shade = 10;
r -= shade;
g -= shade;
b -= shade;
r = Math.max(0, r);
g = Math.max(0, g);
b = Math.max(0, b);
color = new Color(r, g, b);
}
//~
return BorderFactory.createLineBorder(color, 2);
}
public static MouseMotionListener getCardDetailMouse(final GuiDisplay3 visual) {
return new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent me) {
JPanel panel = (JPanel) me.getSource();
Object o = panel.getComponentAt(me.getPoint());
if((o != null) && (o instanceof CardPanel)) {
CardPanel cardPanel = (CardPanel) o;
visual.updateCardDetail(cardPanel.getCard());
}
}//mouseMoved
};
}
public static MouseMotionListener getCardDetailMouse(final GuiDisplay2 visual) {
return new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent me) {
JPanel panel = (JPanel) me.getSource();
Object o = panel.getComponentAt(me.getPoint());
if((o != null) && (o instanceof CardPanel)) {
CardPanel cardPanel = (CardPanel) o;
visual.updateCardDetail(cardPanel.getCard());
}
}//mouseMoved
};
}
public static String formatCardType(Card card) {
ArrayList<String> list = card.getType();
String returnString = "";
String s;
for(int i = 0; i < list.size(); i++) {
s = list.get(i).toString();
if(s.equals("Creature") || s.equals("Land")) {
s += " - ";
} else s += " ";
returnString += s;
}
return returnString;
}
public static JPanel getPicture(Card c) {
if(AllZone.NameChanger.shouldChangeCardName()) return new JPanel();
String suffix = ".jpg";
String filename = "";
if(!c.isFaceDown()) {
String basicLandSuffix = "";
if(c.isBasicLand()) {
if(c.getRandomPicture() != 0) basicLandSuffix = Integer.toString(c.getRandomPicture());
}
filename = cleanString(c.getImageName()) + basicLandSuffix + suffix;
} else filename = "morph" + suffix;
File file = new File(ForgeProps.getFile(IMAGE_BASE), filename);
//try current directory
if(!file.exists()) {
filename = cleanString(c.getName()) + suffix;
file = new File(filename);
}
if(file.exists()) {
return new PicturePanel(file);
} else {
JPanel p = new JPanel();
JTextArea text = new JTextArea("\r\n\r\n" + filename, 10, 15);
Font f = text.getFont();
f = f.deriveFont(f.getSize() + 2.0f);
text.setFont(f);
text.setBackground(p.getBackground());
p.add(text);
if(c.isToken()) return new JPanel();
return p;
}//else
}//getPicture()
public static String cleanString(String in) {
StringBuffer out = new StringBuffer();
char c;
for(int i = 0; i < in.length(); i++) {
c = in.charAt(i);
if(c == ' ' || c == '-') out.append('_');
else if(Character.isLetterOrDigit(c)) {
out.append(c);
}
}
return out.toString().toLowerCase();
}
public static void setupNoLandPanel(JPanel j, Card c[]) {
ArrayList<Card> a = new ArrayList<Card>();
/*
for(int i = 0; i < c.length; i++)
if(c[i].isCreature() || c[i].isGlobalEnchantment() || c[i].isArtifact() || c[i].isPlaneswalker())
a.add(c[i]);
*/
/*
//creatures or planeswalkers
for(int i = 0; i < c.length; i++)
//!artifact because of Memnarch turning planeswalkers into artifacts.
if (c[i].isCreature() || (c[i].isPlaneswalker() && !c[i].isArtifact()))
a.add(c[i]);
//(non-creature, non-enchantment,non-land) artifacts
for(int i = 0; i < c.length; i++)
if (c[i].isArtifact() && !c[i].isCreature() && !c[i].isLand() && !c[i].isGlobalEnchantment() )
a.add(c[i]);
//(non-creature) enchantments
for(int i = 0; i < c.length; i++)
if (c[i].isGlobalEnchantment() && !c[i].isCreature())
a.add(c[i]);
*/
for(int i = 0; i < c.length; i++) {
a.add(c[i]);
}
setupNoLandPermPanel(j, a, true);
}
public static void setupLandPanel(JPanel j, Card c[]) {
ArrayList<Card> a = new ArrayList<Card>();
for(int i = 0; i < c.length; i++)
if((!(c[i].isCreature() || c[i].isEnchantment() || c[i].isArtifact() || c[i].isPlaneswalker()) || (c[i].isLand()
&& c[i].isArtifact() && !c[i].isCreature() && !c[i].isEnchantment()))
&& !AllZone.GameAction.isAttachee(c[i]) || (c[i].getName().startsWith("Mox") && !c[i].getName().equals("Mox Diamond")) )
a.add(c[i]);
setupPanel(j, a, true);
}
/*
private static void setupPanel(JPanel p, ArrayList<Card> list) {
setupPanel(p, list, false);
}
*/
//list holds Card objects
//puts local enchanments in the right order
//adds "<<" to local enchanments names
private static void setupPanel(JPanel p, ArrayList<Card> list, boolean stack) {
int maxY = 0;
int maxX = 0;
//remove all local enchantments
Card c;
/*
for(int i = 0; i < list.size(); i++)
{
c = (Card)list.get(i);
if(c.isLocalEnchantment())
list.remove(i);
}
//add local enchantments to the permanents
//put local enchantments "next to" the permanent they are enchanting
//the inner for loop is backward so permanents with more than one local enchantments are in the right order
Card ca[];
for(int i = 0; i < list.size(); i++)
{
c = (Card)list.get(i);
if(c.hasAttachedCards())
{
ca = c.getAttachedCards();
for(int inner = ca.length - 1; 0 <= inner; inner--)
list.add(i + 1, ca[inner]);
}
}
*/
if(stack) {
// add all Cards in list to the GUI, add arrows to Local Enchantments
ArrayList<Card> manaPool = getCard(list, "Mana Pool");
ArrayList<Card> enchantedLands = getEnchantedLands(list);
ArrayList<Card> basicBlues = getBasics(list, Constant.Color.Blue);
ArrayList<Card> basicReds = getBasics(list, Constant.Color.Red);
ArrayList<Card> basicBlacks = getBasics(list, Constant.Color.Black);
ArrayList<Card> basicGreens = getBasics(list, Constant.Color.Green);
ArrayList<Card> basicWhites = getBasics(list, Constant.Color.White);
ArrayList<Card> badlands = getNonBasicLand(list, "Badlands");
ArrayList<Card> bayou = getNonBasicLand(list, "Bayou");
ArrayList<Card> plateau = getNonBasicLand(list, "Plateau");
ArrayList<Card> scrubland = getNonBasicLand(list, "Scrubland");
ArrayList<Card> savannah = getNonBasicLand(list, "Savannah");
ArrayList<Card> taiga = getNonBasicLand(list, "Taiga");
ArrayList<Card> tropicalIsland = getNonBasicLand(list, "Tropical Island");
ArrayList<Card> tundra = getNonBasicLand(list, "Tundra");
ArrayList<Card> undergroundSea = getNonBasicLand(list, "Underground Sea");
ArrayList<Card> volcanicIsland = getNonBasicLand(list, "Volcanic Island");
ArrayList<Card> nonBasics = getNonBasics(list);
ArrayList<Card> moxEmerald = getMoxen(list, "Mox Emerald");
ArrayList<Card> moxJet = getMoxen(list, "Mox Jet");
ArrayList<Card> moxPearl = getMoxen(list, "Mox Pearl");
ArrayList<Card> moxRuby = getMoxen(list, "Mox Ruby");
ArrayList<Card> moxSapphire = getMoxen(list, "Mox Sapphire");
//ArrayList<Card> moxDiamond = getMoxen(list, "Mox Diamond");
list = new ArrayList<Card>();
list.addAll(manaPool);
list.addAll(enchantedLands);
list.addAll(basicBlues);
list.addAll(basicReds);
list.addAll(basicBlacks);
list.addAll(basicGreens);
list.addAll(basicWhites);
list.addAll(badlands);
list.addAll(bayou);
list.addAll(plateau);
list.addAll(scrubland);
list.addAll(savannah);
list.addAll(taiga);
list.addAll(tropicalIsland);
list.addAll(tundra);
list.addAll(undergroundSea);
list.addAll(volcanicIsland);
list.addAll(nonBasics);
list.addAll(moxEmerald);
list.addAll(moxJet);
list.addAll(moxPearl);
list.addAll(moxRuby);
list.addAll(moxSapphire);
//list.addAll(moxDiamond);
int atInStack = 0;
int marginX = 5;
int marginY = 5;
int x = marginX;
int cardOffset = 10;
String color = "";
ArrayList<JPanel> cards = new ArrayList<JPanel>();
ArrayList<CardPanel> connectedCards = new ArrayList<CardPanel>();
boolean nextEnchanted = false;
Card prevCard = null;
int nextXIfNotStacked = 0;
for(int i = 0; i < list.size(); i++) {
JPanel addPanel;
c = list.get(i);
addPanel = getCardPanel(c);
boolean startANewStack = false;
if(!isStackable(c)) {
startANewStack = true;
} else {
String newColor = c.getName(); //CardUtil.getColor(c);
if(!newColor.equals(color)) {
startANewStack = true;
color = newColor;
}
}
if(i == 0) {
startANewStack = false;
}
if(!startANewStack && atInStack == 4) {
startANewStack = true;
}
if(c.isAura() && c.isEnchanting() && !nextEnchanted) startANewStack = false;
else if(c.isAura() && c.isEnchanting()) {
startANewStack = true;
nextEnchanted = false;
}
if(c.isLand() && c.isEnchanted()) {
startANewStack = false;
nextEnchanted = true;
}
//very hacky, but this is to ensure enchantment stacking occurs correctly when a land is enchanted, and there are more lands of that same name
else if((prevCard != null && c.isLand() && prevCard.isLand() && prevCard.isEnchanted() && prevCard.getName().equals(
c.getName()))) startANewStack = true;
else if(prevCard != null && c.isLand() && prevCard.isLand()
&& !prevCard.getName().equals(c.getName())) startANewStack = true;
/*
if (c.getName().equals("Squirrel Nest")) {
startANewStack = true;
System.out.println("startANewStack: " + startANewStack);
}
*/
if(c.isAura() && c.isEnchanting() && prevCard != null && prevCard.getName().equals("Mana Pool"))
startANewStack = true;
if(startANewStack) {
setupConnectedCards(connectedCards);
connectedCards.clear();
// Fixed distance if last was a stack, looks a bit nicer
if(atInStack > 1) {
x += Math.max(addPanel.getPreferredSize().width, addPanel.getPreferredSize().height)
+ marginX;
} else {
x = nextXIfNotStacked;
}
atInStack = 0;
} else {
if(i != 0) {
x += cardOffset;
}
}
nextXIfNotStacked = x + marginX + addPanel.getPreferredSize().width;
int xLoc = x;
int yLoc = marginY;
yLoc += atInStack * cardOffset;
addPanel.setLocation(new Point(xLoc, yLoc));
addPanel.setSize(addPanel.getPreferredSize());
cards.add(addPanel);
connectedCards.add((CardPanel) addPanel);
atInStack++;
prevCard = c;
}
setupConnectedCards(connectedCards);
connectedCards.clear();
for(int i = cards.size() - 1; i >= 0; i--) {
JPanel card = cards.get(i);
//maxX = Math.max(maxX, card.getLocation().x + card.getSize().width + marginX);
maxY = Math.max(maxY, card.getLocation().y + card.getSize().height + marginY);
p.add(card);
}
maxX = nextXIfNotStacked;
//System.out.println("x:" + maxX + ", y:" + maxY);
if(maxX > 0 && maxY > 0) { //p.getSize().width || maxY > p.getSize().height) {
// p.setSize(new Dimension(maxX, maxY));
p.setPreferredSize(new Dimension(maxX, maxY));
}
} else {
//add all Cards in list to the GUI, add arrows to Local Enchantments
JPanel addPanel;
for(int i = 0; i < list.size(); i++) {
c = list.get(i);
/*if(c.isLocalEnchantment())
addPanel = getCardPanel(c, "<< " +c.getName());
else
addPanel = getCardPanel(c);
*/
addPanel = getCardPanel(c);
p.add(addPanel);
}
}
}//setupPanel()
@SuppressWarnings("unchecked")
private static void setupNoLandPermPanel(JPanel p, ArrayList<Card> list, boolean stack) {
int maxY = 0;
int maxX = 0;
Card c;
if(stack) {
// add all Cards in list to the GUI, add arrows to Local Enchantments
ArrayList<Card> planeswalkers = getPlaneswalkers(list);
ArrayList<Card> equippedEnchantedCreatures = getEquippedEnchantedCreatures(list); //this will also fetch the equipment and/or enchantment
ArrayList<Card> nonTokenCreatures = getNonTokenCreatures(list);
ArrayList<Card> tokenCreatures = getTokenCreatures(list);
//sort tokenCreatures by name (TODO: fix the warning message somehow)
Collections.sort(tokenCreatures, new Comparator() {
public int compare(Object o1, Object o2) {
Card c1 = (Card) o1;
Card c2 = (Card) o2;
return c1.getName().compareTo(c2.getName());
}
});
ArrayList<Card> artifacts = getNonCreatureArtifacts(list);
ArrayList<Card> enchantments = getGlobalEnchantments(list);
//ArrayList<Card> nonBasics = getNonBasics(list);
list = new ArrayList<Card>();
list.addAll(planeswalkers);
list.addAll(equippedEnchantedCreatures);
list.addAll(nonTokenCreatures);
list.addAll(tokenCreatures);
list.addAll(artifacts);
list.addAll(enchantments);
int atInStack = 0;
int marginX = 5;
int marginY = 5;
int x = marginX;
int cardOffset = 10;
String color = "";
ArrayList<JPanel> cards = new ArrayList<JPanel>();
ArrayList<CardPanel> connectedCards = new ArrayList<CardPanel>();
boolean nextEquippedEnchanted = false;
int nextXIfNotStacked = 0;
Card prevCard = null;
for(int i = 0; i < list.size(); i++) {
JPanel addPanel;
c = list.get(i);
addPanel = getCardPanel(c);
boolean startANewStack = false;
if(!isStackable(c)) {
startANewStack = true;
} else {
String newColor = c.getName(); //CardUtil.getColor(c);
if(!newColor.equals(color)) {
startANewStack = true;
color = newColor;
}
}
if(i == 0) {
startANewStack = false;
}
if(!startANewStack && atInStack == 4) {
startANewStack = true;
}
if((c.isEquipment() || c.isAura()) && (c.isEquipping() || c.isEnchanting())
&& !nextEquippedEnchanted) startANewStack = false;
else if((c.isEquipment() || c.isAura()) && (c.isEquipping() || c.isEnchanting())) {
startANewStack = true;
nextEquippedEnchanted = false;
}
if(c.isCreature() && (c.isEquipped() || c.isEnchanted())) {
startANewStack = false;
nextEquippedEnchanted = true;
}
//very hacky, but this is to ensure equipment stacking occurs correctly when a token is equipped/enchanted, and there are more tokens of that same name
else if((prevCard != null && c.isCreature() && prevCard.isCreature()
&& (prevCard.isEquipped() || prevCard.isEnchanted()) && prevCard.getName().equals(
c.getName()))) startANewStack = true;
else if(prevCard != null && c.isCreature() && prevCard.isCreature()
&& !prevCard.getName().equals(c.getName())) startANewStack = true;
if( ( (c.isAura() && c.isEnchanting()) || (c.isEquipment() && c.isEquipping()) ) && prevCard != null && prevCard.isPlaneswalker())
startANewStack = true;
if(startANewStack) {
setupConnectedCards(connectedCards);
connectedCards.clear();
// Fixed distance if last was a stack, looks a bit nicer
if(atInStack > 1) {
x += Math.max(addPanel.getPreferredSize().width, addPanel.getPreferredSize().height)
+ marginX;
} else {
x = nextXIfNotStacked;
}
atInStack = 0;
} else {
if(i != 0) {
x += cardOffset;
}
}
nextXIfNotStacked = x + marginX + addPanel.getPreferredSize().width;
int xLoc = x;
int yLoc = marginY;
yLoc += atInStack * cardOffset;
addPanel.setLocation(new Point(xLoc, yLoc));
addPanel.setSize(addPanel.getPreferredSize());
cards.add(addPanel);
connectedCards.add((CardPanel) addPanel);
atInStack++;
prevCard = c;
}
setupConnectedCards(connectedCards);
connectedCards.clear();
for(int i = cards.size() - 1; i >= 0; i--) {
JPanel card = cards.get(i);
//maxX = Math.max(maxX, card.getLocation().x + card.getSize().width + marginX);
maxY = Math.max(maxY, card.getLocation().y + card.getSize().height + marginY);
p.add(card);
}
maxX = nextXIfNotStacked;
if(maxX > 0 && maxY > 0) { //p.getSize().width || maxY > p.getSize().height) {
p.setPreferredSize(new Dimension(maxX, maxY));
}
} else {
JPanel addPanel;
for(int i = 0; i < list.size(); i++) {
c = list.get(i);
addPanel = getCardPanel(c);
p.add(addPanel);
}
}
}//setupPanel()
public static ArrayList<Card> getPlaneswalkers(ArrayList<Card> cards) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
if(c.isPlaneswalker() && !c.isArtifact()) ret.add(c);
}
return ret;
}
public static ArrayList<Card> getEquippedEnchantedCreatures(ArrayList<Card> cards) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
if(c.isCreature() && (c.isEquipped() || c.isEnchanted())) {
if(c.isEquipped()) ret.addAll(c.getEquippedBy());
if(c.isEnchanted()) ret.addAll(c.getEnchantedBy());
ret.add(c);
}
}
return ret;
}
public static ArrayList<Card> getNonTokenCreatures(ArrayList<Card> cards) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
if(c.isCreature() && !c.isToken() && !c.isEquipped() && !c.isEnchanted()) ret.add(c);
}
return ret;
}
public static ArrayList<Card> getTokenCreatures(ArrayList<Card> cards) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
if(c.isCreature() && c.isToken() && !c.isEquipped() && !c.isEnchanted()) ret.add(c);
}
return ret;
}
public static ArrayList<Card> getTokenCreatures(ArrayList<Card> cards, String tokenName) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
String name = c.getName();
if(c.isCreature() && c.isToken() && name.equals(tokenName)) ret.add(c);
}
return ret;
}
public static ArrayList<Card> getMoxen(ArrayList<Card> cards, String moxName) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
String name = c.getName();
if(name.equals(moxName)) ret.add(c);
}
return ret;
}
public static ArrayList<Card> getNonCreatureArtifacts(ArrayList<Card> cards) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
String name = c.getName();
if(c.isArtifact() && !c.isCreature() && !c.isLand() && !c.isGlobalEnchantment()
&& !(c.isEquipment() && c.isEquipping()) && !name.equals("Mox Emerald")
&& !name.equals("Mox Jet") && !name.equals("Mox Pearl") && !name.equals("Mox Ruby")
&& !name.equals("Mox Sapphire")) ret.add(c);
}
return ret;
}
public static ArrayList<Card> getGlobalEnchantments(ArrayList<Card> cards) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
if(c.isGlobalEnchantment() && !c.isCreature()) ret.add(c);
}
return ret;
}
public static ArrayList<Card> getCard(ArrayList<Card> cards, String name) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
if(c.getName().equals(name)) ret.add(c);
}
return ret;
}
public static ArrayList<Card> getEnchantedLands(ArrayList<Card> cards) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
if(c.isLand() && c.isEnchanted()) {
ret.addAll(c.getEnchantedBy());
ret.add(c);
}
}
return ret;
}
public static ArrayList<Card> getBasics(ArrayList<Card> cards, String color) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
String name = c.getName();
if(c.isEnchanted()) ;//do nothing
else if(name.equals("Swamp") || name.equals("Bog")) {
if(color == Constant.Color.Black) {
ret.add(c);
}
} else if(name.equals("Forest") || name.equals("Grass")) {
if(color == Constant.Color.Green) {
ret.add(c);
}
} else if(name.equals("Plains") || name.equals("White Sand")) {
if(color == Constant.Color.White) {
ret.add(c);
}
} else if(name.equals("Mountain") || name.equals("Rock")) {
if(color == Constant.Color.Red) {
ret.add(c);
}
} else if(name.equals("Island") || name.equals("Underwater")) {
if(color == Constant.Color.Blue) {
ret.add(c);
}
}
}
return ret;
}
public static ArrayList<Card> getNonBasics(ArrayList<Card> cards) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards) {
if(!c.isLand() && !c.getName().startsWith("Mox") && !c.getName().equals("Mana Pool")) {
ret.add(c);
} else {
String name = c.getName();
if(c.isEnchanted() || name.equals("Swamp") || name.equals("Bog") || name.equals("Forest")
|| name.equals("Grass") || name.equals("Plains") || name.equals("White Sand")
|| name.equals("Mountain") || name.equals("Rock") || name.equals("Island")
|| name.equals("Underwater") || name.equals("Badlands") || name.equals("Bayou")
|| name.equals("Plateau") || name.equals("Scrubland") || name.equals("Savannah")
|| name.equals("Taiga") || name.equals("Tropical Island") || name.equals("Tundra")
|| name.equals("Underground Sea") || name.equals("Volcanic Island")
|| name.startsWith("Mox") || name.equals("Mana Pool")) {
// do nothing.
} else {
ret.add(c);
}
}
}
return ret;
}
public static ArrayList<Card> getNonBasicLand(ArrayList<Card> cards, String landName) {
ArrayList<Card> ret = new ArrayList<Card>();
for(Card c:cards)
if(c.getName().equals(landName)) ret.add(c);
return ret;
}
public static boolean isStackable(Card c) {
/*String name = c.getName();
if( name.equals("Swamp") || name.equals("Bog") ||
name.equals("Forest") || name.equals("Grass") ||
name.equals("Plains") || name.equals("White Sand") ||
name.equals("Mountain") || name.equals("Rock") ||
name.equals("Island") || name.equals("Underwater")) {
return true;
}
*/
if(c.isLand() || (c.getName().startsWith("Mox") && !c.getName().equals("Mox Diamond") )|| (c.isLand() && c.isEnchanted())
|| (c.isAura() && c.isEnchanting()) || (c.isToken() && CardFactoryUtil.multipleControlled(c))
|| (c.isCreature() && (c.isEquipped() || c.isEnchanted())) || (c.isEquipment() && c.isEquipping())
|| (c.isEnchantment())) return true;
return false;
}
//~
public static void setupConnectedCards(ArrayList<CardPanel> connectedCards) {
for(int i = connectedCards.size() - 1; i > 0; i--) {
//System.out.println("We should have a stack");
CardPanel cp = connectedCards.get(i);
cp.connectedCard = connectedCards.get(i - 1);
}
}
//~
}

38
src/GuiInput.java Normal file
View File

@@ -0,0 +1,38 @@
import java.util.*;
public class GuiInput extends MyObservable implements Observer
{
Input input;
public GuiInput()
{
AllZone.InputControl.addObserver(this);
AllZone.Stack.addObserver(this);
AllZone.Phase.addObserver(this);
}
public void update(Observable observable, Object obj)
{
Input tmp = AllZone.InputControl.getInput();
if(tmp != null){
setInput(tmp);
}
}
private void setInput(Input in)
{
input = in;
input.showMessage();
}
public void showMessage()
{
//if (input instanceof Input_PayManaCost)
input.showMessage();
}
public void selectButtonOK() {input.selectButtonOK();}
public void selectButtonCancel(){input.selectButtonCancel();}
public void selectPlayer(String player) {input.selectPlayer(player);}
public void selectCard(Card card, PlayerZone zone) {input.selectCard(card, zone);}
public String toString(){return input.toString();}
}

594
src/Gui_BoosterDraft.java Normal file
View File

@@ -0,0 +1,594 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
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.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import forge.error.ErrorViewer;
import forge.properties.ForgeProps;
import forge.properties.NewConstants;
public class Gui_BoosterDraft extends JFrame implements CardDetail, NewConstants, NewConstants.LANG.Gui_BoosterDraft {
private static final long serialVersionUID = -6055633915602448260L;
private BoosterDraft boosterDraft;
private final boolean limitedDeckEditor = true;
private TableModel allCardModel;
private TableModel deckModel;
private JScrollPane jScrollPane1 = new JScrollPane();
private JScrollPane jScrollPane2 = new JScrollPane();
@SuppressWarnings("unused")
// border1
private Border border1;
private TitledBorder titledBorder1;
@SuppressWarnings("unused")
// border2
private Border border2;
private TitledBorder titledBorder2;
private JPanel cardDetailPanel = new JPanel();
private Border border3;
private TitledBorder titledBorder3;
private JPanel picturePanel = new JPanel();
private JLabel statsLabel = new JLabel();
private JTable allCardTable = new JTable();
private JTable deckTable = new JTable();
private JScrollPane jScrollPane3 = new JScrollPane();
private JPanel jPanel3 = new JPanel();
private JLabel cdLabel4 = new JLabel();
private JLabel cdLabel1 = new JLabel();
private JLabel cdLabel2 = new JLabel();
private JLabel cdLabel3 = new JLabel();
private GridLayout gridLayout1 = new GridLayout();
private JLabel cdLabel5 = new JLabel();
private JTextArea cdTextArea = new JTextArea();
private BorderLayout borderLayout1 = new BorderLayout();
private JLabel statsLabel2 = new JLabel();
private JButton jButton1 = new JButton();
public static void main(String[] args) {
Constant.Runtime.GameType[0] = Constant.GameType.Draft;
Constant.Runtime.HumanDeck[0] = new Deck(Constant.GameType.Sealed);
Gui_BoosterDraft g = new Gui_BoosterDraft();
g.showGui(new BoosterDraftTest());
}
public void showGui(BoosterDraft in_boosterDraft) {
boosterDraft = in_boosterDraft;
setup();
showChoices(boosterDraft.nextChoice());
allCardModel.sort(1, true);
deckModel.sort(1, true);
setVisible(true);
}
private void addListeners() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent ev) {
int n = JOptionPane.showConfirmDialog(null, ForgeProps.getLocalized(CLOSE_MESSAGE), "",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION) {
dispose();
new Gui_NewGame();
}
}//windowClosing()
});
}//addListeners()
private void setup() {
addListeners();
// setupMenu();
//construct allCardTable, get all cards
allCardModel = new TableModel(new CardList(), this);
allCardModel.addListeners(allCardTable);
allCardTable.setModel(allCardModel);
//construct deckModel
deckModel = new TableModel(this);
deckModel.addListeners(deckTable);
deckTable.setModel(deckModel);
//add cards to GUI from deck
// refreshGui();
allCardTable.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0) jButton1_actionPerformed(null);
}
});//MouseListener
//get stats from deck
deckModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent ev) {
CardList deck = deckModel.getCards();
statsLabel.setText(getStats(deck));
}
});
//get stats from all cards
allCardModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent ev) {
CardList deck = allCardModel.getCards();
statsLabel2.setText(getStats(deck));
}
});
//Use both so that when "un"maximizing, the frame isn't tiny
setSize(1024, 740);
setExtendedState(Frame.MAXIMIZED_BOTH);
}//setupAndDisplay()
private String getStats(CardList deck) {
int total = deck.size();
int creature = deck.getType("Creature").size();
int land = deck.getType("Land").size();
String show = "Total - " + total + ", Creatures - " + creature + ", Land - " + land;
String[] color = Constant.Color.Colors;
for(int i = 0; i < 5; i++)
show += ", " + color[i] + " - " + CardListUtil.getColor(deck, color[i]).size();
return show;
}//getStats()
public Gui_BoosterDraft() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
}
public void updateCardDetail(Card c) {
CardDetailUtil.updateCardDetail(c, cdTextArea, cardDetailPanel, picturePanel, new JLabel[] {
cdLabel1, cdLabel2, cdLabel3, cdLabel4, cdLabel5});
}
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)),
"Previous Picked Cards");
border2 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
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));
cardDetailPanel.setBorder(titledBorder3);
cardDetailPanel.setBounds(new Rectangle(693, 23, 239, 323));
cardDetailPanel.setLayout(null);
picturePanel.setBorder(BorderFactory.createEtchedBorder());
picturePanel.setBounds(new Rectangle(698, 362, 226, 301));
picturePanel.setLayout(borderLayout1);
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));
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.setTitle("Booster Draft");
jScrollPane3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane3.setBounds(new Rectangle(6, 168, 225, 143));
jPanel3.setBounds(new Rectangle(7, 21, 224, 141));
jPanel3.setLayout(gridLayout1);
cdLabel4.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel4.setHorizontalAlignment(SwingConstants.LEFT);
cdLabel1.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel1.setHorizontalAlignment(SwingConstants.CENTER);
cdLabel2.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel2.setHorizontalAlignment(SwingConstants.CENTER);
cdLabel3.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel3.setHorizontalAlignment(SwingConstants.CENTER);
gridLayout1.setColumns(1);
gridLayout1.setRows(0);
cdLabel5.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel5.setHorizontalAlignment(SwingConstants.LEFT);
cdTextArea.setFont(new java.awt.Font("Dialog", 0, 12));
cdTextArea.setLineWrap(true);
cdTextArea.setWrapStyleWord(true);
statsLabel2.setBounds(new Rectangle(19, 378, 665, 31));
statsLabel2.setText("Total - 0, Creatures - 0 Land - 0");
statsLabel2.setFont(new java.awt.Font("Dialog", 0, 16));
jButton1.setBounds(new Rectangle(238, 418, 147, 44));
jButton1.setFont(new java.awt.Font("Dialog", 0, 16));
jButton1.setText("Choose Card");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
this.getContentPane().add(cardDetailPanel, null);
cardDetailPanel.add(jScrollPane3, null);
jScrollPane3.getViewport().add(cdTextArea, null);
cardDetailPanel.add(jPanel3, null);
jPanel3.add(cdLabel1, null);
jPanel3.add(cdLabel2, null);
jPanel3.add(cdLabel3, null);
jPanel3.add(cdLabel4, null);
this.getContentPane().add(picturePanel, null);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(statsLabel2, null);
this.getContentPane().add(statsLabel, null);
this.getContentPane().add(jScrollPane2, null);
this.getContentPane().add(jButton1, null);
jScrollPane2.getViewport().add(deckTable, null);
jScrollPane1.getViewport().add(allCardTable, null);
jPanel3.add(cdLabel5, null);
}
void addButton_actionPerformed(ActionEvent e) {
int n = allCardTable.getSelectedRow();
if(n != -1) {
setTitle("Deck Editor - " + Constant.Runtime.HumanDeck[0].getName() + " - changed");
Card c = allCardModel.rowToCard(n);
deckModel.addCard(c);
deckModel.resort();
if(limitedDeckEditor) {
allCardModel.removeCard(c);
}
//3 conditions" 0 cards left, select the same row, select next row
int size = allCardModel.getRowCount();
if(size != 0) {
if(size == n) n--;
allCardTable.addRowSelectionInterval(n, n);
}
}//if(valid row)
}//addButton_actionPerformed
void removeButton_actionPerformed(ActionEvent e) {
int n = deckTable.getSelectedRow();
if(n != -1) {
setTitle("Deck Editor - " + Constant.Runtime.HumanDeck[0].getName() + " - changed");
Card c = deckModel.rowToCard(n);
deckModel.removeCard(c);
if(limitedDeckEditor) {
allCardModel.addCard(c);
allCardModel.resort();
}
//3 conditions" 0 cards left, select the same row, select next row
int size = deckModel.getRowCount();
if(size != 0) {
if(size == n) n--;
deckTable.addRowSelectionInterval(n, n);
}
}//if(valid row)
}//removeButton_actionPerformed
//if true, don't do anything else
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()
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
private void closeItem_actionPerformed() {
//check if saved, show dialog "yes, "no"
checkSaveDeck();
dispose();
}
private void stats_actionPerformed(CardList list) {
}
private void saveAsItem_actionPerformed() {}//saveItem_actionPerformed()
private void saveItem_actionPerformed() {}
private void openItem_actionPerformed() {}//openItem_actionPerformed()
public void deleteItem_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");
}
}
@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
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;
ReadBoosterPack pack = new ReadBoosterPack();
for(int i = 0; i < deck.countMain(); i++) {
c = AllZone.CardFactory.getCard(deck.getMain(i), Constant.Player.Human);
//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.CardFactory.getCard(deck.getSideboard(i), Constant.Player.Human);
c.setRarity(pack.getRarity(c.getName()));
allCardModel.addCard(c);
}
} else {
CardList all = AllZone.CardFactory.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
@SuppressWarnings("unused")
// refreshDeck
private void refreshDeck() {
//make new Deck
Deck deck = new Deck(Constant.Runtime.GameType[0]);
deck.setName(Constant.Runtime.HumanDeck[0].getName());
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());
if(deck.isSealed()) {
//add sideboard to deck
list = allCardModel.getCards();
for(int i = 0; i < list.size(); i++)
deck.addSideboard(list.get(i).getName());
}
}/* refreshDeck() */
void jButton1_actionPerformed(ActionEvent e) {
//pick card
int n = allCardTable.getSelectedRow();
if(n == -1) //is valid selection?
return;
Card c = allCardModel.rowToCard(n);
deckModel.addCard(c);
deckModel.resort();
//get next booster pack
boosterDraft.setChoice(c);
if(boosterDraft.hasNextChoice()) {
showChoices(boosterDraft.nextChoice());
} else {
//quit
saveDraft();
dispose();
}
}/*OK Button*/
private void showChoices(CardList list) {
allCardModel.clear();
ReadBoosterPack pack = new ReadBoosterPack();
Card c;
for(int i = 0; i < list.size(); i++) {
c = list.get(i);
c.setRarity(pack.getRarity(c.getName()));
allCardModel.addCard(c);
}
allCardModel.resort();
allCardTable.setRowSelectionInterval(0, 0);
}//showChoices()
private Deck getPlayersDeck() {
Deck deck = new Deck(Constant.GameType.Draft);
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());
for(int i = 0; i < 40; i++) {
deck.addSideboard("Forest");
deck.addSideboard("Mountain");
deck.addSideboard("Swamp");
deck.addSideboard("Island");
deck.addSideboard("Plains");
}
return deck;
}//getPlayersDeck()
private void saveDraft() {
String s = "";
while(s == null || s.length() == 0) {
s = JOptionPane.showInputDialog(null, ForgeProps.getLocalized(SAVE_DRAFT_MESSAGE),
ForgeProps.getLocalized(SAVE_DRAFT_TITLE), JOptionPane.QUESTION_MESSAGE);
}
//TODO: check if overwriting the same name, and let the user delete old drafts
//construct computer's decks
//save draft
Deck[] computer = boosterDraft.getDecks();
Deck human = getPlayersDeck();
human.setName(s);
Deck[] all = {
human, computer[0], computer[1], computer[2], computer[3], computer[4], computer[5], computer[6]};
DeckIO deckIO = new DeckIO(ForgeProps.getFile(BOOSTER_DECKS));
deckIO.writeBoosterDeck(all);
//write file
deckIO.close();
//close and open next screen
dispose();
new Gui_NewGame();
}/*saveDraft()*/
}

722
src/Gui_DeckEditor.java Normal file
View File

@@ -0,0 +1,722 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import forge.error.ErrorViewer;
//import java.util.*; //unused
public class Gui_DeckEditor extends JFrame implements CardDetail, DeckDisplay
{
private static final long serialVersionUID = 130339644136746796L;
Gui_DeckEditor_Menu customMenu;
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 JPanel cardDetailPanel = new JPanel();
private Border border3;
private TitledBorder titledBorder3;
private JPanel picturePanel = new JPanel();
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 JLabel cdLabel4 = new JLabel();
private JLabel cdLabel1 = new JLabel();
private JLabel cdLabel2 = new JLabel();
private JLabel cdLabel3 = new JLabel();
private GridLayout gridLayout1 = new GridLayout();
private JLabel cdLabel5 = new JLabel();
private JTextArea cdTextArea = new JTextArea();
private BorderLayout borderLayout1 = new BorderLayout();
private JLabel statsLabel2 = new JLabel();
private JLabel jLabel1 = new JLabel();
private JCheckBox whiteCheckBox = new JCheckBox("W", true);
private JCheckBox blueCheckBox = new JCheckBox("U", true);
private JCheckBox blackCheckBox = new JCheckBox("B", true);
private JCheckBox redCheckBox = new JCheckBox("R", true);
private JCheckBox greenCheckBox = new JCheckBox("G", true);
private JCheckBox colorlessCheckBox = new JCheckBox("C", true);
private JCheckBox landCheckBox = new JCheckBox("Land", true);
private JCheckBox creatureCheckBox = new JCheckBox("Creature", true);
private JCheckBox sorceryCheckBox = new JCheckBox("Sorcery", true);
private JCheckBox instantCheckBox = new JCheckBox("Instant", true);
private JCheckBox planeswalkerCheckBox = new JCheckBox("Planeswalker", true);
private JCheckBox artifactCheckBox = new JCheckBox("Artifact", true);
private JCheckBox enchantmentCheckBox = new JCheckBox("Enchant", true);
private CardList top;
private CardList bottom;
public static void main(String[] args)
{
}
@Override
public void setTitle(String message) {
super.setTitle(message);
}
public void updateDisplay(CardList top, CardList bottom) {
this.top = top;
this.bottom = bottom;
topModel.clear();
bottomModel.clear();
if (AllZone.NameChanger.shouldChangeCardName()) {
top = new CardList(AllZone.NameChanger.changeCard(top.toArray()));
bottom = new CardList(AllZone.NameChanger.changeCard(bottom
.toArray()));
}
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.NameChanger.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
// update bottom
for (int i = 0; i < bottom.size(); i++) {
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()));
bottomModel.addCard(c);
}// for
topModel.resort();
bottomModel.resort();
}// updateDisplay
public void updateDisplay() {
//updateDisplay(this.top, this.bottom);
topModel.clear();
if (AllZone.NameChanger.shouldChangeCardName()) {
top = new CardList(AllZone.NameChanger.changeCard(top.toArray()));
bottom = new CardList(AllZone.NameChanger.changeCard(bottom
.toArray()));
}
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.NameChanger.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();
}
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;
}
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
public TableModel getTopTableModel()
{
return topModel;
}
public CardList getTop() {return topModel.getCards();}
//bottom shows cards that the user has chosen for his library
public CardList getBottom() {return bottomModel.getCards();}
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();
}
};
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
customMenu.newConstructed();
topModel.sort(1, true);
bottomModel.sort(1, true);
}//show(Command)
private void addListeners()
{
}//addListeners()
private void setup()
{
addListeners();
//construct topTable, get all cards
topModel = new TableModel(new CardList(), (CardDetail)this);
topModel.addListeners(topTable);
topTable.setModel(topModel);
topModel.resizeCols(topTable);
//construct bottomModel
bottomModel = new TableModel((CardDetail)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));
}
});
setSize(1024, 768);
//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()
private String getStats(CardList deck) {
int total = deck.size();
int creature = deck.getType("Creature").size();
int land = deck.getType("Land").size();
String show = "Total - " + total + ", Creatures - " + creature + ", Land - " + land;
String[] color = Constant.Color.Colors;
for(int i = 0; i < 5; i++)
show += ", " + color[i] + " - " + CardListUtil.getColor(deck, color[i]).size();
return show;
}//getStats()
public Gui_DeckEditor() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
}
public void updateCardDetail(Card c) {
//change card name if needed
c = AllZone.CardFactory.copyCard(c);
if(AllZone.NameChanger.shouldChangeCardName()) c = AllZone.NameChanger.changeCard(c);
CardDetailUtil.updateCardDetail(c, cdTextArea, cardDetailPanel, picturePanel, new JLabel[] {
cdLabel1, cdLabel2, cdLabel3, cdLabel4, cdLabel5});
}
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");
border3 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder3 = new TitledBorder(border3, "Card Detail");
this.getContentPane().setLayout(null);
jScrollPane1.setBorder(titledBorder1);
jScrollPane1.setBounds(new Rectangle(19, 28, 726, 346));
jScrollPane2.getViewport().setBackground(new Color(204, 204, 204));
jScrollPane2.setBorder(titledBorder2);
jScrollPane2.setBounds(new Rectangle(19, 458, 726, 218));
removeButton.setBounds(new Rectangle(180, 403, 146, 49));
removeButton.setIcon(upIcon);
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);
addButton.setFont(new java.awt.Font("Dialog", 0, 13));
addButton.setBounds(new Rectangle(23, 403, 146, 49));
/**
* Type filtering
*/
Font f = new Font("Tahoma", Font.PLAIN, 10);
landCheckBox.setBounds(340, 400, 48, 20);
landCheckBox.setFont(f);
landCheckBox.setOpaque(false);
landCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
creatureCheckBox.setBounds(385, 400, 65, 20);
creatureCheckBox.setFont(f);
creatureCheckBox.setOpaque(false);
creatureCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
sorceryCheckBox.setBounds(447, 400, 62, 20);
sorceryCheckBox.setFont(f);
sorceryCheckBox.setOpaque(false);
sorceryCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
instantCheckBox.setBounds(505, 400, 60, 20);
instantCheckBox.setFont(f);
instantCheckBox.setOpaque(false);
instantCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
planeswalkerCheckBox.setBounds(558, 400, 85, 20);
planeswalkerCheckBox.setFont(f);
planeswalkerCheckBox.setOpaque(false);
planeswalkerCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
artifactCheckBox.setBounds(638, 400, 58, 20);
artifactCheckBox.setFont(f);
artifactCheckBox.setOpaque(false);
artifactCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
enchantmentCheckBox.setBounds(692, 400, 80, 20);
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
*/
cardDetailPanel.setBorder(titledBorder3);
cardDetailPanel.setBounds(new Rectangle(765, 23, 239, 323));
cardDetailPanel.setLayout(null);
picturePanel.setBorder(BorderFactory.createEtchedBorder());
picturePanel.setBounds(new Rectangle(772, 362, 226, 301));
picturePanel.setLayout(borderLayout1);
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");
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);
cdLabel4.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel4.setHorizontalAlignment(SwingConstants.LEFT);
cdLabel1.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel1.setHorizontalAlignment(SwingConstants.CENTER);
cdLabel2.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel2.setHorizontalAlignment(SwingConstants.CENTER);
cdLabel3.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel3.setHorizontalAlignment(SwingConstants.CENTER);
gridLayout1.setColumns(1);
gridLayout1.setRows(0);
cdLabel5.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel5.setHorizontalAlignment(SwingConstants.LEFT);
cdTextArea.setFont(new java.awt.Font("Dialog", 0, 12));
cdTextArea.setLineWrap(true);
cdTextArea.setWrapStyleWord(true);
statsLabel2.setBounds(new Rectangle(19, 371, 720, 31));
statsLabel2.setText("Total - 0, Creatures - 0 Land - 0");
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, 9, 400, 19));
this.getContentPane().add(cardDetailPanel, null);
cardDetailPanel.add(jScrollPane3, null);
jScrollPane3.getViewport().add(cdTextArea, null);
cardDetailPanel.add(jPanel3, null);
jPanel3.add(cdLabel1, null);
jPanel3.add(cdLabel2, null);
jPanel3.add(cdLabel3, null);
jPanel3.add(cdLabel4, null);
this.getContentPane().add(picturePanel, null);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(jScrollPane2, null);
this.getContentPane().add(addButton, null);
this.getContentPane().add(removeButton, 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);
jPanel3.add(cdLabel5, 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);
}
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(!Constant.GameType.Constructed.equals(customMenu.getGameType())) {
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
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)
}//removeButton_actionPerformed
@SuppressWarnings("unused")
// stats_actionPerformed
private void stats_actionPerformed(CardList list) {
}
//refresh Gui from deck, Gui shows the cards in the deck
@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.CardFactory.getCard(deck.getMain(i), Constant.Player.Human);
//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.CardFactory.getCard(deck.getSideboard(i), Constant.Player.Human);
c.setRarity(pack.getRarity(c.getName()));
topModel.addCard(c);
}
}
else
{
CardList all = AllZone.CardFactory.getAllCards();
for(int i = 0; i < all.size(); i++)
topModel.addCard(all.get(i));
}
topModel.resort();
bottomModel.resort();
}////refreshGui()
}

1059
src/Gui_DeckEditor_Menu.java Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,314 @@
import static java.lang.Integer.*;
import static javax.swing.JOptionPane.*;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.AbstractButton;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import forge.error.ErrorViewer;
import forge.properties.ForgeProps;
import forge.properties.NewConstants;
public class Gui_DownloadPictures extends DefaultBoundedRangeModel implements Runnable, NewConstants, NewConstants.LANG.Gui_DownloadPictures {
private static final long serialVersionUID = -7890794857949935256L;
public static void main(String[] args) {
startDownload(null);
}
public static final Proxy.Type[] types = Proxy.Type.values();
//proxy
private int type;
private JTextField addr, port;
//progress
private Card[] cards;
private int card;
private boolean cancel;
private JProgressBar bar;
private JOptionPane dlg;
private JButton close;
private Gui_DownloadPictures(Card[] c) {
this.cards = c;
addr = new JTextField(ForgeProps.getLocalized(PROXY_ADDRESS));
port = new JTextField(ForgeProps.getLocalized(PROXY_PORT));
bar = new JProgressBar(this);
JPanel p0 = new JPanel();
p0.setLayout(new BoxLayout(p0, BoxLayout.Y_AXIS));
//Proxy Choice
ButtonGroup bg = new ButtonGroup();
String[] labels = {
ForgeProps.getLocalized(NO_PROXY), ForgeProps.getLocalized(HTTP_PROXY),
ForgeProps.getLocalized(SOCKS_PROXY)};
for(int i = 0; i < types.length; i++) {
JRadioButton rb = new JRadioButton(labels[i]);
rb.addChangeListener(new ProxyHandler(i));
bg.add(rb);
p0.add(rb);
if(i == 0) rb.setSelected(true);
}
//Proxy config
p0.add(addr);
p0.add(port);
// JTextField[] tfs = {addr, port};
// String[] labels = {"Address", "Port"};
// for(int i = 0; i < labels.length; i++) {
// JPanel p1 = new JPanel(new BorderLayout());
// p0.add(p1);
//// p1.add(new JLabel(labels[i]), WEST);
// p1.add(tfs[i]);
// }
//Start
final JButton b = new JButton(ForgeProps.getLocalized(BUTTONS.START));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread(Gui_DownloadPictures.this).start();
b.setEnabled(false);
}
});
// p0.add(b);
p0.add(Box.createVerticalStrut(5));
//Progress
p0.add(bar);
bar.setStringPainted(true);
bar.setString(ForgeProps.getLocalized(BAR_BEFORE_START));
Dimension d = bar.getPreferredSize();
d.width = 300;
bar.setPreferredSize(d);
//JOptionPane
Object[] options = {b, close = new JButton(ForgeProps.getLocalized(BUTTONS.CANCEL))};
dlg = new JOptionPane(p0, DEFAULT_OPTION, PLAIN_MESSAGE, null, options, options[1]);
}
@Override
public int getMinimum() {
return 0;
}
@Override
public int getValue() {
return card;
}
@Override
public int getExtent() {
return 0;
}
@Override
public int getMaximum() {
return cards == null? 0:cards.length;
}
private void update(int card) {
this.card = card;
fireStateChanged();
bar.setString(String.format(ForgeProps.getLocalized(card == cards.length? BAR_CLOSE:BAR_WAIT), this.card,
cards.length));
System.out.println(card + "/" + cards.length);
}
public JDialog getDlg(JFrame frame) {
final JDialog dlg = this.dlg.createDialog(frame, ForgeProps.getLocalized(TITLE));
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dlg.setVisible(false);
}
});
return dlg;
}
public void setCancel(boolean cancel) {
this.cancel = cancel;
}
public void run() {
BufferedInputStream in;
BufferedOutputStream out;
File base = ForgeProps.getFile(IMAGE_BASE);
Proxy p = null;
if(type == 0) p = Proxy.NO_PROXY;
else try {
p = new Proxy(types[type], new InetSocketAddress(addr.getText(), parseInt(port.getText())));
} catch(Exception ex) {
ErrorViewer.showError(ex, ForgeProps.getLocalized(ERRORS.PROXY_CONNECT), addr.getText(),
port.getText());
// throw new RuntimeException("Gui_DownloadPictures : error 1 - " +ex);
return;
}
if(p != null) {
byte[] buf = new byte[1024];
int len;
System.out.println("basedir: " + base);
for(update(0); card < cards.length && !cancel; update(card + 1)) {
try {
String url = cards[card].url;
File f = new File(base, cards[card].name);
in = new BufferedInputStream(new URL(url).openConnection(p).getInputStream());
out = new BufferedOutputStream(new FileOutputStream(f));
while((len = in.read(buf)) != -1) {
//user cancelled
if(cancel) {
in.close();
out.flush();
out.close();
//delete what was written so far
f.delete();
return;
}//if - cancel
out.write(buf, 0, len);
}//while - read and write file
in.close();
out.flush();
out.close();
} catch(Exception ex) {
ErrorViewer.showError(ex, ForgeProps.getLocalized(ERRORS.OTHER), cards[card].name,
cards[card].url);
// throw new RuntimeException("Gui_DownloadPictures : error 1 - " +ex);
break;
}
}//for
}
close.setText(ForgeProps.getLocalized(BUTTONS.CLOSE));
}//run
public static void startDownload(JFrame frame) {
final Card[] card = getNeededCards();
if(card.length == 0) {
JOptionPane.showMessageDialog(frame, ForgeProps.getLocalized(NO_MORE));
return;
}
Gui_DownloadPictures download = new Gui_DownloadPictures(card);
JDialog dlg = download.getDlg(frame);
dlg.setVisible(true);
dlg.dispose();
download.setCancel(true);
}//startDownload()
private static Card[] getNeededCards() {
//read all card names and urls
Card[] card = readFile();
ArrayList<Card> list = new ArrayList<Card>();
File file;
File base = ForgeProps.getFile(IMAGE_BASE);
//check to see which cards we already have
for(int i = 0; i < card.length; i++) {
file = new File(base, card[i].name);
if(!file.exists()) list.add(card[i]);
}
//return all card names and urls that are needed
Card[] out = new Card[list.size()];
list.toArray(out);
// for(int i = 0; i < out.length; i++)
// System.out.println(out[i].name +" " +out[i].url);
return out;
}//getNeededCards()
private static Card[] readFile() {
try {
BufferedReader in = new BufferedReader(new FileReader(ForgeProps.getFile(CARD_PICTURES)));
String line;
ArrayList<Card> list = new ArrayList<Card>();
StringTokenizer tok;
line = in.readLine();
while(line != null && (!line.equals(""))) {
tok = new StringTokenizer(line);
list.add(new Card(tok.nextToken(), tok.nextToken()));
line = in.readLine();
}
Card[] out = new Card[list.size()];
list.toArray(out);
return out;
} catch(Exception ex) {
ErrorViewer.showError(ex, "Gui_DownloadPictures: readFile() error");
throw new RuntimeException("Gui_DownloadPictures : readFile() error");
}
}//readFile()
private class ProxyHandler implements ChangeListener {
private int type;
public ProxyHandler(int type) {
this.type = type;
}
public void stateChanged(ChangeEvent e) {
if(((AbstractButton) e.getSource()).isSelected()) {
Gui_DownloadPictures.this.type = type;
addr.setEnabled(type != 0);
port.setEnabled(type != 0);
}
}
}
private static class Card {
final public String name;
final public String url;
Card(String cardName, String cardURL) {
name = cardName;
url = cardURL;
}
}//Card
}

View File

@@ -0,0 +1,131 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Gui_MultipleBlockers extends JFrame
{
private static final long serialVersionUID = -3585314684734680978L;
private int assignDamage;
private Card att;
private GuiDisplay2 guiDisplay;
private BorderLayout borderLayout1 = new BorderLayout();
private JPanel mainPanel = new JPanel();
private JScrollPane jScrollPane1 = new JScrollPane();
private JLabel numberLabel = new JLabel();
private JPanel jPanel3 = new JPanel();
private BorderLayout borderLayout3 = new BorderLayout();
private JPanel creaturePanel = new JPanel();
public static void main(String[] args)
{
CardList list = new CardList();
list.add(AllZone.CardFactory.getCard("Elvish Piper", ""));
list.add(AllZone.CardFactory.getCard("Lantern Kami", ""));
list.add(AllZone.CardFactory.getCard("Frostling", ""));
list.add(AllZone.CardFactory.getCard("Frostling", ""));
for(int i = 0; i < 2; i++)
new Gui_MultipleBlockers(list.get(i),list, i+1, null);
}
@SuppressWarnings("deprecation") // dialog.show is deprecated
public Gui_MultipleBlockers(Card attacker, CardList creatureList, int damage, GuiDisplay2 display)
{
this();
assignDamage = damage;
updateDamageLabel();//update user message about assigning damage
guiDisplay = display;
att = attacker;
for(int i = 0; i < creatureList.size(); i++)
creaturePanel.add(GuiDisplayUtil.getCardPanel(creatureList.get(i)));
JDialog dialog = new JDialog(this, true);
dialog.setTitle("Multiple Blockers");
dialog.setContentPane(mainPanel);
dialog.setSize(470, 260);
dialog.show();
}
public Gui_MultipleBlockers() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
// setSize(470, 280);
// show();
}
private void jbInit() throws Exception {
this.getContentPane().setLayout(borderLayout1);
this.setTitle("Multiple Blockers");
mainPanel.setLayout(null);
numberLabel.setHorizontalAlignment(SwingConstants.CENTER);
numberLabel.setHorizontalTextPosition(SwingConstants.CENTER);
numberLabel.setText("Assign");
numberLabel.setBounds(new Rectangle(52, 30, 343, 24));
jPanel3.setLayout(borderLayout3);
jPanel3.setBounds(new Rectangle(26, 75, 399, 114));
creaturePanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(MouseEvent e) {
creaturePanel_mousePressed(e);
}
});
creaturePanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
creaturePanel_mouseMoved(e);
}
});
mainPanel.add(jPanel3, null);
jPanel3.add(jScrollPane1, BorderLayout.CENTER);
mainPanel.add(numberLabel, null);
jScrollPane1.getViewport().add(creaturePanel, null);
this.getContentPane().add(mainPanel, BorderLayout.CENTER);
}
void okButton_actionPerformed(ActionEvent e) {
dispose();
}
void creaturePanel_mousePressed(MouseEvent e) {
Object o = creaturePanel.getComponentAt(e.getPoint());
if(o instanceof CardPanel)
{
CardPanel cardPanel = (CardPanel)o;
Card c = cardPanel.getCard();
CardList cl = new CardList();
cl.add(att);
AllZone.GameAction.setAssignedDamage(c, cl, c.getAssignedDamage() + 1);
//c.setAssignedDamage(c.getAssignedDamage() + 1);
if(guiDisplay != null)
guiDisplay.updateCardDetail(c);
}
//reduce damage, show new user message, exit if necessary
assignDamage--;
updateDamageLabel();
if(assignDamage == 0)
dispose();
}//creaturePanel_mousePressed()
void updateDamageLabel()
{
numberLabel.setText("Assign " +assignDamage +" damage - click on card to assign damage");
}
void creaturePanel_mouseMoved(MouseEvent e)
{
Object o = creaturePanel.getComponentAt(e.getPoint());
if(o instanceof CardPanel)
{
CardPanel cardPanel = (CardPanel)o;
Card c = cardPanel.getCard();
if(guiDisplay != null)
guiDisplay.updateCardDetail(c);
}
}
}

670
src/Gui_NewGame.java Normal file
View File

@@ -0,0 +1,670 @@
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import forge.error.ErrorViewer;
import forge.error.ExceptionHandler;
import forge.gui.ListChooser;
import forge.properties.ForgeProps;
import forge.properties.NewConstants;
import forge.properties.NewConstants.LANG.Gui_NewGame.MENU_BAR.MENU;
import forge.properties.NewConstants.LANG.Gui_NewGame.MENU_BAR.OPTIONS;
public class Gui_NewGame extends JFrame implements NewConstants, NewConstants.LANG.Gui_NewGame {
private static final long serialVersionUID = -2437047615019135648L;
private final DeckIO deckIO = new DeckIO(ForgeProps.getFile(DECKS));
private final DeckIO boosterDeckIO = new DeckIO(ForgeProps.getFile(BOOSTER_DECKS));
private ArrayList<Deck> allDecks;
private static Gui_DeckEditor editor;
private JLabel titleLabel = new JLabel();
private JLabel jLabel2 = new JLabel();
private JLabel jLabel3 = new JLabel();
private JComboBox humanComboBox = new JComboBox();
private JComboBox computerComboBox = new JComboBox();
private JButton deckEditorButton = new JButton();
private JButton startButton = new JButton();
private ButtonGroup buttonGroup1 = new ButtonGroup();
private JRadioButton sealedRadioButton = new JRadioButton();
private JRadioButton singleRadioButton = new JRadioButton();
private JPanel jPanel2 = new JPanel();
private Border border1;
private TitledBorder titledBorder1;
private JRadioButton draftRadioButton = new JRadioButton();
private JPanel jPanel1 = new JPanel();
private Border border2;
@SuppressWarnings("unused")
// titledBorder2
private TitledBorder titledBorder2;
private static JCheckBox newGuiCheckBox = new JCheckBox("", true);
private static JCheckBox smoothLandCheckBox = new JCheckBox("", true);
// GenerateConstructedDeck.get2Colors() and GenerateSealedDeck.get2Colors()
// use these two variables
public static JCheckBoxMenuItem removeSmallCreatures = new JCheckBoxMenuItem(
ForgeProps.getLocalized(MENU_BAR.OPTIONS.GENERATE.REMOVE_SMALL));
public static JCheckBoxMenuItem removeArtifacts = new JCheckBoxMenuItem(
ForgeProps.getLocalized(MENU_BAR.OPTIONS.GENERATE.REMOVE_ARTIFACTS));
private JButton questButton = new JButton();
private Action LOOK_AND_FEEL_ACTION = new LookAndFeelAction(this);
private Action DOWNLOAD_ACTION = new DownloadAction();
private Action CARD_SIZES_ACTION = new CardSizesAction();
private Action ABOUT_ACTION = new AboutAction();
public static void main(String[] args) {
ExceptionHandler.registerErrorHandling();
try {
Object[] o = UIManager.getInstalledLookAndFeels();
if(o.length > 3) {
final Color background = new Color(204, 204, 204);
String[] properties = {
"Panel.background", "Panel.background", "JPanel.background", "Button.background",
"RadioButton.background", "MenuBar.background", "Menu.background", "JMenu.background",
"ComboBox.background", "MenuItem.background", "JCheckBoxMenuItem.background",
"Dialog.background", "OptionPane.background", "ScrollBar.background"};
for(int i = 0; i < properties.length; i++) {
//UIManager.put(properties, background);
UIManager.put(properties[i], background);
}
}
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
try {
Constant.Runtime.GameType[0] = Constant.GameType.Constructed;
AllZone.Computer = new ComputerAI_Input(new ComputerAI_General());
new Gui_NewGame();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
}
public Gui_NewGame() {
AllZone.QuestData = null;
allDecks = getDecks();
Constant.Runtime.WinLose.reset();
if(Constant.Runtime.width[0] == 0) Constant.Runtime.width[0] = 70;
if(Constant.Runtime.height[0] == 0) Constant.Runtime.height[0] = 98;
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
if(Constant.Runtime.GameType[0].equals(Constant.GameType.Constructed)) {
singleRadioButton.setSelected(true);
updateDeckComboBoxes();
}
if(Constant.Runtime.GameType[0].equals(Constant.GameType.Sealed)) {
sealedRadioButton.setSelected(true);
updateDeckComboBoxes();
}
if(Constant.Runtime.GameType[0].equals(Constant.GameType.Draft)) {
draftRadioButton.setSelected(true);
draftRadioButton_actionPerformed(null);
}
addListeners();
Dimension screen = getToolkit().getScreenSize();
Rectangle bounds = getBounds();
bounds.width = 460;
bounds.height = 560;
bounds.x = (screen.width - bounds.width) / 2;
bounds.y = (screen.height - bounds.height) / 2;
setBounds(bounds);
setTitle(ForgeProps.getLocalized(LANG.PROGRAM_NAME));
setupMenu();
setVisible(true);
}// init()
private void setupMenu() {
Action[] actions = {
LOOK_AND_FEEL_ACTION, DOWNLOAD_ACTION, CARD_SIZES_ACTION, ErrorViewer.ALL_THREADS_ACTION,
ABOUT_ACTION};
JMenu menu = new JMenu(ForgeProps.getLocalized(MENU.TITLE));
for(Action a:actions)
menu.add(a);
// new stuff
JMenu generatedDeck = new JMenu(ForgeProps.getLocalized(MENU_BAR.OPTIONS.GENERATE.TITLE));
generatedDeck.add(removeSmallCreatures);
generatedDeck.add(removeArtifacts);
JMenu optionsMenu = new JMenu(ForgeProps.getLocalized(OPTIONS.TITLE));
optionsMenu.add(generatedDeck);
JMenuBar bar = new JMenuBar();
bar.add(menu);
bar.add(optionsMenu);
bar.add(new MenuItem_HowToPlay());
setJMenuBar(bar);
}
// returns, ArrayList of Deck objects
private ArrayList<Deck> getDecks() {
ArrayList<Deck> list = new ArrayList<Deck>();
Deck[] deck = deckIO.getDecks();
for(int i = 0; i < deck.length; i++)
list.add(deck[i]);
Collections.sort(list, new DeckSort());
return list;
}
private void addListeners() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent ev) {
System.exit(0);
}
});
questButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
// close this windows
// can't use this.dispose() because "this" object is an
// ActionListener
Gui_NewGame.this.dispose();
new Gui_QuestOptions();
}
});
}// addListeners()
@SuppressWarnings("unused")
// setupSealed
private void setupSealed() {
Deck deck = new Deck(Constant.GameType.Sealed);
ReadBoosterPack booster = new ReadBoosterPack();
CardList pack = booster.getBoosterPack5();
for(int i = 0; i < pack.size(); i++)
deck.addSideboard(pack.get(i).getName());
Constant.Runtime.HumanDeck[0] = deck;
}
private void jbInit() throws Exception {
border1 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder1 = new TitledBorder(border1, "Game Type");
border2 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder2 = new TitledBorder(border2, "Library");
titleLabel.setBounds(new Rectangle(155, 8, 171, 57));
titleLabel.setText("New Game");
titleLabel.setFont(new java.awt.Font("Dialog", 0, 26));
this.getContentPane().setLayout(null);
jLabel2.setText("Your Deck");
jLabel2.setBounds(new Rectangle(9, 12, 85, 27));
jLabel3.setText("Opponent");
jLabel3.setBounds(new Rectangle(9, 45, 85, 27));
humanComboBox.setBounds(new Rectangle(75, 14, 197, 23));
humanComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
humanComboBox_actionPerformed(e);
}
});
computerComboBox.setBounds(new Rectangle(75, 47, 197, 23));
deckEditorButton.setBounds(new Rectangle(278, 24, 124, 36));
deckEditorButton.setToolTipText("");
deckEditorButton.setText("Deck Editor");
deckEditorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
deckEditorButton_actionPerformed(e);
}
});
startButton.setBounds(new Rectangle(159, 375, 139, 54));
startButton.setFont(new java.awt.Font("Dialog", 0, 18));
startButton.setHorizontalTextPosition(SwingConstants.LEADING);
startButton.setText("Start Game");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
startButton_actionPerformed(e);
}
});
sealedRadioButton.setToolTipText("");
sealedRadioButton.setText("Sealed Deck (Medium) - Create your deck from 75 available cards");
sealedRadioButton.setBounds(new Rectangle(14, 51, 406, 28));
sealedRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
sealedRadioButton_actionPerformed(e);
}
});
singleRadioButton.setText("Constructed (Easy) - Use all of the cards to defeat the computer");
singleRadioButton.setBounds(new Rectangle(14, 17, 403, 31));
singleRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
singleRadioButton_actionPerformed(e);
}
});
jPanel2.setBorder(titledBorder1);
jPanel2.setBounds(new Rectangle(10, 71, 425, 120));
jPanel2.setLayout(null);
draftRadioButton.setToolTipText("");
draftRadioButton.setText("Booster Draft (Hard) - Pick cards 1 at a time to create your deck");
draftRadioButton.setBounds(new Rectangle(14, 82, 399, 25));
draftRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
draftRadioButton_actionPerformed(e);
}
});
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setBounds(new Rectangle(10, 209, 425, 150));
jPanel1.setLayout(null);
newGuiCheckBox.setText("Resizable Game Area");
newGuiCheckBox.setBounds(new Rectangle(159, 305, 164, 25));
//newGuiCheckBox.setSelected(true);
smoothLandCheckBox.setText("Stack AI land");
smoothLandCheckBox.setBounds(new Rectangle(159, 330, 165, 25));
//smoothLandCheckBox.setSelected(true);
questButton.setBounds(new Rectangle(137, 435, 187, 53));
questButton.setFont(new java.awt.Font("Dialog", 0, 18));
questButton.setText("Quest Mode");
this.getContentPane().add(titleLabel, null);
jPanel1.add(computerComboBox, null);
jPanel1.add(humanComboBox, null);
jPanel1.add(jLabel2, null);
jPanel1.add(jLabel3, null);
jPanel1.add(deckEditorButton, null);
this.getContentPane().add(startButton, null);
this.getContentPane().add(newGuiCheckBox, null);
this.getContentPane().add(smoothLandCheckBox, null);
this.getContentPane().add(questButton, null);
this.getContentPane().add(jPanel2, null);
jPanel2.add(singleRadioButton, null);
jPanel2.add(sealedRadioButton, null);
jPanel2.add(draftRadioButton, null);
this.getContentPane().add(jPanel1, null);
buttonGroup1.add(singleRadioButton);
buttonGroup1.add(sealedRadioButton);
buttonGroup1.add(draftRadioButton);
}
void deckEditorButton_actionPerformed(ActionEvent e) {
if(editor == null) {
editor = new Gui_DeckEditor();
{
{
Command exit = new Command() {
private static final long serialVersionUID = -9133358399503226853L;
public void execute() {
new Gui_NewGame();
}
};
editor.show(exit);
editor.setVisible(true);
}//run()
}
}//if
editor.setVisible(true);
dispose();
}
Deck getRandomDeck(Deck[] d) {
//get a random number between 0 and d.length
int i = (int) (Math.random() * d.length);
return d[i];
}
void startButton_actionPerformed(ActionEvent e) {
if(humanComboBox.getSelectedItem() == null || computerComboBox.getSelectedItem() == null) return;
String human = humanComboBox.getSelectedItem().toString();
String computer = null;
if(computerComboBox.getSelectedItem() != null) computer = computerComboBox.getSelectedItem().toString();
if(draftRadioButton.isSelected()) {
if(human.equals("New Draft")) {
dispose();
Gui_BoosterDraft draft = new Gui_BoosterDraft();
draft.showGui(new BoosterDraft_1());
return;
} else//load old draft
{
Deck[] deck = boosterDeckIO.readBoosterDeck(human);
int index = Integer.parseInt(computer);
Constant.Runtime.HumanDeck[0] = deck[0];
Constant.Runtime.ComputerDeck[0] = deck[index];
if(Constant.Runtime.ComputerDeck[0] == null) throw new RuntimeException(
"Gui_NewGame : startButton() error - computer deck is null");
}// else - load old draft
}// if
else {
// non-draft decks
String format = Constant.Runtime.GameType[0];
boolean sealed = Constant.GameType.Sealed.equals(format);
boolean constructed = Constant.GameType.Constructed.equals(format);
boolean humanGenerate = human.equals("Generate Deck");
boolean humanGenerateMulti3 = human.equals("Generate 3-Color Deck");
boolean humanGenerateMulti5 = human.equals("Generate 5-Color Gold Deck");
boolean humanRandom = human.equals("Random");
if(humanGenerate) {
if(constructed) Constant.Runtime.HumanDeck[0] = generateConstructedDeck();
else if(sealed) Constant.Runtime.HumanDeck[0] = generateSealedDeck();
}
else if (humanGenerateMulti3) {
if(constructed) Constant.Runtime.HumanDeck[0] = generateConstructed3ColorDeck();
}
else if (humanGenerateMulti5) {
if(constructed) Constant.Runtime.HumanDeck[0] = generateConstructed5ColorDeck();
}
else if(humanRandom) {
Constant.Runtime.HumanDeck[0] = getRandomDeck(getDecks(format));
JOptionPane.showMessageDialog(null, String.format("You are using deck: %s",
Constant.Runtime.HumanDeck[0].getName()), "Deck Name", JOptionPane.INFORMATION_MESSAGE);
}
else {
Constant.Runtime.HumanDeck[0] = deckIO.readDeck(human);
}
boolean computerGenerate = computer.equals("Generate Deck");
boolean computerGenerateMulti3 = computer.equals("Generate 3-Color Deck");
boolean computerGenerateMulti5 = computer.equals("Generate 5-Color Gold Deck");
boolean computerRandom = computer.equals("Random");
if(computerGenerate) {
if(constructed) Constant.Runtime.ComputerDeck[0] = generateConstructedDeck();
else if(sealed) Constant.Runtime.ComputerDeck[0] = generateSealedDeck();
}
else if (computerGenerateMulti3) {
if(constructed) Constant.Runtime.ComputerDeck[0] = generateConstructed3ColorDeck();
}
else if (computerGenerateMulti5) {
if(constructed) Constant.Runtime.ComputerDeck[0] = generateConstructed5ColorDeck();
}
else if(computerRandom) {
Constant.Runtime.ComputerDeck[0] = getRandomDeck(getDecks(format));
JOptionPane.showMessageDialog(null, String.format("The computer is using deck: %s",
Constant.Runtime.ComputerDeck[0].getName()), "Deck Name", JOptionPane.INFORMATION_MESSAGE);
} else {
Constant.Runtime.ComputerDeck[0] = deckIO.readDeck(computer);
}
}// else
//DO NOT CHANGE THIS ORDER, GuiDisplay needs to be created before cards are added
if(newGuiCheckBox.isSelected()) AllZone.Display = new GuiDisplay3();
else AllZone.Display = new GuiDisplay2();
if(smoothLandCheckBox.isSelected()) Constant.Runtime.smooth[0] = true;
else Constant.Runtime.smooth[0] = false;
AllZone.GameAction.newGame(Constant.Runtime.HumanDeck[0], Constant.Runtime.ComputerDeck[0]);
AllZone.Display.setVisible(true);
dispose();
}//startButton_actionPerformed()
private Deck generateSealedDeck() {
GenerateSealedDeck gen = new GenerateSealedDeck();
CardList name = gen.generateDeck();
Deck deck = new Deck(Constant.GameType.Sealed);
for(int i = 0; i < 40; i++)
deck.addMain(name.get(i).getName());
return deck;
}
private Deck generateConstructedDeck() {
GenerateConstructedDeck gen = new GenerateConstructedDeck();
CardList name = gen.generateDeck();
Deck deck = new Deck(Constant.GameType.Constructed);
for(int i = 0; i < 60; i++)
deck.addMain(name.get(i).getName());
return deck;
}
private Deck generateConstructed3ColorDeck() {
GenerateConstructedMultiColorDeck gen = new GenerateConstructedMultiColorDeck();
CardList name = gen.generate3ColorDeck();
Deck deck = new Deck(Constant.GameType.Constructed);
for(int i = 0; i < 60; i++)
deck.addMain(name.get(i).getName());
return deck;
}
private Deck generateConstructed5ColorDeck() {
GenerateConstructedMultiColorDeck gen = new GenerateConstructedMultiColorDeck();
CardList name = gen.generate5ColorDeck();
Deck deck = new Deck(Constant.GameType.Constructed);
for(int i = 0; i < 60; i++)
deck.addMain(name.get(i).getName());
return deck;
}
void singleRadioButton_actionPerformed(ActionEvent e) {
Constant.Runtime.GameType[0] = Constant.GameType.Constructed;
updateDeckComboBoxes();
}
void sealedRadioButton_actionPerformed(ActionEvent e) {
Constant.Runtime.GameType[0] = Constant.GameType.Sealed;
updateDeckComboBoxes();
}
private void updateDeckComboBoxes() {
humanComboBox.removeAllItems();
computerComboBox.removeAllItems();
if(Constant.GameType.Sealed.equals(Constant.Runtime.GameType[0])
|| Constant.GameType.Constructed.equals(Constant.Runtime.GameType[0])) {
humanComboBox.addItem("Generate Deck");
computerComboBox.addItem("Generate Deck");
humanComboBox.addItem("Generate 3-Color Deck");
computerComboBox.addItem("Generate 3-Color Deck");
humanComboBox.addItem("Generate 5-Color Gold Deck");
computerComboBox.addItem("Generate 5-Color Gold Deck");
humanComboBox.addItem("Random");
computerComboBox.addItem("Random");
}
Deck d;
for(int i = 0; i < allDecks.size(); i++) {
d = allDecks.get(i);
if(d.getDeckType().equals(Constant.Runtime.GameType[0])) {
humanComboBox.addItem(d.getName());
computerComboBox.addItem(d.getName());
}
}//for
//not sure if the code below is useful or not
//this will select the deck that you previously used
//if(Constant.Runtime.HumanDeck[0] != null)
// humanComboBox.setSelectedItem(Constant.Runtime.HumanDeck[0].getName());
}/*updateComboBoxes()*/
Deck[] getDecks(String gameType) {
ArrayList<Deck> list = new ArrayList<Deck>();
Deck d;
for(int i = 0; i < allDecks.size(); i++) {
d = allDecks.get(i);
if(d.getDeckType().equals(gameType)) list.add(d);
}//for
//convert ArrayList to Deck[]
Deck[] out = new Deck[list.size()];
list.toArray(out);
return out;
}//getDecks()
void draftRadioButton_actionPerformed(ActionEvent e) {
Constant.Runtime.GameType[0] = Constant.GameType.Draft;
humanComboBox.removeAllItems();
computerComboBox.removeAllItems();
humanComboBox.addItem("New Draft");
Object[] key = boosterDeckIO.getBoosterDecks().keySet().toArray();
Arrays.sort(key);
for(int i = 0; i < key.length; i++)
humanComboBox.addItem(key[i]);
for(int i = 0; i < 7; i++)
computerComboBox.addItem("" + (i + 1));
}
void humanComboBox_actionPerformed(ActionEvent e) {
}/* draftRadioButton_actionPerformed() */
public static class LookAndFeelAction extends AbstractAction {
private static final long serialVersionUID = -4447498333866711215L;
private Component c;
public LookAndFeelAction(Component c) {
super(ForgeProps.getLocalized(MENU_BAR.MENU.LF));
this.c = c;
}
public void actionPerformed(ActionEvent e) {
LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
String[] keys = new String[info.length];
for(int i = 0; i < info.length; i++)
keys[i] = info[i].getName();
ListChooser<String> ch = new ListChooser<String>("Choose one", 0, 1, keys);
if(ch.show()) try {
int index = ch.getSelectedIndex();
if(index == -1) return;
UIManager.setLookAndFeel(info[index].getClassName());
SwingUtilities.updateComponentTreeUI(c);
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
}
}
public static class DownloadAction extends AbstractAction {
private static final long serialVersionUID = 6564425021778307101L;
public DownloadAction() {
super(ForgeProps.getLocalized(MENU_BAR.MENU.DOWNLOAD));
}
public void actionPerformed(ActionEvent e) {
Gui_DownloadPictures.startDownload(null);
}
}
public static class CardSizesAction extends AbstractAction {
private static final long serialVersionUID = -2900235618450319571L;
private String[] keys = {"Tiny", "Small", "Medium", "Large"};
private int[] widths = {42, 63, 70, 93};
private int[] heights = {59, 88, 98, 130};
public CardSizesAction() {
super(ForgeProps.getLocalized(MENU_BAR.MENU.CARD_SIZES));
}
public void actionPerformed(ActionEvent e) {
ListChooser<String> ch = new ListChooser<String>("Choose one", "Choose a new card size", 0, 1, keys);
if(ch.show()) try {
int index = ch.getSelectedIndex();
if(index == -1) return;
Constant.Runtime.width[0] = widths[index];
Constant.Runtime.height[0] = heights[index];
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
}
}
public static class AboutAction extends AbstractAction {
private static final long serialVersionUID = 5492173304463396871L;
public AboutAction() {
super(ForgeProps.getLocalized(MENU_BAR.MENU.ABOUT));
}
public void actionPerformed(ActionEvent e) {
JTextArea area = new JTextArea(8, 25);
Font f = new Font(area.getFont().getName(), Font.PLAIN, 13);
area.setFont(f);
area.setText("I enjoyed programming this project. I'm glad other people also enjoy my program. MTG Forge has turned out to be very successful.\n\nmtgrares@yahoo.com\nhttp://mtgrares.blogspot.com\n\nWritten by: Forge");
area.setWrapStyleWord(true);
area.setLineWrap(true);
area.setEditable(false);
JPanel p = new JPanel();
area.setBackground(p.getBackground());
JOptionPane.showMessageDialog(null, area, "About", JOptionPane.INFORMATION_MESSAGE);
}
}
}

241
src/Gui_Quest.java Normal file
View File

@@ -0,0 +1,241 @@
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
//presumes AllZone.QuestData is not null
//AllZone.QuestData should be set by Gui_QuestOptions
public class Gui_Quest extends JFrame {
private static final long serialVersionUID = -6432089669283627896L;
private QuestData questData;
private JLabel jLabel1 = new JLabel();
private JLabel difficultlyLabel = new JLabel();
private JLabel winLostLabel = new JLabel();
private JLabel rankLabel = new JLabel();
@SuppressWarnings("unused")
// border1
private Border border1;
private TitledBorder titledBorder1;
private JButton deckEditorButton = new JButton();
private JPanel jPanel2 = new JPanel();
private JButton playGameButton = new JButton();
private JRadioButton oppTwoRadio = new JRadioButton();
private JRadioButton oppOneRadio = new JRadioButton();
private JRadioButton oppThreeRadio = new JRadioButton();
private JLabel jLabel5 = new JLabel();
private JComboBox deckComboBox = new JComboBox();
private ButtonGroup oppGroup = new ButtonGroup();
private static JCheckBox smoothLandCheckBox = new JCheckBox("", true);
private static JCheckBox resizeCheckbox = new JCheckBox("", true);
public static void main(String[] args) {
new Gui_Quest();
}
public Gui_Quest() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
questData = AllZone.QuestData;
setup();
setVisible(true);
}
private void setup() {
//center window on the screen
Dimension screen = this.getToolkit().getScreenSize();
setBounds(screen.width / 4, 50, //position
500, 500); //size
//if user closes this window, go back to "Quest Options" screen
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent ev) {
Gui_Quest.this.dispose();
new Gui_QuestOptions();
}
});
//set labels
difficultlyLabel.setText(questData.getDifficulty());
rankLabel.setText(questData.getRank());
String s = questData.getWin() + " wins / " + questData.getLost() + " losses";
winLostLabel.setText(s);
String[] op = questData.getOpponents();
oppOneRadio.setText(op[0]);
oppTwoRadio.setText(op[1]);
oppThreeRadio.setText(op[2]);
//get deck names as Strings
ArrayList<String> list = questData.getDeckNames();
Collections.sort(list);
for(int i = 0; i < list.size(); i++)
deckComboBox.addItem(list.get(i));
if(Constant.Runtime.HumanDeck[0] != null)
deckComboBox.setSelectedItem(Constant.Runtime.HumanDeck[0].getName());
}//setup()
private void jbInit() throws Exception {
border1 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)),
"Choices");
jLabel1.setFont(new java.awt.Font("Dialog", 0, 25));
jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
jLabel1.setText("Quest Mode");
jLabel1.setBounds(new Rectangle(1, 7, 453, 45));
this.setResizable(false);
this.setTitle("Quest Mode");
this.getContentPane().setLayout(null);
difficultlyLabel.setText("Medium");
difficultlyLabel.setBounds(new Rectangle(1, 52, 453, 41));
difficultlyLabel.setFont(new java.awt.Font("Dialog", 0, 25));
difficultlyLabel.setHorizontalAlignment(SwingConstants.CENTER);
winLostLabel.setText("23 wins / 10 loses");
winLostLabel.setBounds(new Rectangle(1, 130, 453, 43));
winLostLabel.setFont(new java.awt.Font("Dialog", 0, 25));
winLostLabel.setHorizontalAlignment(SwingConstants.CENTER);
winLostLabel.setHorizontalTextPosition(SwingConstants.CENTER);
rankLabel.setText("Card Flopper");
rankLabel.setBounds(new Rectangle(1, 93, 453, 37));
rankLabel.setFont(new java.awt.Font("Dialog", 0, 25));
rankLabel.setHorizontalAlignment(SwingConstants.CENTER);
deckEditorButton.setBounds(new Rectangle(291, 123, 142, 38));
deckEditorButton.setFont(new java.awt.Font("Dialog", 0, 18));
deckEditorButton.setText("Deck Editor");
deckEditorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
deckEditorButton_actionPerformed(e);
}
});
jPanel2.setBorder(titledBorder1);
jPanel2.setBounds(new Rectangle(39, 173, 441, 173));
jPanel2.setLayout(null);
playGameButton.setBounds(new Rectangle(150, 418, 161, 37));
playGameButton.setFont(new java.awt.Font("Dialog", 0, 18));
playGameButton.setText("Play Game");
playGameButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
playGameButton_actionPerformed(e);
}
});
oppTwoRadio.setText("Bob");
oppTwoRadio.setBounds(new Rectangle(15, 50, 397, 41));
oppOneRadio.setSelected(true);
oppOneRadio.setText("Sam");
oppOneRadio.setBounds(new Rectangle(15, 18, 392, 33));
oppThreeRadio.setText("Generated Deck");
oppThreeRadio.setBounds(new Rectangle(15, 91, 406, 25));
jLabel5.setText("Your Deck:");
jLabel5.setBounds(new Rectangle(15, 126, 125, 29));
deckComboBox.setBounds(new Rectangle(98, 127, 185, 29));
smoothLandCheckBox.setText("Stack AI land");
smoothLandCheckBox.setBounds(new Rectangle(154, 385, 153, 21));
//smoothLandCheckBox.setSelected(true);
resizeCheckbox.setText("Resizable Game Area");
resizeCheckbox.setBounds(new Rectangle(154, 354, 156, 24));
//resizeCheckbox.setSelected(true);
this.getContentPane().add(rankLabel, null);
this.getContentPane().add(jLabel1, null);
this.getContentPane().add(difficultlyLabel, null);
this.getContentPane().add(winLostLabel, null);
jPanel2.add(jLabel5, null);
jPanel2.add(deckComboBox, null);
jPanel2.add(oppOneRadio, null);
jPanel2.add(oppTwoRadio, null);
jPanel2.add(oppThreeRadio, null);
jPanel2.add(deckEditorButton, null);
this.getContentPane().add(playGameButton, null);
this.getContentPane().add(smoothLandCheckBox, null);
this.getContentPane().add(resizeCheckbox, null);
this.getContentPane().add(jPanel2, null);
oppGroup.add(oppOneRadio);
oppGroup.add(oppTwoRadio);
oppGroup.add(oppThreeRadio);
}
void deckEditorButton_actionPerformed(ActionEvent e) {
Command exit = new Command() {
private static final long serialVersionUID = -5110231879441074581L;
public void execute() {
//saves all deck data
QuestData.saveData(AllZone.QuestData);
new Gui_Quest();
}
};
Gui_Quest_DeckEditor g = new Gui_Quest_DeckEditor();
g.show(exit);
g.setVisible(true);
this.dispose();
}//deck editor button
void playGameButton_actionPerformed(ActionEvent e) {
Object check = deckComboBox.getSelectedItem();
if(check == null || getOpponent().equals("")) return;
Deck human = questData.getDeck(check.toString());
Deck computer = questData.ai_getDeck(getOpponent());
Constant.Runtime.HumanDeck[0] = human;
Constant.Runtime.ComputerDeck[0] = computer;
//smoothLandCheckBox.isSelected() - for the AI
//DO NOT CHANGE THIS ORDER, GuiDisplay needs to be created before cards are added
if(resizeCheckbox.isSelected()) AllZone.Display = new GuiDisplay3();
else AllZone.Display = new GuiDisplay2();
if(smoothLandCheckBox.isSelected()) Constant.Runtime.smooth[0] = true;
else Constant.Runtime.smooth[0] = false;
AllZone.GameAction.newGame(human, computer);
AllZone.Display.setVisible(true);
//end - you can change stuff after this
//close this window
dispose();
}//play game button
String getOpponent() {
if(oppOneRadio.isSelected()) return oppOneRadio.getText();
else if(oppTwoRadio.isSelected()) return oppTwoRadio.getText();
else if(oppThreeRadio.isSelected()) return oppThreeRadio.getText();
return "";
}
}

207
src/Gui_QuestOptions.java Normal file
View File

@@ -0,0 +1,207 @@
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class Gui_QuestOptions extends JFrame {
private static final long serialVersionUID = 2018518804206822235L;
private QuestData questData = new QuestData();
private JLabel jLabel1 = new JLabel();
private JButton continueQuestButton = new JButton();
private JPanel jPanel1 = new JPanel();
@SuppressWarnings("unused")
// border1
private Border border1;
private TitledBorder titledBorder1;
private JPanel jPanel2 = new JPanel();
private GridLayout gridLayout1 = new GridLayout();
private JRadioButton easyRadio = new JRadioButton();
private JRadioButton hardRadio = new JRadioButton();
private JRadioButton mediumRadio = new JRadioButton();
private JRadioButton veryHardRadio = new JRadioButton();
private JButton newQuestButton = new JButton();
private JTextArea jTextArea1 = new JTextArea();
private ButtonGroup buttonGroup1 = new ButtonGroup();
private JPanel jPanel3 = new JPanel();
private Border border2;
private TitledBorder titledBorder2;
public static void main(String[] args) {
new Gui_QuestOptions();
}
public Gui_QuestOptions() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
setup();
setupRadioButtonText();
setVisible(true);
}
private void setup() {
//make the text look correct on the screen
jTextArea1.setBackground(getBackground());
//center window on the screen
Dimension screen = this.getToolkit().getScreenSize();
setBounds(screen.width / 4, 50, //position
420, 490); //size
//if user closes this window, go back to "New Game" screen
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent ev) {
Gui_QuestOptions.this.dispose();
new Gui_NewGame();
}
});
//is there any saved data?
if(!questData.hasSaveFile()) continueQuestButton.setEnabled(false);
}//setup()
//show total number of games for each difficulty
private void setupRadioButtonText() {
String[] diff = questData.getDifficutlyChoices();
JRadioButton[] b = {easyRadio, mediumRadio, hardRadio, veryHardRadio};
for(int i = 0; i < diff.length; i++) {
b[i].setText(diff[i] + " - " + questData.getTotalNumberOfGames(diff[i]));
}
}//setupRadioButtonText()
private void jbInit() throws Exception {
border1 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140)),
"Quest Length");
border2 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder2 = new TitledBorder(border2, "Continue");
jLabel1.setFont(new java.awt.Font("Dialog", 0, 25));
jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
jLabel1.setText("Quest Options");
jLabel1.setBounds(new Rectangle(104, 0, 213, 63));
this.setTitle("Quest Options");
this.getContentPane().setLayout(null);
continueQuestButton.setBounds(new Rectangle(70, 23, 159, 35));
continueQuestButton.setFont(new java.awt.Font("Dialog", 0, 18));
continueQuestButton.setText("Continue Quest");
continueQuestButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
continueQuestButton_actionPerformed(e);
}
});
jPanel1.setBorder(titledBorder1);
jPanel1.setBounds(new Rectangle(67, 63, 303, 259));
jPanel1.setLayout(null);
jPanel2.setBounds(new Rectangle(12, 27, 271, 101));
jPanel2.setLayout(gridLayout1);
gridLayout1.setColumns(1);
gridLayout1.setRows(4);
easyRadio.setText("Easy - 50 games");
hardRadio.setText("Hard - 200 games");
mediumRadio.setText("Medium - 100 games");
veryHardRadio.setText("Very Hard - 300 games");
newQuestButton.setBounds(new Rectangle(78, 206, 145, 38));
newQuestButton.setFont(new java.awt.Font("Dialog", 0, 18));
newQuestButton.setText("New Quest");
newQuestButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
newQuestButton_actionPerformed(e);
}
});
jTextArea1.setEnabled(false);
jTextArea1.setFont(new java.awt.Font("Dialog", 0, 14));
jTextArea1.setDisabledTextColor(Color.black);
jTextArea1.setEditable(false);
jTextArea1.setText("Note: Starting a new quest will delete your current quest data");
jTextArea1.setLineWrap(true);
jTextArea1.setWrapStyleWord(true);
jTextArea1.setBounds(new Rectangle(13, 141, 274, 50));
jPanel3.setBorder(titledBorder2);
jPanel3.setBounds(new Rectangle(68, 338, 289, 86));
jPanel3.setLayout(null);
jPanel2.add(easyRadio, null);
jPanel2.add(mediumRadio, null);
jPanel2.add(hardRadio, null);
jPanel2.add(veryHardRadio, null);
jPanel1.add(newQuestButton, null);
jPanel1.add(jTextArea1, null);
this.getContentPane().add(jPanel1, null);
this.getContentPane().add(jPanel3, null);
jPanel3.add(continueQuestButton, null);
this.getContentPane().add(jLabel1, null);
jPanel1.add(jPanel2, null);
buttonGroup1.add(easyRadio);
buttonGroup1.add(mediumRadio);
buttonGroup1.add(hardRadio);
buttonGroup1.add(veryHardRadio);
}
void continueQuestButton_actionPerformed(ActionEvent e) {
//set global variable
AllZone.QuestData = QuestData.loadData();
dispose();
new Gui_Quest();
}
void newQuestButton_actionPerformed(ActionEvent e) {
String difficulty = "";
if(easyRadio.isSelected()) difficulty = questData.EASY;
else if(mediumRadio.isSelected()) difficulty = questData.MEDIUM;
else if(hardRadio.isSelected()) difficulty = questData.HARD;
else if(veryHardRadio.isSelected()) difficulty = questData.VERY_HARD;
else //user didn't select a difficulty
return;
//give the user a few cards to build a deck
questData.newGame(difficulty);
copyAIDecks(questData, QuestData.loadData());
QuestData.saveData(questData);
questData.readAIQuestDeckFiles();
//set global variable
AllZone.QuestData = questData;
dispose();
new Gui_Quest();
}
//copy AI decks from old to newData
void copyAIDecks(QuestData newData, QuestData old) {
ArrayList<String> a = old.ai_getDeckNames();
for(int i = 0; i < a.size(); i++)
newData.ai_addDeck(old.ai_getDeck(a.get(i).toString()));
}
}

View File

@@ -0,0 +1,744 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import forge.error.ErrorViewer;
public class Gui_Quest_DeckEditor extends JFrame implements CardDetail, DeckDisplay {
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 JPanel cardDetailPanel = new JPanel();
private Border border3;
private TitledBorder titledBorder3;
private JPanel picturePanel = new JPanel();
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 JLabel cdLabel4 = new JLabel();
private JLabel cdLabel1 = new JLabel();
private JLabel cdLabel2 = new JLabel();
private JLabel cdLabel3 = new JLabel();
private GridLayout gridLayout1 = new GridLayout();
private JLabel cdLabel5 = new JLabel();
private JTextArea cdTextArea = new JTextArea();
private BorderLayout borderLayout1 = new BorderLayout();
private JLabel statsLabel2 = new JLabel();
private JLabel jLabel1 = new JLabel();
private JCheckBox whiteCheckBox = new JCheckBox("W", true);
private JCheckBox blueCheckBox = new JCheckBox("U", true);
private JCheckBox blackCheckBox = new JCheckBox("B", true);
private JCheckBox redCheckBox = new JCheckBox("R", true);
private JCheckBox greenCheckBox = new JCheckBox("G", true);
private JCheckBox colorlessCheckBox = new JCheckBox("C", true);
private JCheckBox landCheckBox = new JCheckBox("Land", true);
private JCheckBox creatureCheckBox = new JCheckBox("Creature", true);
private JCheckBox sorceryCheckBox = new JCheckBox("Sorcery", true);
private JCheckBox instantCheckBox = new JCheckBox("Instant", true);
private JCheckBox planeswalkerCheckBox = new JCheckBox("Planeswalker", true);
private JCheckBox artifactCheckBox = new JCheckBox("Artifact", true);
private JCheckBox enchantmentCheckBox = new JCheckBox("Enchant", true);
private CardList top;
private CardList bottom;
public static void main(String[] args) {
}
@Override
public void setTitle(String message) {
super.setTitle(message);
}
public void updateDisplay(CardList top, CardList bottom) {
this.top = top;
this.bottom = bottom;
topModel.clear();
bottomModel.clear();
if (AllZone.NameChanger.shouldChangeCardName()) {
top = new CardList(AllZone.NameChanger.changeCard(top.toArray()));
bottom = new CardList(AllZone.NameChanger.changeCard(bottom
.toArray()));
}
Card c;
String cardName;
QuestData_BoosterPack pack = new QuestData_BoosterPack();
ArrayList<String> addedList = AllZone.QuestData.getAddedCards();
//update top
for(int i = 0; i < top.size(); i++) {
c = top.get(i);
cardName = c.getName();
c.setRarity(pack.getRarity(cardName));
if(addedList.contains(cardName)) c.setRarity("new");
topModel.addCard(c);
}//for
//update bottom
for(int i = 0; i < bottom.size(); i++) {
c = bottom.get(i);
c.setRarity(pack.getRarity(c.getName()));;
bottomModel.addCard(c);
}//for
topModel.resort();
bottomModel.resort();
}//updateDisplay
public void updateDisplay() {
//updateDisplay(this.top, this.bottom);
topModel.clear();
if (AllZone.NameChanger.shouldChangeCardName()) {
top = new CardList(AllZone.NameChanger.changeCard(top.toArray()));
bottom = new CardList(AllZone.NameChanger.changeCard(bottom
.toArray()));
}
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.NameChanger.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();
}
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;
}
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;
}
public TableModel getTopTableModel() {
return topModel;
}
//top shows available card pool
public CardList getTop() {
return topModel.getCards();
}
//bottom shows cards that the user has chosen for his library
public CardList getBottom() {
return bottomModel.getCards();
}
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);
QuestData questData = AllZone.QuestData;
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.CardFactory.getCard(deck.getMain(i), ""));
}
ArrayList<String> list = AllZone.QuestData.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)
private void addListeners()
{
}//addListeners()
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);
//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()
private String getStats(CardList deck) {
int total = deck.size();
int creature = deck.getType("Creature").size();
int land = deck.getType("Land").size();
String show = "Total - " + total + ", Creatures - " + creature + ", Land - " + land;
String[] color = Constant.Color.Colors;
for(int i = 0; i < 5; i++)
show += ", " + color[i] + " - " + CardListUtil.getColor(deck, color[i]).size();
return show;
}//getStats()
public Gui_Quest_DeckEditor() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
}
public void updateCardDetail(Card c) {
//change card name if needed
c = AllZone.CardFactory.copyCard(c);
if(AllZone.NameChanger.shouldChangeCardName()) c = AllZone.NameChanger.changeCard(c);
CardDetailUtil.updateCardDetail(c, cdTextArea, cardDetailPanel, picturePanel, new JLabel[] {
cdLabel1, cdLabel2, cdLabel3, cdLabel4, cdLabel5});
}
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");
border3 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder3 = new TitledBorder(border3, "Card Detail");
this.getContentPane().setLayout(null);
jScrollPane1.setBorder(titledBorder1);
jScrollPane1.setBounds(new Rectangle(19, 28, 726, 346));
jScrollPane2.getViewport().setBackground(new Color(204, 204, 204));
jScrollPane2.setBorder(titledBorder2);
jScrollPane2.setBounds(new Rectangle(19, 458, 726, 218));
removeButton.setBounds(new Rectangle(180, 403, 146, 49));
removeButton.setIcon(upIcon);
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);
addButton.setFont(new java.awt.Font("Dialog", 0, 13));
addButton.setBounds(new Rectangle(23, 403, 146, 49));
/**
* Type filtering
*/
Font f = new Font("Tahoma", Font.PLAIN, 10);
landCheckBox.setBounds(340, 400, 48, 20);
landCheckBox.setFont(f);
landCheckBox.setOpaque(false);
landCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
creatureCheckBox.setBounds(385, 400, 65, 20);
creatureCheckBox.setFont(f);
creatureCheckBox.setOpaque(false);
creatureCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
sorceryCheckBox.setBounds(447, 400, 62, 20);
sorceryCheckBox.setFont(f);
sorceryCheckBox.setOpaque(false);
sorceryCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
instantCheckBox.setBounds(505, 400, 60, 20);
instantCheckBox.setFont(f);
instantCheckBox.setOpaque(false);
instantCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
planeswalkerCheckBox.setBounds(558, 400, 85, 20);
planeswalkerCheckBox.setFont(f);
planeswalkerCheckBox.setOpaque(false);
planeswalkerCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
artifactCheckBox.setBounds(638, 400, 58, 20);
artifactCheckBox.setFont(f);
artifactCheckBox.setOpaque(false);
artifactCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateDisplay();
}
});
enchantmentCheckBox.setBounds(692, 400, 80, 20);
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
*/
cardDetailPanel.setBorder(titledBorder3);
cardDetailPanel.setBounds(new Rectangle(765, 23, 239, 323));
cardDetailPanel.setLayout(null);
picturePanel.setBorder(BorderFactory.createEtchedBorder());
picturePanel.setBounds(new Rectangle(772, 362, 226, 301));
picturePanel.setLayout(borderLayout1);
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");
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);
cdLabel4.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel4.setHorizontalAlignment(SwingConstants.LEFT);
cdLabel1.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel1.setHorizontalAlignment(SwingConstants.CENTER);
cdLabel2.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel2.setHorizontalAlignment(SwingConstants.CENTER);
cdLabel3.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel3.setHorizontalAlignment(SwingConstants.CENTER);
gridLayout1.setColumns(1);
gridLayout1.setRows(0);
cdLabel5.setFont(new java.awt.Font("Dialog", 0, 14));
cdLabel5.setHorizontalAlignment(SwingConstants.LEFT);
cdTextArea.setFont(new java.awt.Font("Dialog", 0, 12));
cdTextArea.setLineWrap(true);
cdTextArea.setWrapStyleWord(true);
statsLabel2.setBounds(new Rectangle(19, 371, 720, 31));
statsLabel2.setText("Total - 0, Creatures - 0 Land - 0");
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, 9, 400, 19));
this.getContentPane().add(cardDetailPanel, null);
cardDetailPanel.add(jScrollPane3, null);
jScrollPane3.getViewport().add(cdTextArea, null);
cardDetailPanel.add(jPanel3, null);
jPanel3.add(cdLabel1, null);
jPanel3.add(cdLabel2, null);
jPanel3.add(cdLabel3, null);
jPanel3.add(cdLabel4, null);
this.getContentPane().add(picturePanel, null);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(jScrollPane2, null);
this.getContentPane().add(addButton, null);
this.getContentPane().add(removeButton, 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);
jPanel3.add(cdLabel5, 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);
}
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(!Constant.GameType.Constructed.equals(customMenu.getGameType())) {
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
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)
}//removeButton_actionPerformed
@SuppressWarnings("unused")
// stats_actionPerformed
private void stats_actionPerformed(CardList list) {
}
//refresh Gui from deck, Gui shows the cards in the deck
@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.CardFactory.getCard(deck.getMain(i), Constant.Player.Human);
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.CardFactory.getCard(deck.getSideboard(i), Constant.Player.Human);
c.setRarity(pack.getRarity(c.getName()));
topModel.addCard(c);
}
}
else
{
CardList all = AllZone.CardFactory.getAllCards();
for(int i = 0; i < all.size(); i++)
topModel.addCard(all.get(i));
}
topModel.resort();
bottomModel.resort();
}////refreshGui()
}

View File

@@ -0,0 +1,761 @@
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileFilter;
//presumes AllZone.QuestData is not null
public class Gui_Quest_DeckEditor_Menu extends JMenuBar {
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;
private final String deckEditorName = "Deck Editor";
//used for import and export, try to made the gui user friendly
private static File previousDirectory = null;
private Command exitCommand;
private QuestData questData;
private Deck currentDeck;
//the class DeckDisplay is in the file "Gui_DeckEditor_Menu.java"
private DeckDisplay deckDisplay;
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.QuestData;
exitCommand = exit;
setupMenu();
if(canEditComputerDecks) setupComputerMenu();
}
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(isHumanMenu);
}
});//import
export.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
exportDeck();
}
});//export
menu.add(import2);
menu.add(export);
}//addImportExport()
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()
@SuppressWarnings("unchecked")
// TableSorter type safety
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.CardFactory.getCard(cardName, "");
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);
}
String text = "";
String newLine = "\r\n";
int count = 0;
text = all.size() + " Total Cards" + newLine + newLine;
//creatures
text += all.getType("Creature").size() + " Creatures" + newLine;
text += "-------------" + newLine;
for(int i = 0; i < noCopies.size(); i++) {
Card c = noCopies.get(i);
if(c.isCreature()) {
count = all.getName(c.getName()).size();
text += count + "x " + c.getName() + 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 += newLine + count + " Spells" + newLine;
text += "----------" + 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 += count + "x " + c.getName() + newLine;
}
}
//land
text += newLine + all.getType("Land").size() + " Land" + newLine;
text += "--------" + newLine;
for(int i = 0; i < noCopies.size(); i++) {
Card c = noCopies.get(i);
if(c.isLand()) {
count = all.getName(c.getName()).size();
text += count + "x " + c.getName() + newLine;
}
}
text += newLine;
return text;
}//getExportDeckText
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()
+ " : " + ex.getStackTrace());
}
}//exportDeckText()
private FileFilter getFileFilter() {
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File f) {
return f.getName().endsWith(".deck") || f.isDirectory();
}
@Override
public String getDescription() {
return "Deck File .deck";
}
};
return filter;
}//getFileFilter()
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()
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();
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();
ArrayList<String> list = questData.getCardpool();
for(int i = 0; i < list.size(); i++)
cardpool.add(AllZone.CardFactory.getCard(list.get(i).toString(), ""));
} else {
questData.ai_addDeck(deck);
cardpool = AllZone.CardFactory.getAllCards();
}
//convert Deck main to CardList
CardList deckList = new CardList();
for(int i = 0; i < deck.countMain(); i++)
deckList.add(AllZone.CardFactory.getCard(deck.getMain(i), ""));
//update gui
deckDisplay.updateDisplay(cardpool, deckList);
}//importDeck()
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
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) {
ArrayList<String> nameList = questData.ai_getDeckNames();
Collections.sort(nameList);
Deck deck;
String allText = "";
for(int i = 0; i < nameList.size(); i++) {
deck = questData.ai_getDeck(nameList.get(i).toString());
allText += deck.getName() + "\r\n";
allText += getExportDeckText(deck);
allText += "++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n \r\n";
}
JTextArea area = new JTextArea(allText, 30, 30);
JOptionPane.showMessageDialog(null, new JScrollPane(area));
}//actionPerformed()
});//viewAllDecks
//AI
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
String deckName = getUserInput_OpenDeck(questData.ai_getDeckNames());
//check if user selected "cancel"
if(deckName.equals("")) return;
setComputerPlayer(deckName);
Deck d = questData.ai_getDeck(deckName);
CardList deck = new CardList();
for(int i = 0; i < d.countMain(); i++)
deck.add(AllZone.CardFactory.getCard(d.getMain(i), ""));
CardList cardpool = AllZone.CardFactory.getAllCards();
deckDisplay.updateDisplay(cardpool, deck);
}
});//open
//AI
new2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
deckDisplay.updateDisplay(AllZone.CardFactory.getAllCards(), new CardList());
setComputerPlayer("");
}
});//new
//AI
rename.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
String name = getUserInput_GetDeckName(questData.ai_getDeckNames());
//check if user cancels
if(name.equals("")) return;
//is the current deck already saved and in QuestData?
if(questData.ai_getDeckNames().contains(currentDeck.getName()))
questData.ai_removeDeck(currentDeck.getName());//remove old deck
currentDeck.setName(name);
Deck deck = convertCardListToDeck(deckDisplay.getBottom());
deck.setName(name);
questData.ai_addDeck(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(questData.ai_getDeckNames());
//check if user cancels
if(name.equals("")) return;
}
setComputerPlayer(name);
Deck deck = convertCardListToDeck(deckDisplay.getBottom());
deck.setName(name);
questData.ai_addDeck(deck);
}
});//save
//AI
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
String name = getUserInput_GetDeckName(questData.ai_getDeckNames());
//check if user cancels
if(name.equals("")) return;
setComputerPlayer(name);
Deck deck = convertCardListToDeck(deckDisplay.getBottom());
deck.setName(name);
questData.ai_addDeck(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
questData.ai_removeDeck(currentDeck.getName());
//show card pool
CardList cardpool = AllZone.CardFactory.getAllCards();
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()
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++) {
deck.add(AllZone.CardFactory.getCard(d.getMain(i), ""));
//remove any cards that are in the deck from the card pool
cardpool.remove(d.getMain(i));
}
deckDisplay.updateDisplay(cardpool, deck);
}//openHumanDeck
//the usual menu options that will be used
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");
//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);
deckMenu.addSeparator();
addImportExport(deckMenu, true);
deckMenu.addSeparator();
deckMenu.add(delete);
deckMenu.addSeparator();
deckMenu.add(exit);
this.add(deckMenu);
}//setupMenu()
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
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);
}
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
private String cleanString(String in) {
String out = "";
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 += c[i];
return out;
}
//if user cancels, returns ""
private String getUserInput_GetDeckName(ArrayList<String> 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 ""
private String getUserInput_OpenDeck(ArrayList<String> deckNameList) {
ArrayList<String> 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]);
if(o == null) return "";
return o.toString();
}//getUserInput_OpenDeck()
//used by Gui_Quest_DeckEditor
public void close() {
exitCommand.execute();
}
//used by Gui_Quest_DeckEditor
public String getDeckName() {
return currentDeck.getName();
}
//used by Gui_Quest_DeckEditor
public String getGameType() {
return currentDeck.getDeckType();
}
//returns CardList of Card objects,
//argument ArrayList holds String card names
public static CardList covertToCardList(ArrayList<String> list) {
CardList c = new CardList();
Card card;
for(int i = 0; i < list.size(); i++) {
card = AllZone.CardFactory.getCard(list.get(i).toString(), "");
c.add(card);
}
return c;
}
}

61
src/Gui_SealedDeck.java Normal file
View File

@@ -0,0 +1,61 @@
import java.awt.FlowLayout;
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import forge.error.ErrorViewer;
public class Gui_SealedDeck extends JFrame {
private static final long serialVersionUID = -5073942967852403230L;
private JLabel jLabel1 = new JLabel();
private JPanel jPanel1 = new JPanel();
private JButton jButton3 = new JButton();
private JButton jButton2 = new JButton();
private FlowLayout flowLayout1 = new FlowLayout();
private JComboBox boosterComboBox = new JComboBox();
private JLabel jLabel5 = new JLabel();
private JLabel jLabel4 = new JLabel();
private JComboBox setComboBox = new JComboBox();
public Gui_SealedDeck() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
}
private void jbInit() throws Exception {
jLabel1.setBounds(new Rectangle(118, 14, 220, 69));
jLabel1.setText("Sealed Deck");
jLabel1.setFont(new java.awt.Font("Dialog", 0, 26));
this.getContentPane().setLayout(null);
jPanel1.setBounds(new Rectangle(89, 230, 237, 43));
jPanel1.setLayout(flowLayout1);
jButton3.setText("Next ->");
jButton2.setText("<- Back");
boosterComboBox.setBounds(new Rectangle(240, 173, 51, 23));
jLabel5.setText("Booster Packs Per Person");
jLabel5.setBounds(new Rectangle(89, 173, 164, 21));
jLabel4.setText("Set");
jLabel4.setBounds(new Rectangle(89, 121, 30, 15));
setComboBox.setBounds(new Rectangle(136, 115, 161, 23));
jPanel1.add(jButton2, null);
jPanel1.add(jButton3, null);
this.getContentPane().add(jLabel1, null);
this.getContentPane().add(setComboBox, null);
this.getContentPane().add(jLabel4, null);
this.getContentPane().add(jLabel5, null);
this.getContentPane().add(boosterComboBox, null);
this.getContentPane().add(jPanel1, null);
}
}

135
src/Gui_SetEditor.java Normal file
View File

@@ -0,0 +1,135 @@
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class Gui_SetEditor extends JFrame {
private static final long serialVersionUID = 519896860030378941L;
private JLabel jLabel1 = new JLabel();
private JScrollPane jScrollPane1 = new JScrollPane();
private JScrollPane jScrollPane2 = new JScrollPane();
private JPanel jPanel1 = new JPanel();
private Border border1;
private TitledBorder titledBorder1;
private JPanel jPanel2 = new JPanel();
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();
private JButton jButton3 = new JButton();
private JList jList1 = new JList();
private JList jList2 = new JList();
private JPanel jPanel3 = new JPanel();
private JButton jButton4 = new JButton();
private JButton jButton5 = new JButton();
private FlowLayout flowLayout1 = new FlowLayout();
private JLabel jLabel2 = new JLabel();
private JLabel jLabel3 = new JLabel();
private JButton jButton6 = new JButton();
private JButton jButton7 = new JButton();
private JPanel jPanel4 = new JPanel();
private Border border2;
private TitledBorder titledBorder2;
private JLabel jLabel5 = new JLabel();
private JLabel jLabel6 = new JLabel();
private JLabel jLabel4 = new JLabel();
private JLabel jLabel7 = new JLabel();
private JLabel jLabel8 = new JLabel();
public static void main(String[] args) {
Gui_SetEditor g = new Gui_SetEditor();
g.setVisible(true);
}
public Gui_SetEditor() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
}
private void jbInit() throws Exception {
border1 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder1 = new TitledBorder(border1, "Card Detail");
border2 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titledBorder2 = new TitledBorder(border2, "Set Statistics");
jLabel1.setBounds(new Rectangle(299, 14, 137, 69));
jLabel1.setText("Set Editor");
jLabel1.setFont(new java.awt.Font("Dialog", 0, 26));
this.getContentPane().setLayout(null);
jScrollPane1.setBounds(new Rectangle(13, 112, 181, 271));
jScrollPane2.setBounds(new Rectangle(306, 112, 181, 271));
jPanel1.setBorder(titledBorder1);
jPanel1.setBounds(new Rectangle(609, 28, 228, 291));
jPanel2.setBorder(BorderFactory.createEtchedBorder());
jPanel2.setBounds(new Rectangle(604, 343, 240, 321));
jButton1.setBounds(new Rectangle(197, 161, 105, 32));
jButton1.setText("Add ->");
jButton2.setBounds(new Rectangle(197, 200, 105, 32));
jButton2.setText("Add Note ->");
jButton3.setText("<- Remove");
jButton3.setBounds(new Rectangle(197, 286, 105, 32));
jPanel3.setLayout(flowLayout1);
jPanel3.setBounds(new Rectangle(132, 514, 237, 43));
jButton4.setText("Cancel");
jButton5.setText("Save");
jLabel2.setText("All Available Cards");
jLabel2.setBounds(new Rectangle(51, 81, 133, 24));
jLabel3.setHorizontalAlignment(SwingConstants.CENTER);
jLabel3.setText("Set");
jLabel3.setBounds(new Rectangle(305, 82, 179, 22));
jButton6.setBounds(new Rectangle(495, 119, 53, 54));
jButton6.setToolTipText("Move a card up in the listing");
jButton6.setText("Up");
jButton7.setBounds(new Rectangle(494, 329, 56, 51));
jButton7.setToolTipText("Move a card down in the listing");
jButton7.setText("Down");
jPanel4.setBorder(titledBorder2);
jPanel4.setBounds(new Rectangle(245, 400, 320, 96));
jPanel4.setLayout(null);
jLabel5.setText("White - 10, Green - 10, Black - 10, Red - 10, Blue - 10");
jLabel5.setBounds(new Rectangle(14, 19, 418, 23));
jLabel6.setText("Artifact - 2, Land - 1, Multi-Colored - 0, Total - 100");
jLabel6.setBounds(new Rectangle(14, 45, 418, 23));
jLabel4.setText("Common - 70, Uncommon - 20, Rare - 10");
jLabel4.setBounds(new Rectangle(14, 70, 418, 23));
jLabel7.setText("Elvish Piper - R");
jLabel7.setBounds(new Rectangle(497, 194, 101, 23));
jLabel8.setText("Kodoma\'s Reach - C");
jLabel8.setBounds(new Rectangle(494, 231, 127, 29));
this.getContentPane().add(jLabel1, null);
this.getContentPane().add(jScrollPane2, null);
jScrollPane2.getViewport().add(jList1, null);
this.getContentPane().add(jScrollPane1, null);
jScrollPane1.getViewport().add(jList2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton3, null);
jPanel3.add(jButton5, null);
jPanel3.add(jButton4, null);
this.getContentPane().add(jPanel4, null);
jPanel4.add(jLabel5, null);
jPanel4.add(jLabel6, null);
jPanel4.add(jLabel4, null);
this.getContentPane().add(jPanel3, null);
this.getContentPane().add(jLabel2, null);
this.getContentPane().add(jLabel3, null);
this.getContentPane().add(jButton6, null);
this.getContentPane().add(jButton7, null);
this.getContentPane().add(jPanel1, null);
this.getContentPane().add(jPanel2, null);
this.getContentPane().add(jLabel7, null);
this.getContentPane().add(jLabel8, null);
}
}

59
src/Gui_Welcome.java Normal file
View File

@@ -0,0 +1,59 @@
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class Gui_Welcome extends JFrame {
private static final long serialVersionUID = -7355345901761929563L;
private JLabel jLabel1 = new JLabel();
private JRadioButton jRadioButton1 = new JRadioButton();
private JRadioButton jRadioButton2 = new JRadioButton();
private JButton nextButton = new JButton();
private ButtonGroup buttonGroup1 = new ButtonGroup();
public Gui_Welcome() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
setSize(399, 317);
setVisible(true);
}
private void jbInit() throws Exception {
jLabel1.setFont(new java.awt.Font("Dialog", 0, 26));
jLabel1.setText("Welcome");
jLabel1.setBounds(new Rectangle(119, 8, 210, 69));
this.getContentPane().setLayout(null);
jRadioButton1.setText("Single Game - Play against the Computer");
jRadioButton1.setBounds(new Rectangle(26, 100, 343, 31));
jRadioButton2.setText("Sealed Deck - Create your deck from Booster Packs");
jRadioButton2.setBounds(new Rectangle(26, 154, 329, 28));
nextButton.setBounds(new Rectangle(146, 243, 86, 30));
nextButton.setText("Next ->");
nextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
nextButton_actionPerformed(e);
}
});
this.getContentPane().add(jLabel1, null);
this.getContentPane().add(nextButton, null);
this.getContentPane().add(jRadioButton2, null);
this.getContentPane().add(jRadioButton1, null);
buttonGroup1.add(jRadioButton1);
buttonGroup1.add(jRadioButton2);
}
void nextButton_actionPerformed(ActionEvent e) {
}
}

206
src/Gui_WinLose.java Normal file
View File

@@ -0,0 +1,206 @@
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
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.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class Gui_WinLose extends JFrame {
private static final long serialVersionUID = -5800412940994975483L;
private JLabel titleLabel = new JLabel();
private JButton continueButton = new JButton();
private JButton restartButton = new JButton();
private JButton quitButton = new JButton();
private JLabel statsLabel = new JLabel();
private JPanel jPanel2 = new JPanel();
@SuppressWarnings("unused")
// titledBorder1
private TitledBorder titledBorder1;
@SuppressWarnings("unused")
// border1
private Border border1;
public static void main(String[] args) {
Constant.Runtime.GameType[0] = Constant.GameType.Sealed;
Constant.Runtime.WinLose.addWin();
Constant.Runtime.WinLose.addLose();
//setup limited deck
Deck deck = new Deck(Constant.GameType.Sealed);
CardList pack = new CardList(BoosterPack.getBoosterPack(1).toArray());
for(int i = 0; i < pack.size(); i++)
if((i % 2) == 0) deck.addSideboard(pack.get(i).getName());
else deck.addMain(pack.get(i).getName());
Constant.Runtime.HumanDeck[0] = deck;
//end - setup limited deck
new Gui_WinLose();
}
public Gui_WinLose() {
try {
jbInit();
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
setup();
Dimension screen = this.getToolkit().getScreenSize();
setBounds(screen.width / 3, 100, //position
215, 370); //size
setVisible(true);
}
private void setup() {
WinLose winLose = Constant.Runtime.WinLose;
//3 is the match length, 3 is the number of games
//disable buttons if match is up, or human player won 2 or lost 2 games already
if((winLose.countWinLose() == 3) || (winLose.getWin() == 2) || (winLose.getLose() == 2)) {
// editDeckButton.setEnabled(false);
continueButton.setEnabled(false);
}
//show Wins and Loses
statsLabel.setText("Won: " + winLose.getWin() + ", Lost: " + winLose.getLose());
//show "You Won" or "You Lost"
if(winLose.didWinRecently()) titleLabel.setText("You Won");
else titleLabel.setText("You Lost");
}//setup();
private void jbInit() throws Exception {
titledBorder1 = new TitledBorder("");
border1 = BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140));
titleLabel.setFont(new java.awt.Font("Dialog", 0, 26));
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
titleLabel.setText("You Won");
titleLabel.setBounds(new Rectangle(-4, 0, 198, 60));
this.getContentPane().setLayout(null);
continueButton.setBounds(new Rectangle(22, 21, 123, 30));
continueButton.setText("Continue Match");
continueButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
continueButton_actionPerformed(e);
}
});
restartButton.setBounds(new Rectangle(22, 90, 123, 30));
restartButton.setText("Restart Match");
restartButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
restartButton_actionPerformed(e);
}
});
quitButton.setBounds(new Rectangle(22, 158, 123, 30));
quitButton.setText("Quit Match");
quitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
quitButton_actionPerformed(e);
}
});
statsLabel.setFont(new java.awt.Font("Dialog", 0, 16));
statsLabel.setHorizontalAlignment(SwingConstants.CENTER);
statsLabel.setText("Wins 2, Lost 1");
statsLabel.setBounds(new Rectangle(12, 59, 170, 30));
jPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
jPanel2.setBounds(new Rectangle(20, 104, 166, 217));
jPanel2.setLayout(null);
this.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
this_windowClosing(e);
}
});
this.getContentPane().add(statsLabel, null);
this.getContentPane().add(jPanel2, null);
jPanel2.add(continueButton, null);
jPanel2.add(quitButton, null);
jPanel2.add(restartButton, null);
this.getContentPane().add(titleLabel, null);
}
void editDeckButton_actionPerformed(ActionEvent e) {
Command exit = new Command() {
private static final long serialVersionUID = 4735992294414389187L;
public void execute() {
new Gui_WinLose();
}
};
Gui_DeckEditor editor = new Gui_DeckEditor();
editor.show(exit);
dispose();
}//editDeckButton_actionPerformed()
void continueButton_actionPerformed(ActionEvent e) {
//open up "Game" screen
// AllZone.Computer_Play.reset();//sometimes computer has creature in play in the 2nd game of the match
AllZone.GameAction.newGame(Constant.Runtime.HumanDeck[0], Constant.Runtime.ComputerDeck[0]);
AllZone.Display.setVisible(true);
dispose();
}
void restartButton_actionPerformed(ActionEvent e) {
Constant.Runtime.WinLose.reset();
AllZone.GameAction.newGame(Constant.Runtime.HumanDeck[0], Constant.Runtime.ComputerDeck[0]);
AllZone.Display.setVisible(true);
dispose();
}
void quitButton_actionPerformed(ActionEvent e) {
//are we on a quest?
if(AllZone.QuestData == null) new Gui_NewGame();
else {
WinLose winLose = Constant.Runtime.WinLose;
QuestData quest = AllZone.QuestData;
if(winLose.getWin() == 2) quest.addWin();
else quest.addLost();
if(quest.shouldAddCards(winLose.didWinRecently())) {
quest.addCards();
JOptionPane.showMessageDialog(null, "You have won new cards.");
}
if(quest.shouldAddAdditionalCards(winLose.didWinRecently())) {
quest.addAdditionalCards();
JOptionPane.showMessageDialog(null, "You have won a random rare.");
}
winLose.reset();
QuestData.saveData(quest);
new Gui_Quest();
}//else - on quest
dispose();
//clear Image caches, so the program doesn't get slower and slower
ImageUtil.rotatedCache.clear();
ImageCache.cache.clear();
}
void this_windowClosing(WindowEvent e) {
quitButton_actionPerformed(null);
}
}

93
src/IO.java Normal file
View File

@@ -0,0 +1,93 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class IO {
private final File file;
private Map<String, Serializable> map = new HashMap<String, Serializable>();
public IO(String filename) {
file = new File(filename);
try {
if(!file.exists()) {
file.createNewFile();
writeMap();
}
} catch(Exception ex) {
ErrorViewer.showError(ex, "IO : constructor error, bad filename - %s%n%s", filename, ex.getMessage());
throw new RuntimeException(String.format("IO : constructor error, bad filename - %s%n%s", filename,
ex.getMessage()), ex);
}
}
@SuppressWarnings("unchecked")
// Map has unchecked cast
private void readMap() {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
map = (Map<String, Serializable>) in.readObject();
in.close();
} catch(Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("IO : readMap() error, " + ex.getMessage());
}
}
private void writeMap() {
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(map);
out.flush();
out.close();
} catch(Exception ex) {
ErrorViewer.showError(ex);
throw new RuntimeException("IO : writeMap error, " + ex.getMessage());
}
}
public void writeObject(String key, Serializable ser) {
readMap();
map.put(key, ser);
writeMap();
}
//may return null;
public Object readObject(String key) {
readMap();
return map.get(key);
}
public void deleteObject(String key) {
readMap();
map.remove(key);
writeMap();
}
public ArrayList<String> getKeyList() {
readMap();
ArrayList<String> list = new ArrayList<String>();
Iterator<String> it = map.keySet().iterator();
while(it.hasNext())
list.add(it.next()); // guessing that this is going to be a string.
return list;
}
public String[] getKeyString() {
ArrayList<String> list = getKeyList();
String[] s = new String[list.size()];
list.toArray(s);
return s;
}
}

127
src/ImageCache.java Normal file
View File

@@ -0,0 +1,127 @@
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import javax.imageio.ImageIO;
import forge.error.ErrorViewer;
import forge.properties.ForgeProps;
import forge.properties.NewConstants;
/**
* For storing card images in a cache.
*/
public class ImageCache implements NewConstants {
/**
* Card size.
*/
//protected static Rectangle cardSize = new Rectangle(93, 130);
//protected static Rectangle cardSize = new Rectangle(70, 98);
//public static Rectangle cardSize = new Rectangle(70,98);
public static Rectangle cardSize = new Rectangle(Constant.Runtime.width[0],
Constant.Runtime.height[0]);
/**
* Cache for storing images.
*/
public static HashMap<String, Image> cache = new HashMap<String, Image>();
//protected static HashMap<String, Image> cache = new HashMap<String, Image>();
//~ Image size was not getting updated if the user changed it between games...
public static void dumpCache() {
cardSize = new Rectangle(Constant.Runtime.width[0], Constant.Runtime.height[0]);
cache = new HashMap<String, Image>();
}
//~
/**
* Load image from disk and then put it into the cache. If image has been loaded before then no loading is
* needed.
*
* @param card card to load image for
* @return {@link Image}
*/
final public static Image getImage(Card card) {
/**
* Try to get from cache.
*/
String name = card.getImageName();
if(card.isBasicLand()) {
if(card.getRandomPicture() != 0) name += Integer.toString(card.getRandomPicture());
} else if(card.isFaceDown()) name = "Morph";
if(cache.containsKey(name)) {
return cache.get(name);
}
/**
* Load image.
*/
BufferedImage image = null;
Image resized = null;
File imagePath = getImagePath(card);
if(imagePath == null) {
return null;
}
try {
image = ImageIO.read(imagePath);
resized = image.getScaledInstance(cardSize.width, cardSize.height, java.awt.Image.SCALE_SMOOTH);
} catch(Exception ex) {
ErrorViewer.showError(ex);
}
/**
* Put to cache.
*/
cache.put(name, resized);
return resized;
}
/**
* Get path to image for specific card.
*
* @param c card to get path for
* @return String if image exists, else null
*/
final public static File getImagePath(Card c) {
if(AllZone.NameChanger.shouldChangeCardName()) {
return null;
}
String suffix = ".jpg";
String filename = "";
if(!c.isFaceDown()) {
String basicLandSuffix = "";
if(c.isBasicLand()) {
if(c.getRandomPicture() != 0) basicLandSuffix = Integer.toString(c.getRandomPicture());
}
filename = GuiDisplayUtil.cleanString(c.getImageName()) + basicLandSuffix + suffix;
} else filename = "morph" + suffix;
File file = new File(ForgeProps.getFile(IMAGE_BASE), filename);
/**
* try current directory
*/
if(!file.exists()) {
filename = GuiDisplayUtil.cleanString(c.getName()) + suffix;
file = new File(filename);
}
if(file.exists()) {
return file;
} else {
return null;
}
}
}

31
src/ImageJPanel.java Normal file
View File

@@ -0,0 +1,31 @@
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class ImageJPanel extends JPanel
{
private static final long serialVersionUID = 2908946871498362599L;
private Image aImage = null;
public ImageJPanel(String s)
{
init(s);
}
private void init(String image)
{
ImageIcon imageIcon = new ImageIcon("pics\\" + image);
aImage = imageIcon.getImage();
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(aImage, 0, 0, this);
}
}

98
src/ImageUtil.java Normal file
View File

@@ -0,0 +1,98 @@
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.HashMap;
/**
* Class for working with images.
*
*/
public class ImageUtil
{
public static HashMap<String,BufferedImage> rotatedCache = new HashMap<String,BufferedImage>();
/**
* Rotates image and puts it into cache.
* If image has already been rotated before it is read from cache
*
* @param source image to rotate
* @return
*/
final public static Image getTappedImage(Image original, String name)
{
if (rotatedCache.containsKey(name))
{
return (Image) rotatedCache.get(name);
}
int width = original.getWidth(null);
int height = original.getHeight(null);
if (width == -1 || height == -1)
{
return null;
}
BufferedImage source = new BufferedImage(height, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = source.getGraphics();
g.drawImage(original, 0, 0, null);
g.dispose();
BufferedImage target = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
g = target.getGraphics();
g.drawImage(rotateImage(source), 0, 0, null);
g.dispose();
rotatedCache.put(name, target);
return target;
}
/**
* Rotate image (90 degrees).
*
* @param source image to rotate
* @return rotated image
*/
final protected static BufferedImage rotateImage(BufferedImage source)
{
BufferedImage target = new BufferedImage(source.getHeight(), source.getWidth(), BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
/**
* Rotate 90 degrees around image center
*/
at.rotate(90.0 * Math.PI / 180.0, source.getWidth() / 2.0, source.getHeight() / 2.0);
//Draw from source (rotated) to target
Graphics2D g = (Graphics2D) target.getGraphics();
g.drawImage(source, at, null);
g.dispose();
//Code below is an alternate way to draw using straight Graphics2D - seems to be slower
//Draw from source (rotated) to target
// Graphics2D g = (Graphics2D) target.getGraphics();
// g.rotate(Math.PI / 2.0, source.getWidth() / 2.0, source.getHeight() / 2.0);
// g.drawImage(source, null, 0, 0);
// g.dispose();
return target;
}
}

39
src/Input.java Normal file
View File

@@ -0,0 +1,39 @@
public abstract class Input implements java.io.Serializable
{
private static final long serialVersionUID = -6539552513871194081L;
//showMessage() is always the first method called
public void showMessage() {AllZone.Display.showMessage("Blank Input");}
public void selectCard(Card c, PlayerZone zone) {}
public void selectPlayer(String player) {}
public void selectButtonOK() {}
public void selectButtonCancel() {}
//helper methods, since they are used alot
//to be used by anything in CardFactory like SetTargetInput
//NOT TO BE USED by Input_Main or any of the "regular" Inputs objects that are not set using AllZone.InputControl.setInput(Input)
final public void stop()
{
//clears a "temp" Input like Input_PayManaCost if there is one
AllZone.InputControl.resetInput();
AllZone.InputControl.updateObservers();
if(AllZone.Phase.isNeedToNextPhase()==true){
//for debugging: System.out.println("There better be no nextPhase in the stack.");
AllZone.Phase.setNeedToNextPhase(false);
AllZone.Phase.nextPhase();
}
}
final public void stopPayCost(SpellAbility sa)
{
// AllZone.InputControl.updateObservers();
AllZone.GameAction.playSpellAbility(sa);
}
//exits the "current" Input and sets the next Input
final public void stopSetNext(Input in) {stop(); AllZone.InputControl.setInput(in);}
public String toString() {return "blank";}//returns the Input name like "EmptyStack"
}

247
src/InputControl.java Normal file
View File

@@ -0,0 +1,247 @@
import java.util.*;
@SuppressWarnings("unused") // java.util.*
public class InputControl extends MyObservable implements java.io.Serializable
{
private static final long serialVersionUID = 3955194449319994301L;
private Input input;
static int n = 0;
public void setInput(Input in)
{
input = in;
updateObservers();
}
public void resetInput()
{
input = null;
updateObservers();
}
public Input getInput()
{
final String phase = AllZone.Phase.getPhase();
final String player = AllZone.Phase.getActivePlayer();
//System.out.println(n++ +" " +phase +" " +player);
if(input != null)
return input;
else if(AllZone.Stack.size() > 0)
{
input = new Input_StackNotEmpty();
return input;
}
else if(player.equals(Constant.Player.Human))
{
if(phase.equals(Constant.Phase.Untap))
{
AllZone.Combat.reset();
AllZone.Combat.setAttackingPlayer(Constant.Player.Human);
AllZone.Combat.setDefendingPlayer(Constant.Player.Computer);
AllZone.pwCombat.reset();
AllZone.pwCombat.setAttackingPlayer(Constant.Player.Human);
AllZone.pwCombat.setDefendingPlayer(Constant.Player.Computer);
return new Input_Untap();
}
//else if(phase.equals(Constant.Phase.Upkeep))
//return new Input_Instant(Input_Instant.YES_NEXT_PHASE, "Upkeep Phase: Play Instants and Abilities");
else if(phase.equals(Constant.Phase.Draw))
return new Input_Draw();
else if(phase.equals(Constant.Phase.Main1) || phase.equals(Constant.Phase.Main2))
return new Input_Main();
else if(phase.equals(Constant.Phase.Combat_Before_Declare_Attackers_InstantAbility))
{
if (ComputerUtil.getPossibleAttackers().size() > 0)
return new Input_Before_Attack_Instant();
else
{
AllZone.Phase.setNeedToNextPhase(true);
return null;
}
}
else if(phase.equals(Constant.Phase.Combat_Declare_Attackers))
{
return new Input_Attack();
}
else if (phase.equals(Constant.Phase.Combat_Declare_Attackers_InstantAbility))
{
if (! skipPhase())
return new Input_Attack_Instant();
else
{
AllZone.Phase.setNeedToNextPhase(true);
return null;
}
}
//this is called twice per turn, only when its human's turn
//and then the 2nd time when its the computer's turn
else if(phase.equals(Constant.Phase.Combat_Declare_Blockers_InstantAbility))
{
if(! skipPhase())
return new Input_Block_Instant();
else
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(InputControl,phase.equals(Combat_Declare_Blockers_InstantAbility) = true");
AllZone.Phase.setNeedToNextPhase(true);
//do not return getInput() here. There is now a check for null by this method's caller.
return null;
}
}
else if(phase.equals(Constant.Phase.Combat_FirstStrikeDamage))
{
if(! skipPhase())
return new Input_FirstStrikeDamage();
else
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(InputControl.getInput(),phase.equals(Combat_Damage)) = true");
AllZone.Phase.setNeedToNextPhase(true);
//do not return getInput here. There is now a check for null by this method's caller.
//return getInput();
return null;
}
}
else if(phase.equals(Constant.Phase.Combat_Damage))
{
if(! skipPhase())
return new Input_CombatDamage();
else
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(InputControl.getInput(),phase.equals(Combat_Damage)) = true");
//System.out.println("stack size:" +AllZone.Stack.size());
AllZone.Phase.setNeedToNextPhase(true);
//do not return getInput here. There is now a check for null by this method's caller.
//return getInput();
return null;
}
}
else if(phase.equals(Constant.Phase.At_End_Of_Turn))
{
AllZone.EndOfTurn.executeAt();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(InputControl.getInput(),phase.equals(At_End_Of_Turn)) = true");
AllZone.Phase.setNeedToNextPhase(true);
//do not return getInput() here. There is now a check for null by this method's caller
//return getInput();
return null;
}
else if(phase.equals(Constant.Phase.End_Of_Turn))
{
if(AllZone.Display.stopEOT())
return new Input_EOT();
else
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(InputControl.getInput(),phase.equals(End_Of_Turn)) = true");
AllZone.Phase.setNeedToNextPhase(true);
//do not return getInput() here. There is now a check for null in this method's caller.
//return getInput();
return null;
}
}
else if(phase.equals(Constant.Phase.Until_End_Of_Turn))
{
AllZone.EndOfTurn.executeUntil();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(InputControl.getInput(),phase.equals(Until_End_Of_Turn)) = true");
AllZone.Phase.setNeedToNextPhase(true);
//do not return getInput() here. There is now a check for null by this method's caller.
//return getInput();
return null;
}
else if(phase.equals(Constant.Phase.Cleanup))
return new Input_Cleanup();
//takes place during the computer's turn, like blocking etc...
else if(phase.equals(Constant.Phase.Combat_Declare_Blockers))
{
if(! skipPhase())
return new Input_Block();
else
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(InputControl.getInput(),phase.equals(Combat_Declare_Blockers)) = true");
AllZone.Phase.setNeedToNextPhase(true);
//do not return getInput here. There is now a check for null by this method's caller.
//return getInput();
return null;
}
}
// else if(phase.equals(Constant.Phase.End_Of_Turn))
// return new Input_Instant(Input_Instant.YES_NEXT_PHASE, "End of Computer's Turn: Play Instants and Abilities");
}//Human
else
{ //computer
if(phase.equals(Constant.Phase.Untap))
{
AllZone.Combat.reset();
AllZone.Combat.setAttackingPlayer(Constant.Player.Computer);
AllZone.Combat.setDefendingPlayer(Constant.Player.Human);
AllZone.pwCombat.reset();
AllZone.pwCombat.setAttackingPlayer(Constant.Player.Computer);
AllZone.pwCombat.setDefendingPlayer(Constant.Player.Human);
return new Input_Untap();
}
else if(phase.equals(Constant.Phase.Draw))
return new Computer_Draw();
else if(phase.equals(Constant.Phase.Cleanup))
{
return new Computer_Cleanup();
}
else
return AllZone.Computer;
}//Computer
return new Input()
{
private static final long serialVersionUID = 7378891097354547936L;
public void showMessage()
{
AllZone.Display.showMessage("InputControl : Error nothing found");
throw new RuntimeException("InputControl : getInput() error, should not be here, phase " +phase +", player " +player);
}
};
}//getInput()
private boolean skipPhase()
{
CardList check = new CardList();
check.addAll(AllZone.Combat.getAttackers());
check.addAll(AllZone.pwCombat.getAttackers());
CardList all = new CardList();
all.addAll(AllZone.Computer_Play.getCards());
all.addAll(AllZone.Human_Play.getCards());
all = all.filter(new CardListFilter(){
public boolean addCard(Card c) {
return c.isCreature() && c.getAssignedDamage() > 0;
}
});
return check.size() == 0 && all.size() == 0;
}
}//InputControl

30
src/InputUtil.java Normal file
View File

@@ -0,0 +1,30 @@
//import java.util.*; //unused
public class InputUtil
{
//plays activated abilities and instants
static public void playInstantAbility(Card card, PlayerZone zone)
{
if(zone.is(Constant.Zone.Hand) || zone.is(Constant.Zone.Play, Constant.Player.Human))
AllZone.GameAction.playCard(card);
}
//plays activated abilities and any card including land, sorceries, and instants
static public void playAnyCard(Card card, PlayerZone zone)
{
if(zone.is(Constant.Zone.Hand, Constant.Player.Human) &&
(card.isLand()))
{
AllZone.Human_Hand.remove(card);
AllZone.Human_Play.add(card);
}
else if(zone.is(Constant.Zone.Hand, Constant.Player.Human) &&
card.getManaCost().equals("0"))//for Mox Ruby and the like
{
AllZone.Human_Hand.remove(card);
AllZone.Stack.add(card.getSpellAbility()[0]);
}
else if (zone.is(Constant.Zone.Hand, Constant.Player.Human) || zone.is(Constant.Zone.Play, Constant.Player.Human))
AllZone.GameAction.playCard(card);
}//selectCard()
}

83
src/Input_Attack.java Normal file
View File

@@ -0,0 +1,83 @@
public class Input_Attack extends Input
{
private static final long serialVersionUID = 7849903731842214245L;
public void showMessage()
{
ButtonUtil.enableOnlyOK();
AllZone.Display.showMessage("Declare Attackers: Select creatures that you want to attack with");
PlayerZone play = AllZone.getZone(Constant.Zone.Play, Constant.Player.Human);
CardList creats = new CardList(play.getCards());
creats = creats.getType("Creature");
for (int i = 0;i<creats.size(); i++)
{
Card c = creats.get(i);
if (CombatUtil.canAttack(c) && c.getKeyword().contains("This card attacks each turn if able."))
{
AllZone.Combat.addAttacker(c);
if (!c.getKeyword().contains("Vigilance"))
c.tap();
}
}
}
public void selectButtonOK()
{
Card check = getPlaneswalker();
if(check == null)
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Input_Attack.selectButtonOK,check==null) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
else
{
AllZone.pwCombat.setPlaneswalker(check);
AllZone.InputControl.setInput(new Input_Attack_Planeswalker());
}
}
//return Computer's planeswalker if there is one
//just returns 1, does not return multiple planeswalkers
private Card getPlaneswalker()
{
CardList c = new CardList(AllZone.Computer_Play.getCards());
c = c.getType("Planeswalker");
if(c.isEmpty())
return null;
return c.get(0);
}
public void selectCard(Card card, PlayerZone zone)
{
if(zone.is(Constant.Zone.Play, Constant.Player.Human) &&
card.isCreature() &&
card.isUntapped() &&
CombatUtil.canAttack(card)
)
{
if(! card.getKeyword().contains("Vigilance"))
{
card.tap();
//otherwise cards stay untapped, not sure why this is needed but it works
AllZone.Human_Play.updateObservers();
}
AllZone.Combat.addAttacker(card);
//for Castle Raptors, since it gets a bonus if untapped
for (String effect : AllZone.StateBasedEffects.getStateBasedMap().keySet() ) {
Command com = GameActionUtil.commands.get(effect);
com.execute();
}
GameActionUtil.executeCardStateEffects();
CombatUtil.showCombat();
}
}//selectCard()
}

View File

@@ -0,0 +1,24 @@
public class Input_Attack_Instant extends Input
{
private static final long serialVersionUID = -8244057741266587006L;
public void showMessage()
{
//GameActionUtil.executeExaltedEffects();
AllZone.Combat.verifyCreaturesInPlay();
CombatUtil.showCombat();
ButtonUtil.enableOnlyOK();
AllZone.Display.showMessage("Declare Attackers: Play Instants and Abilities");
}
public void selectButtonOK()
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Input_Block_Instant.selectButtonOK) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void selectCard(Card card, PlayerZone zone)
{
InputUtil.playInstantAbility(card, zone);
}//selectCard()
}

View File

@@ -0,0 +1,46 @@
public class Input_Attack_Planeswalker extends Input
{
private static final long serialVersionUID = 5738375759147611797L;
public void showMessage()
{
ButtonUtil.enableOnlyOK();
AllZone.Display.showMessage("Planeswalker Declare Attackers:\r\nSelect creatures that you want to attack " +AllZone.pwCombat.getPlaneswalker());
}
public void selectButtonOK()
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Input_Attack_Planeswalker.selectButtonOK) = true; Note, this has not been tested, did it work?");
AllZone.Phase.setNeedToNextPhase(true);
this.stop();
}
public void selectCard(Card card, PlayerZone zone)
{
if(zone.is(Constant.Zone.Play, Constant.Player.Human) &&
card.isCreature() &&
card.isUntapped() &&
CombatUtil.canAttack(card)
)
{
if(! card.getKeyword().contains("Vigilance"))
{
card.tap();
//otherwise cards stay untapped, not sure why this is needed but it works
AllZone.Human_Play.updateObservers();
}
AllZone.pwCombat.addAttacker(card);
//for Castle Raptors, since it gets a bonus if untapped
for (String effect : AllZone.StateBasedEffects.getStateBasedMap().keySet() ) {
Command com = GameActionUtil.commands.get(effect);
com.execute();
}
GameActionUtil.executeCardStateEffects();
CombatUtil.showCombat();
}
}//selectCard()
}

View File

@@ -0,0 +1,25 @@
public class Input_Before_Attack_Instant extends Input
{
private static final long serialVersionUID = -6625873677267183150L;
public void showMessage()
{
//GameActionUtil.executeExaltedEffects();
AllZone.Combat.verifyCreaturesInPlay();
CombatUtil.showCombat();
ButtonUtil.enableOnlyOK();
AllZone.Display.showMessage("Before Attack Phase: Play Instants and Abilities");
}
public void selectButtonOK()
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Input_Block_Instant.selectButtonOK) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void selectCard(Card card, PlayerZone zone)
{
InputUtil.playInstantAbility(card, zone);
}//selectCard()
}

65
src/Input_Block.java Normal file
View File

@@ -0,0 +1,65 @@
import java.util.*;
public class Input_Block extends Input
{
private static final long serialVersionUID = 6120743598368928128L;
private Card currentAttacker = null;
private ArrayList<Card> allBlocking = new ArrayList<Card>();
public void showMessage()
{
//for Castle Raptors, since it gets a bonus if untapped
for (String effect : AllZone.StateBasedEffects.getStateBasedMap().keySet() ) {
Command com = GameActionUtil.commands.get(effect);
com.execute();
}
GameActionUtil.executeCardStateEffects();
//could add "Reset Blockers" button
ButtonUtil.enableOnlyOK();
if(currentAttacker == null)
AllZone.Display.showMessage("To Block, click on your Opponents attacker first, then your blocker(s)");
else
AllZone.Display.showMessage("Select a creature to block " +currentAttacker.getName() +" (" +currentAttacker.getUniqueNumber() +") ");
CombatUtil.showCombat();
}
public void selectButtonOK()
{
ButtonUtil.reset();
if(AllZone.pwCombat.getAttackers().length == 0)
{
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Input_Cleanup.showMessage(), n<=7) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
else
{
AllZone.InputControl.setInput(new Input_Block_Planeswalker());
}
}
public void selectCard(Card card, PlayerZone zone)
{
//is attacking?
if(CardUtil.toList(AllZone.Combat.getAttackers()).contains(card))
{
currentAttacker = card;
}
else if(zone.is(Constant.Zone.Play, Constant.Player.Human) &&
card.isCreature() &&
card.isUntapped() &&
CombatUtil.canBlock(currentAttacker, card))
{
if(currentAttacker != null && (! allBlocking.contains(card)))
{
allBlocking.add(card);
AllZone.Combat.addBlocker(currentAttacker, card);
}
}
showMessage();
}//selectCard()
}

View File

@@ -0,0 +1,29 @@
public class Input_Block_Instant extends Input
{
private static final long serialVersionUID = 6024555691502280746L;
public void showMessage()
{
//GameActionUtil.executeExaltedEffects();
AllZone.Combat.verifyCreaturesInPlay();
CombatUtil.showCombat();
ButtonUtil.enableOnlyOK();
AllZone.Display.showMessage("Declare Blockers: Play Instants and Abilities");
}
public void selectButtonOK()
{
AllZone.Combat.setAssignedFirstStrikeDamage();
AllZone.pwCombat.setAssignedFirstStrikeDamage();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Input_Block_Instant.selectButtonOK) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void selectCard(Card card, PlayerZone zone)
{
InputUtil.playInstantAbility(card, zone);
}//selectCard()
}

View File

@@ -0,0 +1,60 @@
import java.util.*;
public class Input_Block_Planeswalker extends Input
{
private static final long serialVersionUID = 8504632360578751473L;
private Card currentAttacker = null;
private ArrayList<Card> allBlocking = new ArrayList<Card>();
public void showMessage()
{
//for Castle Raptors, since it gets a bonus if untapped
for (String effect : AllZone.StateBasedEffects.getStateBasedMap().keySet() ) {
Command com = GameActionUtil.commands.get(effect);
com.execute();
}
GameActionUtil.executeCardStateEffects();
//could add "Reset Blockers" button
ButtonUtil.enableOnlyOK();
if(currentAttacker == null)
AllZone.Display.showMessage("Planeswalker Combat\r\nTo Block, click on your Opponents attacker first , then your blocker(s)");
else
AllZone.Display.showMessage("Select a creature to block " +currentAttacker.getName() +" (" +currentAttacker.getUniqueNumber() +") ");
CombatUtil.showCombat();
}
public void selectButtonOK()
{
ButtonUtil.reset();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Input_Block_Planeswalker.selectButtonOK) = true; Note, this has not been tested, did it work?");
AllZone.Phase.setNeedToNextPhase(true);
this.stop();
}
public void selectCard(Card card, PlayerZone zone)
{
//is attacking?
if(CardUtil.toList(AllZone.pwCombat.getAttackers()).contains(card))
{
currentAttacker = card;
}
else if(zone.is(Constant.Zone.Play, Constant.Player.Human) &&
card.isCreature() &&
card.isUntapped() &&
CombatUtil.canBlock(currentAttacker, card))
{
if(currentAttacker != null && (! allBlocking.contains(card)))
{
allBlocking.add(card);
AllZone.pwCombat.addBlocker(currentAttacker, card);
}
}
showMessage();
}//selectCard()
}

41
src/Input_Cleanup.java Normal file
View File

@@ -0,0 +1,41 @@
public class Input_Cleanup extends Input
{
private static final long serialVersionUID = -4164275418971547948L;
public void showMessage()
{
ButtonUtil.disableAll();
int n = AllZone.Human_Hand.getCards().length;
//MUST showMessage() before stop() or it will overwrite the next Input's message
AllZone.Display.showMessage("Cleanup Phase: You can only have a maximum of 7 cards, you currently have " +n +" cards in your hand - select a card to discard");
//goes to the next phase
if(n <= 7)
{
CombatUtil.removeAllDamage();
//AllZone.Phase.nextPhase();
//for debugging: System.out.println("need to nextPhase(Input_Cleanup.showMessage(), n<=7) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
}
public void selectCard(Card card, PlayerZone zone)
{
if(zone.is(Constant.Zone.Hand, Constant.Player.Human))
{
AllZone.GameAction.discard(card);
showMessage();
//We need a nextPhase here or else it will never get the needToNextPhase from showMessage() (because there isn't a nextPhsae() in the stack).
System.out.println("There better not be a nextPhase() on the stack!");
if(AllZone.Phase != null)
{
if(AllZone.Phase.isNeedToNextPhase())
{
AllZone.Phase.setNeedToNextPhase(false);
AllZone.Phase.nextPhase();
}
}
}
}//selectCard()
}

241
src/Input_CombatDamage.java Normal file
View File

@@ -0,0 +1,241 @@
import java.util.ArrayList;
public class Input_CombatDamage extends Input
{
private static final long serialVersionUID = -8549102582210309044L;
public Input_CombatDamage()
{
AllZone.Combat.verifyCreaturesInPlay();
AllZone.pwCombat.verifyCreaturesInPlay();
CombatUtil.showCombat();
}
public void showMessage()
{
ButtonUtil.enableOnlyOK();
AllZone.Display.showMessage("Combat Damage is on the stack - Play Instants and Abilities");
}
public void selectButtonOK()
{
damageCreatureAndPlayer();
AllZone.GameAction.checkStateEffects();
AllZone.Combat.reset();
AllZone.Display.showCombat("");
//AllZone.Phase.nextPhase();
//for debugging:
System.out.println("need to nextPhase(Input_CombatDamage.selectButtonOK) = true");
AllZone.Phase.setNeedToNextPhase(true);
}
public void selectCard(Card card, PlayerZone zone)
{
InputUtil.playInstantAbility(card, zone);
}//selectCard()
@SuppressWarnings("unused") // playerDamage
private void playerDamage(PlayerLife p)
{
int n = p.getAssignedDamage();
p.setAssignedDamage(0);
p.subtractLife(n);
}
//moves assigned damage to damage for all creatures
//deals damage to player if needed
public void damageCreatureAndPlayer()
{
String player = AllZone.Combat.getDefendingPlayer();
if (player.equals("")) //this is a really bad hack, to allow raging goblin to attack on turn 1
player = Constant.Player.Computer;
PlayerLife life = AllZone.GameAction.getPlayerLife(player);
life.subtractLife(AllZone.Combat.getDefendingDamage());
//why???
/*
life = AllZone.GameAction.getPlayerLife(AllZone.Combat.getAttackingPlayer());
life.subtractLife(AllZone.Combat.getAttackingDamage());
life.subtractLife(AllZone.pwCombat.getAttackingDamage());
*/
CardList unblocked = new CardList(AllZone.Combat.getUnblockedAttackers());
for(int j = 0; j < unblocked.size(); j++)
{
//System.out.println("Unblocked Creature: " +unblocked.get(j).getName());
if (!unblocked.getCard(j).hasFirstStrike() ||
(unblocked.getCard(j).hasFirstStrike() && unblocked.getCard(j).hasDoubleStrike())) {
GameActionUtil.executePlayerCombatDamageEffects(unblocked.get(j));
}
}
//GameActionUtil.executePlayerCombatDmgOptionalEffects(unblocked.toArray());
CardList attackers = new CardList(AllZone.Combat.getAttackers());
CardList blockers = new CardList(AllZone.Combat.getAllBlockers().toArray());
for (int i=0; i < attackers.size(); i++){
//this shouldn't trigger if creature has first strike, only if it also has double strike
if (!attackers.getCard(i).hasFirstStrike() ||
(attackers.getCard(i).hasFirstStrike() && attackers.getCard(i).hasDoubleStrike()))
{
ArrayList<String> list = attackers.getCard(i).getKeyword();
CardList defend = AllZone.Combat.getBlockers(attackers.getCard(i));
//System.out.println("creatures blocking " + attackers.getCard(i).getName() + " : " +defend.size());
/*
//hack, don't get lifelink if a doublestriker kills his blocker with first strike damage
if (!attackers.getCard(i).hasDoubleStrike() || (defend.size()!=0 && attackers.getCard(i).hasDoubleStrike()) )
{
for (int j=0; j < list.size(); j++)
{
if (list.get(j).equals("Lifelink"))
GameActionUtil.executeLifeLinkEffects(attackers.getCard(i));
}
}
*/
if (!attackers.getCard(i).hasDoubleStrike() ||
(attackers.getCard(i).hasDoubleStrike() && !AllZone.Combat.isBlocked(attackers.getCard(i)) ) ||
(attackers.getCard(i).hasDoubleStrike() && AllZone.Combat.isBlocked(attackers.getCard(i)) && defend.size() != 0 ) )
{
/*
//old stuff: lifelink triggers on multiple instances of the lifelink keyword
for (int j=0; j < list.size(); j++)
{
if (list.get(j).equals("Lifelink"))
GameActionUtil.executeLifeLinkEffects(attackers.getCard(i));
}
*/
if (list.contains("Lifelink"))
GameActionUtil.executeLifeLinkEffects(attackers.getCard(i));
for(int j=0; j < CardFactoryUtil.hasNumberEnchantments(attackers.getCard(i), "Guilty Conscience"); j++)
GameActionUtil.executeGuiltyConscienceEffects(attackers.getCard(i));
}
//not sure if this will work correctly with multiple blockers?
int defenderToughness = 0;
for (int k=0; k<defend.size(); k++)
{
defenderToughness += defend.get(k).getNetDefense();
}
if ( (!attackers.getCard(i).hasFirstStrike() || (attackers.getCard(i).hasFirstStrike() && attackers.getCard(i).hasDoubleStrike() )) &&
list.contains("Trample") && defenderToughness < attackers.getCard(i).getNetAttack() && AllZone.Combat.isBlocked(attackers.getCard(i)) )
{
GameActionUtil.executePlayerCombatDamageEffects(attackers.getCard(i));
}
}
}
for (int i=0; i < blockers.size(); i++){
//System.out.println("blocker #" + i + ": " + blockers.getCard(i).getName() +" " + blockers.getCard(i).getAttack());
/*
if (blockers.getCard(i).getKeyword().contains("Lifelink"))
{
GameActionUtil.executeLifeLinkEffects(blockers.getCard(i));
}
*/
//this shouldn't trigger if creature has first strike, only if it also has double strike
if (!blockers.getCard(i).hasFirstStrike() ||
(blockers.getCard(i).hasFirstStrike() && blockers.getCard(i).hasDoubleStrike()))
{
if (blockers.getCard(i).getKeyword().contains("Lifelink"))
{
GameActionUtil.executeLifeLinkEffects(blockers.getCard(i));
}
for(int j=0; j < CardFactoryUtil.hasNumberEnchantments(blockers.getCard(i), "Guilty Conscience"); j++)
GameActionUtil.executeGuiltyConscienceEffects(blockers.getCard(i));
/*
ArrayList<String> list = blockers.getCard(i).getKeyword();
for (int j=0; j < list.size(); j++)
{
if (list.get(j).equals("Lifelink"))
GameActionUtil.executeLifeLinkEffects(blockers.getCard(i));
}
*/
}
}
//get all attackers and blockers
CardList check = new CardList();
check.addAll(AllZone.Human_Play.getCards());
check.addAll(AllZone.Computer_Play.getCards());
CardList all = check.getType("Creature");
if(AllZone.pwCombat.getPlaneswalker() != null)
all.add(AllZone.pwCombat.getPlaneswalker());
CardList pwAttackers = new CardList(AllZone.pwCombat.getAttackers());
CardList pwBlockers = new CardList(AllZone.pwCombat.getAllBlockers().toArray());
for (int i=0; i < pwAttackers.size(); i++){
//System.out.println("attacker #" + i + ": " + attackers.getCard(i).getName() +" " + attackers.getCard(i).getAttack());
if ( (!pwAttackers.getCard(i).hasFirstStrike() || (pwAttackers.getCard(i).hasFirstStrike() && pwAttackers.getCard(i).hasDoubleStrike()) ) )
{
if (pwAttackers.getCard(i).getKeyword().contains("Lifelink"))
GameActionUtil.executeLifeLinkEffects(pwAttackers.getCard(i));
for(int j=0; j < CardFactoryUtil.hasNumberEnchantments(pwAttackers.getCard(i), "Guilty Conscience"); j++)
GameActionUtil.executeGuiltyConscienceEffects(pwAttackers.getCard(i));
}
}
for (int i=0; i < pwBlockers.size(); i++){
//System.out.println("blocker #" + i + ": " + blockers.getCard(i).getName() +" " + blockers.getCard(i).getAttack());
if ( (!pwBlockers.getCard(i).hasFirstStrike() ||
(pwBlockers.getCard(i).hasFirstStrike() && pwBlockers.getCard(i).hasDoubleStrike()) ) )
{
if (pwBlockers.getCard(i).getKeyword().contains("Lifelink"))
GameActionUtil.executeLifeLinkEffects(pwBlockers.getCard(i));
for(int j=0; j < CardFactoryUtil.hasNumberEnchantments(pwBlockers.getCard(i), "Guilty Conscience"); j++)
GameActionUtil.executeGuiltyConscienceEffects(pwBlockers.getCard(i));
}
}
//hacky stuff, hope it won't cause any bugs:
for (int i=0; i < pwAttackers.size(); i++){
AllZone.pwCombat.removeFromCombat(pwAttackers.get(i));
}
for (int i=0; i < pwBlockers.size(); i++){
AllZone.pwCombat.removeFromCombat(pwBlockers.get(i));
}
Card c;
for(int i = 0; i < all.size(); i++)
{
c = all.get(i);
//because this sets off Jackal Pup, and Filthly Cur damage ability
//and the stack says "Jack Pup causes 0 damage to the Computer"
if(c.getAssignedDamage() != 0)
{
//c.addDamage(c.getAssignedDamage());
System.out.println("Calling addDamage for card " + c.getName());
AllZone.GameAction.addDamage(c, c.getAssignedDamage());
c.setAssignedDamage(0);
}
}
}//moveDamage()
}

Some files were not shown because too many files have changed in this diff Show More