diff --git a/Mage.Client/pom.xml b/Mage.Client/pom.xml index 818f319f927..bf98878f842 100644 --- a/Mage.Client/pom.xml +++ b/Mage.Client/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 org.mage diff --git a/Mage.Client/src/main/java/mage/client/MageFrame.java b/Mage.Client/src/main/java/mage/client/MageFrame.java index ae3f7ab1d66..01274af98d1 100644 --- a/Mage.Client/src/main/java/mage/client/MageFrame.java +++ b/Mage.Client/src/main/java/mage/client/MageFrame.java @@ -39,13 +39,9 @@ import java.awt.Image; import java.awt.Rectangle; import java.awt.SplashScreen; import java.awt.Toolkit; -import java.awt.event.AWTEventListener; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; @@ -163,7 +159,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { private static MageFrame instance; - private ConnectDialog connectDialog; + private final ConnectDialog connectDialog; private final ErrorDialog errorDialog; private static CallbackClient callbackClient; private static final Preferences PREFS = Preferences.userNodeForPackage(MageFrame.class); @@ -254,12 +250,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { } }); - Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { - @Override - public void eventDispatched(AWTEvent event) { - handleEvent(event); - } - }, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK); + Toolkit.getDefaultToolkit().addAWTEventListener(event -> handleEvent(event), AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK); TConfig config = TConfig.current(); config.setArchiveDetector(new TArchiveDetector("zip")); @@ -307,12 +298,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { desktopPane.add(errorDialog, JLayeredPane.POPUP_LAYER); UI.addComponent(MageComponents.DESKTOP_PANE, desktopPane); - PING_TASK_EXECUTOR.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - SessionHandler.ping(); - } - }, 60, 60, TimeUnit.SECONDS); + PING_TASK_EXECUTOR.scheduleAtFixedRate(() -> SessionHandler.ping(), 60, 60, TimeUnit.SECONDS); updateMemUsageTask = new UpdateMemUsageTask(jMemUsageLabel); @@ -369,24 +355,21 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { setGUISize(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - disableButtons(); - if (PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_CHECK, "false").equals("true")) { - checkForNewImages(); - } - - updateMemUsageTask.execute(); - LOGGER.info("Client start up time: " + ((System.currentTimeMillis() - startTime) / 1000 + " seconds")); - if (autoConnect()) { - enableButtons(); - } else { - connectDialog.showDialog(); - } - setWindowTitle(); - + SwingUtilities.invokeLater(() -> { + disableButtons(); + if (PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_CHECK, "false").equals("true")) { + checkForNewImages(); } + + updateMemUsageTask.execute(); + LOGGER.info("Client start up time: " + ((System.currentTimeMillis() - startTime) / 1000 + " seconds")); + if (autoConnect()) { + enableButtons(); + } else { + connectDialog.showDialog(); + } + setWindowTitle(); + }); if (SystemUtil.isMacOSX()) { @@ -532,12 +515,9 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { private AbstractButton createSwitchPanelsButton() { final JToggleButton switchPanelsButton = new JToggleButton("Switch panels"); - switchPanelsButton.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - createAndShowSwitchPanelsMenu((JComponent) e.getSource(), switchPanelsButton); - } + switchPanelsButton.addItemListener(e -> { + if (e.getStateChange() == ItemEvent.SELECTED) { + createAndShowSwitchPanelsMenu((JComponent) e.getSource(), switchPanelsButton); } }); switchPanelsButton.setFocusable(false); @@ -557,12 +537,9 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { menuItem = new MagePaneMenuItem(window); menuItem.setFont(GUISizeHelper.menuFont); menuItem.setState(i == 0); - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent ae) { - MagePane frame = ((MagePaneMenuItem) ae.getSource()).getFrame(); - setActive(frame); - } + menuItem.addActionListener(ae -> { + MagePane frame = ((MagePaneMenuItem) ae.getSource()).getFrame(); + setActive(frame); }); menuItem.setIcon(window.getFrameIcon()); menu.add(menuItem); @@ -883,11 +860,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { btnPreferences.setFocusable(false); btnPreferences.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btnPreferences.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnPreferences.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnPreferencesActionPerformed(evt); - } - }); + btnPreferences.addActionListener(evt -> btnPreferencesActionPerformed(evt)); mageToolbar.add(btnPreferences); mageToolbar.add(jSeparator4); @@ -896,11 +869,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { btnConnect.setFocusable(false); btnConnect.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btnConnect.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnConnect.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnConnectActionPerformed(evt); - } - }); + btnConnect.addActionListener(evt -> btnConnectActionPerformed(evt)); mageToolbar.add(btnConnect); lblStatus.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); @@ -916,11 +885,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { btnDeckEditor.setFocusable(false); btnDeckEditor.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btnDeckEditor.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnDeckEditor.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnDeckEditorActionPerformed(evt); - } - }); + btnDeckEditor.addActionListener(evt -> btnDeckEditorActionPerformed(evt)); mageToolbar.add(btnDeckEditor); mageToolbar.add(jSeparator2); @@ -930,11 +895,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { btnCollectionViewer.setFocusable(false); btnCollectionViewer.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btnCollectionViewer.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnCollectionViewer.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCollectionViewerActionPerformed(evt); - } - }); + btnCollectionViewer.addActionListener(evt -> btnCollectionViewerActionPerformed(evt)); mageToolbar.add(btnCollectionViewer); mageToolbar.add(jSeparator5); @@ -944,11 +905,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { btnSendFeedback.setFocusable(false); btnSendFeedback.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btnSendFeedback.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnSendFeedback.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnSendFeedbackActionPerformed(evt); - } - }); + btnSendFeedback.addActionListener(evt -> btnSendFeedbackActionPerformed(evt)); mageToolbar.add(btnSendFeedback); mageToolbar.add(jSeparator6); @@ -958,11 +915,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { btnSymbols.setFocusable(false); btnSymbols.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btnSymbols.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnSymbols.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnSymbolsActionPerformed(evt); - } - }); + btnSymbols.addActionListener(evt -> btnSymbolsActionPerformed(evt)); mageToolbar.add(btnSymbols); mageToolbar.add(jSeparatorSymbols); @@ -972,11 +925,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { btnImages.setFocusable(false); btnImages.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btnImages.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnImages.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnImagesActionPerformed(evt); - } - }); + btnImages.addActionListener(evt -> btnImagesActionPerformed(evt)); mageToolbar.add(btnImages); mageToolbar.add(jSeparatorImages); @@ -986,11 +935,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { btnAbout.setFocusable(false); btnAbout.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btnAbout.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnAbout.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnAboutActionPerformed(evt); - } - }); + btnAbout.addActionListener(evt -> btnAboutActionPerformed(evt)); mageToolbar.add(btnAbout); mageToolbar.add(jSeparator7); @@ -1192,12 +1137,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { if (SwingUtilities.isEventDispatchThread()) { userRequestDialog.showDialog(userRequestMessage); } else { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - userRequestDialog.showDialog(userRequestMessage); - } - }); + SwingUtilities.invokeLater(() -> userRequestDialog.showDialog(userRequestMessage)); } } @@ -1206,12 +1146,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { if (SwingUtilities.isEventDispatchThread()) { errorDialog.showDialog(title, message); } else { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - errorDialog.showDialog(title, message); - } - }); + SwingUtilities.invokeLater(() -> errorDialog.showDialog(title, message)); } } @@ -1253,40 +1188,32 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { LOGGER.info("Logging level: " + LOGGER.getEffectiveLevel()); startTime = System.currentTimeMillis(); - Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - LOGGER.fatal(null, e); + Thread.setDefaultUncaughtExceptionHandler((t, e) -> LOGGER.fatal(null, e)); + SwingUtilities.invokeLater(() -> { + for (String arg : args) { + if (arg.startsWith(LITE_MODE_ARG)) { + liteMode = true; + } + if (arg.startsWith(GRAY_MODE_ARG)) { + grayMode = true; + } + if (arg.startsWith(FILL_SCREEN_ARG)) { + fullscreenMode = true; + } } - }); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - for (String arg : args) { - if (arg.startsWith(LITE_MODE_ARG)) { - liteMode = true; - } - if (arg.startsWith(GRAY_MODE_ARG)) { - grayMode = true; - } - if (arg.startsWith(FILL_SCREEN_ARG)) { - fullscreenMode = true; + if (!liteMode) { + final SplashScreen splash = SplashScreen.getSplashScreen(); + if (splash != null) { + Graphics2D g = splash.createGraphics(); + if (g != null) { + renderSplashFrame(g); } + splash.update(); } - if (!liteMode) { - final SplashScreen splash = SplashScreen.getSplashScreen(); - if (splash != null) { - Graphics2D g = splash.createGraphics(); - if (g != null) { - renderSplashFrame(g); - } - splash.update(); - } - } - instance = new MageFrame(); - instance.setVisible(true); + } + instance = new MageFrame(); + instance.setVisible(true); - } }); } @@ -1383,12 +1310,9 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { setStatusText(message); enableButtons(); } else { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setStatusText(message); - enableButtons(); - } + SwingUtilities.invokeLater(() -> { + setStatusText(message); + enableButtons(); }); } } @@ -1403,20 +1327,17 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { hideTables(); } else { LOGGER.info("DISCONNECTED (NO Event Dispatch Thread)"); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setStatusText("Not connected"); - disableButtons(); - hideGames(); - hideTables(); - SessionHandler.disconnect(false); - if (errorCall) { - UserRequestMessage message = new UserRequestMessage("Connection lost", "The connection to server was lost. Reconnect to " + currentConnection.getHost() + "?"); - message.setButton1("No", null); - message.setButton2("Yes", PlayerAction.CLIENT_RECONNECT); - showUserRequestDialog(message); - } + SwingUtilities.invokeLater(() -> { + setStatusText("Not connected"); + disableButtons(); + hideGames(); + hideTables(); + SessionHandler.disconnect(false); + if (errorCall) { + UserRequestMessage message = new UserRequestMessage("Connection lost", "The connection to server was lost. Reconnect to " + currentConnection.getHost() + "?"); + message.setButton1("No", null); + message.setButton2("Yes", PlayerAction.CLIENT_RECONNECT); + showUserRequestDialog(message); } } ); diff --git a/Mage.Client/src/main/java/mage/client/cards/Card.java b/Mage.Client/src/main/java/mage/client/cards/Card.java index f87c03bbebf..f8d974caf69 100644 --- a/Mage.Client/src/main/java/mage/client/cards/Card.java +++ b/Mage.Client/src/main/java/mage/client/cards/Card.java @@ -86,7 +86,6 @@ import mage.client.util.ImageHelper; import mage.client.util.gui.ArrowBuilder; import mage.constants.CardType; import mage.constants.EnlargeMode; -import mage.remote.Session; import mage.view.AbilityView; import mage.view.CardView; import mage.view.CounterView; @@ -101,10 +100,10 @@ import org.apache.log4j.Logger; @SuppressWarnings("serial") public class Card extends MagePermanent implements MouseMotionListener, MouseListener, FocusListener, ComponentListener { - protected static DefaultActionCallback callback = DefaultActionCallback.getInstance(); + protected static final DefaultActionCallback callback = DefaultActionCallback.getInstance(); protected Point p; - protected CardDimensions dimension; + protected final CardDimensions dimension; protected final UUID gameId; protected final BigCard bigCard; @@ -112,10 +111,10 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis protected Popup tooltipPopup; protected boolean tooltipShowing; - protected TextPopup tooltipText = new TextPopup(); + protected final TextPopup tooltipText = new TextPopup(); protected BufferedImage background; - protected BufferedImage image = new BufferedImage(FRAME_MAX_WIDTH, FRAME_MAX_HEIGHT, BufferedImage.TYPE_INT_RGB); - protected BufferedImage small; + protected final BufferedImage image = new BufferedImage(FRAME_MAX_WIDTH, FRAME_MAX_HEIGHT, BufferedImage.TYPE_INT_RGB); + protected final BufferedImage small; protected String backgroundName; // if this is set, it's opened if the user right clicks on the card panel diff --git a/Mage.Client/src/main/java/mage/client/cards/CardArea.java b/Mage.Client/src/main/java/mage/client/cards/CardArea.java index 8ebd826c3e8..531cf10eb2c 100644 --- a/Mage.Client/src/main/java/mage/client/cards/CardArea.java +++ b/Mage.Client/src/main/java/mage/client/cards/CardArea.java @@ -52,7 +52,7 @@ import org.mage.card.arcane.CardPanel; public class CardArea extends JPanel implements MouseListener { - protected CardEventSource cardEventSource = new CardEventSource(); + protected final CardEventSource cardEventSource = new CardEventSource(); private boolean reloaded = false; private final javax.swing.JLayeredPane cardArea; @@ -89,7 +89,7 @@ public class CardArea extends JPanel implements MouseListener { setGUISize(); for (Component component : cardArea.getComponents()) { if (component instanceof CardPanel) { - ((CardPanel) component).setBounds(0, 0, cardDimension.width, cardDimension.height); + component.setBounds(0, 0, cardDimension.width, cardDimension.height); } } } diff --git a/Mage.Client/src/main/java/mage/client/cards/CardDraggerGlassPane.java b/Mage.Client/src/main/java/mage/client/cards/CardDraggerGlassPane.java index 2ca05863488..b813b53bfef 100644 --- a/Mage.Client/src/main/java/mage/client/cards/CardDraggerGlassPane.java +++ b/Mage.Client/src/main/java/mage/client/cards/CardDraggerGlassPane.java @@ -3,7 +3,6 @@ package mage.client.cards; import mage.cards.MageCard; import mage.client.plugins.impl.Plugins; import mage.view.CardView; -import org.apache.log4j.Logger; import javax.swing.*; import java.awt.*; @@ -11,13 +10,12 @@ import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.ArrayList; -import java.util.Collection; /** * Created by StravantUser on 2016-09-22. */ public class CardDraggerGlassPane implements MouseListener, MouseMotionListener { - private DragCardSource source; + private final DragCardSource source; private Component dragComponent; private JRootPane currentRoot; private JComponent glassPane; diff --git a/Mage.Client/src/main/java/mage/client/cards/CardEventSource.java b/Mage.Client/src/main/java/mage/client/cards/CardEventSource.java index 0327dc887d9..81e29d83dba 100644 --- a/Mage.Client/src/main/java/mage/client/cards/CardEventSource.java +++ b/Mage.Client/src/main/java/mage/client/cards/CardEventSource.java @@ -33,7 +33,6 @@ import mage.client.util.Event; import mage.client.util.EventDispatcher; import mage.client.util.EventSource; import mage.client.util.Listener; -import mage.view.CardView; import mage.view.SimpleCardView; /** diff --git a/Mage.Client/src/main/java/mage/client/cards/CardGrid.java b/Mage.Client/src/main/java/mage/client/cards/CardGrid.java index 618f604a45e..1180ccab472 100644 --- a/Mage.Client/src/main/java/mage/client/cards/CardGrid.java +++ b/Mage.Client/src/main/java/mage/client/cards/CardGrid.java @@ -39,7 +39,6 @@ import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; @@ -64,7 +63,7 @@ import org.mage.card.arcane.CardPanel; */ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener, ICardGrid { - protected CardEventSource cardEventSource = new CardEventSource(); + protected final CardEventSource cardEventSource = new CardEventSource(); protected BigCard bigCard; protected UUID gameId; private final Map cards = new HashMap<>(); @@ -154,22 +153,22 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener, List sortedCards = new ArrayList<>(cards.values()); switch (sortSetting.getSortBy()) { case NAME: - Collections.sort(sortedCards, new CardNameComparator()); + sortedCards.sort(new CardNameComparator()); break; case CARD_TYPE: - Collections.sort(sortedCards, new CardTypeComparator()); + sortedCards.sort(new CardTypeComparator()); break; case RARITY: - Collections.sort(sortedCards, new CardRarityComparator()); + sortedCards.sort(new CardRarityComparator()); break; case COLOR: - Collections.sort(sortedCards, new CardColorComparator()); + sortedCards.sort(new CardColorComparator()); break; case COLOR_IDENTITY: - Collections.sort(sortedCards, new CardColorDetailedIdentity()); + sortedCards.sort(new CardColorDetailedIdentity()); break; case CASTING_COST: - Collections.sort(sortedCards, new CardCostComparator()); + sortedCards.sort(new CardCostComparator()); break; } @@ -409,7 +408,7 @@ class CardCostComparator implements Comparator { @Override public int compare(MageCard o1, MageCard o2) { - int val = Integer.valueOf(o1.getOriginal().getConvertedManaCost()).compareTo(Integer.valueOf(o2.getOriginal().getConvertedManaCost())); + int val = Integer.valueOf(o1.getOriginal().getConvertedManaCost()).compareTo(o2.getOriginal().getConvertedManaCost()); if (val == 0) { return o1.getOriginal().getName().compareTo(o2.getOriginal().getName()); } else { diff --git a/Mage.Client/src/main/java/mage/client/cards/Cards.java b/Mage.Client/src/main/java/mage/client/cards/Cards.java index 8cd01f78ac7..d6a3363db77 100644 --- a/Mage.Client/src/main/java/mage/client/cards/Cards.java +++ b/Mage.Client/src/main/java/mage/client/cards/Cards.java @@ -37,8 +37,6 @@ import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; @@ -210,7 +208,7 @@ public class Cards extends javax.swing.JPanel { tmp.setIsAbility(true); tmp.overrideTargets(card.getTargets()); tmp.overrideId(card.getId()); - tmp.setAbilityType(((StackAbilityView) card).getAbilityType()); + tmp.setAbilityType(card.getAbilityType()); card = tmp; } else { card.setAbilityType(null); @@ -258,7 +256,7 @@ public class Cards extends javax.swing.JPanel { this.cardDimension = dimension; for (Component component : cardArea.getComponents()) { if (component instanceof CardPanel) { - ((CardPanel) component).setBounds(0, 0, dimension.width, dimension.height); + component.setBounds(0, 0, dimension.width, dimension.height); } } layoutCards(); @@ -358,12 +356,7 @@ public class Cards extends javax.swing.JPanel { } } // sort the cards - Collections.sort(cardsToLayout, new Comparator() { - @Override - public int compare(CardPanel cp1, CardPanel cp2) { - return Integer.valueOf(cp1.getLocation().x).compareTo(cp2.getLocation().x); - } - }); + cardsToLayout.sort((cp1, cp2) -> Integer.valueOf(cp1.getLocation().x).compareTo(cp2.getLocation().x)); // relocate the cards int dx = 0; for (Component component : cardsToLayout) { diff --git a/Mage.Client/src/main/java/mage/client/cards/CardsList.java b/Mage.Client/src/main/java/mage/client/cards/CardsList.java index bfc3658f308..bec809a416c 100644 --- a/Mage.Client/src/main/java/mage/client/cards/CardsList.java +++ b/Mage.Client/src/main/java/mage/client/cards/CardsList.java @@ -83,7 +83,7 @@ import org.mage.card.arcane.CardPanel; */ public class CardsList extends javax.swing.JPanel implements MouseListener, ICardGrid { - protected CardEventSource cardEventSource = new CardEventSource(); + protected final CardEventSource cardEventSource = new CardEventSource(); private Dimension cardDimension; private int rowHeight; private CardsView cards; @@ -346,8 +346,8 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar break; } if (comparator != null) { - Collections.sort(sortedCards, new CardViewNameComparator()); - Collections.sort(sortedCards, comparator); + sortedCards.sort(new CardViewNameComparator()); + sortedCards.sort(comparator); } CardView lastCard = null; for (CardView card : sortedCards) { @@ -536,11 +536,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar chkPiles.setText("Piles"); chkPiles.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); chkPiles.setMargin(new java.awt.Insets(3, 2, 2, 2)); - chkPiles.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - chkPilesActionPerformed(evt); - } - }); + chkPiles.addActionListener(evt -> chkPilesActionPerformed(evt)); cbSortBy.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SortBy" })); cbSortBy.setToolTipText("Sort the cards if card view is active."); @@ -549,11 +545,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar cbSortBy.setName("SortBy"); // NOI18N cbSortBy.setOpaque(false); cbSortBy.setPreferredSize(new java.awt.Dimension(120, 20)); - cbSortBy.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbSortByActionPerformed(evt); - } - }); + cbSortBy.addActionListener(evt -> cbSortByActionPerformed(evt)); bgView.add(jToggleListView); jToggleListView.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/list_panel.png"))); // NOI18N @@ -564,11 +556,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar jToggleListView.setMaximumSize(new java.awt.Dimension(37, 25)); jToggleListView.setMinimumSize(new java.awt.Dimension(37, 25)); jToggleListView.setPreferredSize(new java.awt.Dimension(44, 22)); - jToggleListView.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jToggleListViewActionPerformed(evt); - } - }); + jToggleListView.addActionListener(evt -> jToggleListViewActionPerformed(evt)); bgView.add(jToggleCardView); jToggleCardView.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/card_panel.png"))); // NOI18N @@ -576,11 +564,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar jToggleCardView.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); jToggleCardView.setMargin(new java.awt.Insets(2, 6, 2, 6)); jToggleCardView.setPreferredSize(new java.awt.Dimension(40, 22)); - jToggleCardView.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jToggleCardViewActionPerformed(evt); - } - }); + jToggleCardView.addActionListener(evt -> jToggleCardViewActionPerformed(evt)); javax.swing.GroupLayout panelControlLayout = new javax.swing.GroupLayout(panelControl); panelControl.setLayout(panelControlLayout); diff --git a/Mage.Client/src/main/java/mage/client/cards/DraftGrid.java b/Mage.Client/src/main/java/mage/client/cards/DraftGrid.java index 4dc525154a7..89c8149d095 100644 --- a/Mage.Client/src/main/java/mage/client/cards/DraftGrid.java +++ b/Mage.Client/src/main/java/mage/client/cards/DraftGrid.java @@ -40,7 +40,6 @@ import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import mage.cards.CardDimensions; import mage.cards.MageCard; @@ -62,7 +61,7 @@ public class DraftGrid extends javax.swing.JPanel implements MouseListener { private static final Logger logger = Logger.getLogger(DraftGrid.class); - protected CardEventSource cardEventSource = new CardEventSource(); + protected final CardEventSource cardEventSource = new CardEventSource(); protected BigCard bigCard; protected MageCard markedCard; protected boolean emptyGrid; @@ -126,7 +125,7 @@ public class DraftGrid extends javax.swing.JPanel implements MouseListener { Dimension dimension = new Dimension(cardDimension.frameWidth, cardDimension.frameHeight); List sortedCards = new ArrayList<>(booster.values()); - Collections.sort(sortedCards, new CardViewRarityComparator()); + sortedCards.sort(new CardViewRarityComparator()); for (CardView card: sortedCards) { MageCard cardImg = Plugins.getInstance().getMageCard(card, bigCard, dimension, null, true, true); cardImg.addMouseListener(this); diff --git a/Mage.Client/src/main/java/mage/client/cards/DragCardGrid.java b/Mage.Client/src/main/java/mage/client/cards/DragCardGrid.java index a362c619bb8..e352c154e6e 100644 --- a/Mage.Client/src/main/java/mage/client/cards/DragCardGrid.java +++ b/Mage.Client/src/main/java/mage/client/cards/DragCardGrid.java @@ -7,15 +7,12 @@ import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; @@ -40,9 +37,11 @@ import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JMenu; import javax.swing.JMenuItem; +import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; +import mage.cards.Card; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.JToggleButton; @@ -52,6 +51,9 @@ import javax.swing.SwingUtilities; import mage.cards.MageCard; import mage.cards.decks.DeckCardInfo; import mage.cards.decks.DeckCardLayout; +import mage.cards.repository.CardCriteria; +import mage.cards.repository.CardInfo; +import mage.cards.repository.CardRepository; import mage.client.MageFrame; import mage.client.constants.Constants; import mage.client.dialog.PreferencesDialog; @@ -66,6 +68,7 @@ import mage.client.util.Event; import mage.client.util.GUISizeHelper; import mage.client.util.Listener; import mage.constants.CardType; +import mage.util.RandomUtil; import mage.view.CardView; import mage.view.CardsView; import org.apache.log4j.Logger; @@ -455,12 +458,9 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg } public enum Sort { - NONE("No Sort", new Comparator() { - @Override - public int compare(CardView o1, CardView o2) { - // Always equal, sort into the first row - return 0; - } + NONE("No Sort", (o1, o2) -> { + // Always equal, sort into the first row + return 0; }), CARD_TYPE("Card Type", new CardViewCardTypeComparator()), CMC("Converted Mana Cost", new CardViewCostComparator()), @@ -508,44 +508,44 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg } // Counters we use - private CardTypeCounter creatureCounter = new CardTypeCounter() { + private final CardTypeCounter creatureCounter = new CardTypeCounter() { @Override protected boolean is(CardView card) { return card.getCardTypes().contains(CardType.CREATURE); } }; - private CardTypeCounter landCounter = new CardTypeCounter() { + private final CardTypeCounter landCounter = new CardTypeCounter() { @Override protected boolean is(CardView card) { return card.getCardTypes().contains(CardType.LAND); } }; - private CardTypeCounter artifactCounter = new CardTypeCounter() { + private final CardTypeCounter artifactCounter = new CardTypeCounter() { @Override protected boolean is(CardView card) { return card.getCardTypes().contains(CardType.ARTIFACT); } }; - private CardTypeCounter enchantmentCounter = new CardTypeCounter() { + private final CardTypeCounter enchantmentCounter = new CardTypeCounter() { @Override protected boolean is(CardView card) { return card.getCardTypes().contains(CardType.ENCHANTMENT); } }; - private CardTypeCounter instantCounter = new CardTypeCounter() { + private final CardTypeCounter instantCounter = new CardTypeCounter() { @Override protected boolean is(CardView card) { return card.getCardTypes().contains(CardType.INSTANT); } }; - private CardTypeCounter sorceryCounter = new CardTypeCounter() { + private final CardTypeCounter sorceryCounter = new CardTypeCounter() { @Override protected boolean is(CardView card) { return card.getCardTypes().contains(CardType.SORCERY); } }; - private CardTypeCounter planeswalkerCounter = new CardTypeCounter() { + private final CardTypeCounter planeswalkerCounter = new CardTypeCounter() { @Override protected boolean is(CardView card) { return card.getCardTypes().contains(CardType.PLANESWALKER); @@ -577,15 +577,15 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg void hideCards(Collection card); void duplicateCards(Collection cards); - + void invertCardSelection(Collection cards); void showAll(); - }; + } // Constants - public static int COUNT_LABEL_HEIGHT = 20; - public static int GRID_PADDING = 10; + public static final int COUNT_LABEL_HEIGHT = 20; + public static final int GRID_PADDING = 10; private final static ImageIcon INSERT_ROW_ICON = new ImageIcon(DragCardGrid.class.getClassLoader().getResource("editor_insert_row.png")); private final static ImageIcon INSERT_COL_ICON = new ImageIcon(DragCardGrid.class.getClassLoader().getResource("editor_insert_col.png")); @@ -606,36 +606,38 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg JButton visibilityButton; JButton selectByButton; JButton analyseButton; + JButton blingButton; + // Popup for toolbar - JPopupMenu filterPopup; + final JPopupMenu filterPopup; JPopupMenu selectByTypePopup; - JPopupMenu sortPopup; - JPopupMenu selectByPopup; - JCheckBox separateCreaturesCb; - JTextField searchByTextField; + final JPopupMenu sortPopup; + final JPopupMenu selectByPopup; + final JCheckBox separateCreaturesCb; + final JTextField searchByTextField; JToggleButton multiplesButton; - JSlider cardSizeSlider; - JLabel cardSizeSliderLabel; + final JSlider cardSizeSlider; + final JLabel cardSizeSliderLabel; - Map sortButtons = new HashMap<>(); - HashMap selectByTypeButtons = new HashMap<>(); + final Map sortButtons = new HashMap<>(); + final HashMap selectByTypeButtons = new HashMap<>(); - JLabel deckNameAndCountLabel; - JLabel landCountLabel; - JLabel creatureCountLabel; + final JLabel deckNameAndCountLabel; + final JLabel landCountLabel; + final JLabel creatureCountLabel; // Main two controls holding the scrollable card grid - JScrollPane cardScroll; + final JScrollPane cardScroll; JLayeredPane cardContent; // Drag onto insert arrow - JLabel insertArrow; + final JLabel insertArrow; // Card area selection panel - SelectionBox selectionPanel; + final SelectionBox selectionPanel; Set selectionDragStartCards; int selectionDragStartX; int selectionDragStartY; @@ -672,7 +674,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg return name; } - private String name; + private final String name; } public static class Settings { @@ -756,9 +758,10 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg // Toolbar sortButton = new JButton("Sort"); filterButton = new JButton("Filter"); - visibilityButton = new JButton("Visibility"); + visibilityButton = new JButton("V"); // "Visibility" button selectByButton = new JButton("Select By"); - analyseButton = new JButton("Mana"); + analyseButton = new JButton("M"); // "Mana" button + blingButton = new JButton("B"); // "Bling" button // Name and count label deckNameAndCountLabel = new JLabel(); @@ -779,9 +782,10 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg toolbarInner.add(creatureCountLabel); toolbarInner.add(sortButton); toolbarInner.add(filterButton); - toolbarInner.add(visibilityButton); toolbarInner.add(selectByButton); + toolbarInner.add(visibilityButton); toolbarInner.add(analyseButton); + toolbarInner.add(blingButton); toolbar.add(toolbarInner, BorderLayout.WEST); JPanel sliderPanel = new JPanel(new GridBagLayout()); sliderPanel.setOpaque(false); @@ -929,6 +933,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg JMenuItem showAll = new JMenuItem("Show all"); showAll.addActionListener(e -> showAll()); visPopup.add(showAll); + visibilityButton.setToolTipText("Visibility of cards. Right click to get the same options this provides"); visibilityButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { @@ -956,15 +961,15 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg ButtonGroup selectByTypeModeGroup = new ButtonGroup(); for (final CardType cardType : CardType.values()) { - if (cardType == cardType.CONSPIRACY) { + if (cardType == cardType.CONSPIRACY) { multiplesButton = new JToggleButton("Multiples"); selectByTypeButtons.put(cardType, multiplesButton); selectByTypeMode.add(multiplesButton); selectByTypeModeGroup.add(multiplesButton); multiplesButton.addActionListener(e -> { - multiplesButton.setSelected(!multiplesButton.isSelected()); - reselectBy(); - }); + multiplesButton.setSelected(!multiplesButton.isSelected()); + reselectBy(); + }); continue; } @@ -1011,13 +1016,14 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg } // Analyse Mana (aka #blue pips, #islands, #white pips, #plains etc.) - analyseButton.setToolTipText("Counts coloured/colourless mana costs. Counts land types."); + analyseButton.setToolTipText("Mana Analyser! Counts coloured/colourless mana costs. Counts land types."); - analyseButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent evt) { - analyseDeck(); - } - }); + analyseButton.addActionListener(evt -> analyseDeck()); + + // Bling button - aka Add in a premium 'JR', 'MBP', 'CS' etc card + blingButton.setToolTipText("Bling your deck! Select the original and added cards by selecting 'Multiples' in the selection options"); + + blingButton.addActionListener(evt -> blingDeck()); // Filter popup filterPopup = new JPopupMenu(); @@ -1108,7 +1114,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg l.duplicateCards(toDuplicate); } } - + private void invertSelection() { Collection toInvert = allCards; for (DragCardGridListener l : listeners) { @@ -1229,7 +1235,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg trimGrid(); // First sort all cards by name - Collections.sort(allCards, new CardViewNameComparator()); + allCards.sort(new CardViewNameComparator()); // Now re-insert all of the cards using the current sort for (CardView card : allCards) { @@ -1478,6 +1484,84 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg MageFrame.getInstance().showMessage(finalInfo); } + public void blingDeck() { + if (!(this.mode == Constants.DeckEditorMode.FREE_BUILDING)) { + return; + } + + if (JOptionPane.showConfirmDialog(null, "Are you sure you want to bling your deck? This process will add cards!", "WARNING", + JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) { + return; + } + + HashMap pimpedSets = new HashMap<>(); + HashMap pimpedCards = new HashMap<>(); + pimpedSets.put("CP", 1); + pimpedSets.put("JR", 1); + pimpedSets.put("MPS", 1); + pimpedSets.put("CLASH", 1); + pimpedSets.put("ARENA", 1); + pimpedSets.put("UGIN", 1); + pimpedSets.put("WMCQ", 1); + pimpedSets.put("APAC", 1); + pimpedSets.put("EURO", 1); + pimpedSets.put("FNMP", 1); + pimpedSets.put("MGDC", 1); + pimpedSets.put("MPRP", 1); + pimpedSets.put("EXP", 1); + pimpedSets.put("GPX", 1); + pimpedSets.put("GRC", 1); + pimpedSets.put("MBP", 1); + pimpedSets.put("MLP", 1); + pimpedSets.put("PLS", 1); + pimpedSets.put("PTC", 1); + pimpedSets.put("SUS", 1); + + String[] sets = pimpedSets.keySet().toArray(new String[pimpedSets.keySet().size()]); + Boolean didModify = false; + + for (ArrayList> gridRow : cardGrid) { + for (ArrayList stack : gridRow) { + for (CardView card : stack) { + if (card.getSuperTypes().contains("Basic")) { + continue; + } + + if (!pimpedSets.containsKey(card.getExpansionSetCode())) { + final CardCriteria cardCriteria = new CardCriteria(); + cardCriteria.setCodes(sets); + cardCriteria.name(card.getName()); + + List cardPool = CardRepository.instance.findCards(cardCriteria); + + if (cardPool.size() > 0) { + Card acard = cardPool.get(RandomUtil.nextInt(cardPool.size())).getMockCard(); + + if (acard.getName().equals(card.getName())) { + CardView pimpedCard = new CardView(acard); + addCardView(pimpedCard, false); + eventSource.addSpecificCard(pimpedCard, "add-specific-card"); + pimpedCards.put(pimpedCard, 1); + didModify = true; + } + } + } + } + } + + if (didModify) { + for (CardView c : pimpedCards.keySet()) { + sortIntoGrid(c); + } + + layoutGrid(); + cardScroll.revalidate(); + repaint(); + JOptionPane.showMessageDialog(null, "Added " + pimpedCards.size() + " cards. You can select them and the originals by choosing 'Multiples'"); + } + } + } + // Update the contents of the card grid public void setCards(CardsView cardsView, DeckCardLayout layout, BigCard bigCard) { if (bigCard != null) { @@ -1640,10 +1724,10 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg AbstractButton button = selectByTypeButtons.get(cardType); String text = cardType.toString(); int numCards = getCount(cardType); - if (cardType == cardType.CONSPIRACY) { + if (cardType == cardType.CONSPIRACY) { continue; } - + if (numCards > 0) { button.setForeground(Color.BLACK); text = text + " - " + numCards; @@ -1659,7 +1743,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg JMenuItem hide = new JMenuItem("Hide"); hide.addActionListener(e2 -> hideSelection()); menu.add(hide); - + JMenuItem invertSelection = new JMenuItem("Invert Selection"); invertSelection.addActionListener(e2 -> invertSelection()); menu.add(invertSelection); diff --git a/Mage.Client/src/main/java/mage/client/cards/DragCardTarget.java b/Mage.Client/src/main/java/mage/client/cards/DragCardTarget.java index 70138889c4c..a656a4bc937 100644 --- a/Mage.Client/src/main/java/mage/client/cards/DragCardTarget.java +++ b/Mage.Client/src/main/java/mage/client/cards/DragCardTarget.java @@ -2,7 +2,6 @@ package mage.client.cards; import mage.view.CardView; -import java.awt.*; import java.awt.event.MouseEvent; import java.util.Collection; diff --git a/Mage.Client/src/main/java/mage/client/cards/Permanent.java b/Mage.Client/src/main/java/mage/client/cards/Permanent.java index 0db10e58871..f5b3dd2494f 100644 --- a/Mage.Client/src/main/java/mage/client/cards/Permanent.java +++ b/Mage.Client/src/main/java/mage/client/cards/Permanent.java @@ -52,11 +52,9 @@ import mage.cards.Sets; import static mage.client.constants.Constants.DAMAGE_MAX_LEFT; import static mage.client.constants.Constants.POWBOX_TEXT_MAX_TOP; import mage.client.util.Config; -import mage.client.util.ImageHelper; import mage.constants.CardType; import mage.view.CounterView; import mage.view.PermanentView; -import org.mage.plugins.card.images.ImageCache; import mage.client.util.TransformedImageCache; /** @@ -67,9 +65,9 @@ public class Permanent extends Card { protected PermanentView permanent; - protected List links = new ArrayList<>(); + protected final List links = new ArrayList<>(); protected boolean linked; - protected BufferedImage tappedImage; + protected final BufferedImage tappedImage; protected BufferedImage flippedImage; /** Creates new form Permanent diff --git a/Mage.Client/src/main/java/mage/client/components/ColorPane.java b/Mage.Client/src/main/java/mage/client/components/ColorPane.java index 8fc39aa5be9..79851a659d3 100644 --- a/Mage.Client/src/main/java/mage/client/components/ColorPane.java +++ b/Mage.Client/src/main/java/mage/client/components/ColorPane.java @@ -13,9 +13,7 @@ import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JTextPane; import javax.swing.SwingUtilities; -import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkEvent.EventType; -import javax.swing.event.HyperlinkListener; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; @@ -35,8 +33,8 @@ import mage.view.CardView; */ public class ColorPane extends JEditorPane { - HTMLEditorKit kit = new HTMLEditorKit(); - HTMLDocument doc = new HTMLDocument(); + final HTMLEditorKit kit = new HTMLEditorKit(); + final HTMLDocument doc = new HTMLDocument(); private int tooltipDelay; private int tooltipCounter; private boolean hyperlinkEnabled = false; @@ -47,39 +45,28 @@ public class ColorPane extends JEditorPane { } private void addHyperlinkHandlers() { - addHyperlinkListener(new HyperlinkListener() { - - @Override - public void hyperlinkUpdate(final HyperlinkEvent e) { - ThreadUtils.threadPool2.submit(new Runnable() { - - @Override - public void run() { - tooltipDelay = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_SHOW_TOOLTIPS_DELAY, 300); - if (tooltipDelay == 0) { - return; - } - String name = e.getDescription().substring(1); - CardInfo card = CardRepository.instance.findCard(name); - try { - final Component container = MageFrame.getUI().getComponent(MageComponents.POPUP_CONTAINER); - if (e.getEventType() == EventType.EXITED) { - setPopupVisibility(container, false); - } - if (e.getEventType() == EventType.ENTERED && card != null) { - CardInfoPane cardInfoPane = (CardInfoPane) MageFrame.getUI().getComponent(MageComponents.CARD_INFO_PANE); - cardInfoPane.setCard(new CardView(card.getMockCard()), container); - setPopupVisibility(container, true); - } - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - - } - }); + addHyperlinkListener(e -> ThreadUtils.threadPool2.submit(() -> { + tooltipDelay = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_SHOW_TOOLTIPS_DELAY, 300); + if (tooltipDelay == 0) { + return; + } + String name = e.getDescription().substring(1); + CardInfo card = CardRepository.instance.findCard(name); + try { + final Component container = MageFrame.getUI().getComponent(MageComponents.POPUP_CONTAINER); + if (e.getEventType() == EventType.EXITED) { + setPopupVisibility(container, false); + } + if (e.getEventType() == EventType.ENTERED && card != null) { + CardInfoPane cardInfoPane = (CardInfoPane) MageFrame.getUI().getComponent(MageComponents.CARD_INFO_PANE); + cardInfoPane.setCard(new CardView(card.getMockCard()), container); + setPopupVisibility(container, true); + } + } catch (InterruptedException e1) { + e1.printStackTrace(); } - }); + })); addMouseListener(new MouseAdapter() { @Override @@ -96,22 +83,19 @@ public class ColorPane extends JEditorPane { private void setPopupVisibility(final Component container, final boolean show) throws InterruptedException { final Component c = MageFrame.getUI().getComponent(MageComponents.DESKTOP_PANE); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - tooltipCounter += show ? 1 : -1; - if (tooltipCounter < 0) { - tooltipCounter = 0; - } - if (tooltipCounter > 0) { - Point location = new Point(getLocationOnScreen().x - container.getWidth(), MouseInfo.getPointerInfo().getLocation().y); - Component parentComponent = MageFrame.getInstance(); - location = GuiDisplayUtil.keepComponentInsideParent(location, parentComponent.getLocationOnScreen(), container, parentComponent); - container.setLocation(location); - } - container.setVisible(tooltipCounter > 0); - c.repaint(); + SwingUtilities.invokeLater(() -> { + tooltipCounter += show ? 1 : -1; + if (tooltipCounter < 0) { + tooltipCounter = 0; } + if (tooltipCounter > 0) { + Point location = new Point(getLocationOnScreen().x - container.getWidth(), MouseInfo.getPointerInfo().getLocation().y); + Component parentComponent = MageFrame.getInstance(); + location = GuiDisplayUtil.keepComponentInsideParent(location, parentComponent.getLocationOnScreen(), container, parentComponent); + container.setLocation(location); + } + container.setVisible(tooltipCounter > 0); + c.repaint(); }); } diff --git a/Mage.Client/src/main/java/mage/client/components/MageDesktopManager.java b/Mage.Client/src/main/java/mage/client/components/MageDesktopManager.java index e2c704f2d5e..146af3294b2 100644 --- a/Mage.Client/src/main/java/mage/client/components/MageDesktopManager.java +++ b/Mage.Client/src/main/java/mage/client/components/MageDesktopManager.java @@ -6,12 +6,8 @@ package mage.client.components; import java.awt.BorderLayout; -import javax.swing.DefaultDesktopManager; -import javax.swing.DesktopManager; -import javax.swing.JDesktopPane; -import javax.swing.JFrame; -import javax.swing.JInternalFrame; -import javax.swing.SwingUtilities; +import javax.swing.*; + import mage.client.dialog.CardInfoWindowDialog; /** @@ -41,24 +37,21 @@ public class MageDesktopManager extends DefaultDesktopManager { } public static void main(String args[]) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - JFrame frame = new JFrame(); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + SwingUtilities.invokeLater(() -> { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - JDesktopPane desktopPane = new JDesktopPane(); - DesktopManager dm = new MageDesktopManager(); - desktopPane.setDesktopManager(dm); - JInternalFrame internalFrame = new JInternalFrame("Test Internal Frame", true, false, true, true); - internalFrame.setSize(200, 150); - internalFrame.setVisible(true); - desktopPane.add(internalFrame); + JDesktopPane desktopPane = new JDesktopPane(); + DesktopManager dm = new MageDesktopManager(); + desktopPane.setDesktopManager(dm); + JInternalFrame internalFrame = new JInternalFrame("Test Internal Frame", true, false, true, true); + internalFrame.setSize(200, 150); + internalFrame.setVisible(true); + desktopPane.add(internalFrame); - frame.add(desktopPane, BorderLayout.CENTER); - frame.setSize(800, 600); - frame.setVisible(true); - } + frame.add(desktopPane, BorderLayout.CENTER); + frame.setSize(800, 600); + frame.setVisible(true); }); } } diff --git a/Mage.Client/src/main/java/mage/client/components/MageJDesktop.java b/Mage.Client/src/main/java/mage/client/components/MageJDesktop.java index f090861b2c0..8c5052ce6de 100644 --- a/Mage.Client/src/main/java/mage/client/components/MageJDesktop.java +++ b/Mage.Client/src/main/java/mage/client/components/MageJDesktop.java @@ -24,7 +24,7 @@ public class MageJDesktop extends JDesktopPane { UIDefaults map = new UIDefaults(); Painter painter = new Painter() { - Color color = null; + final Color color = null; @Override public void paint(Graphics2D g, Object c, int w, int h) { diff --git a/Mage.Client/src/main/java/mage/client/components/MageRoundPane.java b/Mage.Client/src/main/java/mage/client/components/MageRoundPane.java index 53a2d1878e2..4d318a7beda 100644 --- a/Mage.Client/src/main/java/mage/client/components/MageRoundPane.java +++ b/Mage.Client/src/main/java/mage/client/components/MageRoundPane.java @@ -27,23 +27,13 @@ public class MageRoundPane extends JPanel { private final Color defaultBackgroundColor = new Color(141, 130, 112, 200); private Color backgroundColor = defaultBackgroundColor; private final int alpha = 0; - private static Map SHADOW_IMAGE_CACHE; + private static final Map SHADOW_IMAGE_CACHE; private static final Map IMAGE_CACHE; static { - SHADOW_IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap(new Function() { - @Override - public BufferedImage apply(ShadowKey key) { - return createShadowImage(key); - } - })); + SHADOW_IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap((Function) key -> createShadowImage(key))); - IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap(new Function() { - @Override - public BufferedImage apply(Key key) { - return createImage(key); - } - })); + IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap((Function) key -> createImage(key))); } private final static class ShadowKey { diff --git a/Mage.Client/src/main/java/mage/client/components/MageSynthStyleFactory.java b/Mage.Client/src/main/java/mage/client/components/MageSynthStyleFactory.java index 73eb67b69ca..375f7c60d5e 100644 --- a/Mage.Client/src/main/java/mage/client/components/MageSynthStyleFactory.java +++ b/Mage.Client/src/main/java/mage/client/components/MageSynthStyleFactory.java @@ -14,7 +14,7 @@ import javax.swing.plaf.synth.SynthStyleFactory; * @author nantuko */ public class MageSynthStyleFactory extends SynthStyleFactory { - private SynthStyleFactory wrappedFactory; + private final SynthStyleFactory wrappedFactory; public MageSynthStyleFactory(SynthStyleFactory factory) { this.wrappedFactory = factory; diff --git a/Mage.Client/src/main/java/mage/client/components/MageTextArea.java b/Mage.Client/src/main/java/mage/client/components/MageTextArea.java index 219e0f72d7c..9f2f6975df0 100644 --- a/Mage.Client/src/main/java/mage/client/components/MageTextArea.java +++ b/Mage.Client/src/main/java/mage/client/components/MageTextArea.java @@ -57,22 +57,19 @@ public class MageTextArea extends JEditorPane { buffer.append(""); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - String promptText = buffer.toString(); - MageTextArea.super.setText(promptText); - // in case the text don't fit in the panel a tooltip with the text is added - if (panelWidth > 0 && MageTextArea.this.getPreferredSize().getWidth() > panelWidth) { - String tooltip = "

" + basicText + "

"; - MageTextArea.super.setToolTipText(tooltip); - } else { - MageTextArea.super.setToolTipText(null); - } - setCaretPosition(0); + SwingUtilities.invokeLater(() -> { + String promptText = buffer.toString(); + MageTextArea.super.setText(promptText); + // in case the text don't fit in the panel a tooltip with the text is added + if (panelWidth > 0 && MageTextArea.this.getPreferredSize().getWidth() > panelWidth) { + String tooltip = "

" + basicText + "

"; + MageTextArea.super.setToolTipText(tooltip); + } else { + MageTextArea.super.setToolTipText(null); } + setCaretPosition(0); }); } } diff --git a/Mage.Client/src/main/java/mage/client/components/MageUI.java b/Mage.Client/src/main/java/mage/client/components/MageUI.java index 9eaa377525f..48c14687f4a 100644 --- a/Mage.Client/src/main/java/mage/client/components/MageUI.java +++ b/Mage.Client/src/main/java/mage/client/components/MageUI.java @@ -96,12 +96,7 @@ public class MageUI { while (!j.isEnabled()) { Thread.sleep(10); } - Thread t = new Thread(new Runnable() { - @Override - public void run() { - j.doClick(); - } - }); + Thread t = new Thread(() -> j.doClick()); t.start(); } } diff --git a/Mage.Client/src/main/java/mage/client/components/ability/AbilityPicker.java b/Mage.Client/src/main/java/mage/client/components/ability/AbilityPicker.java index 9c06eb63d2d..574b6036c93 100644 --- a/Mage.Client/src/main/java/mage/client/components/ability/AbilityPicker.java +++ b/Mage.Client/src/main/java/mage/client/components/ability/AbilityPicker.java @@ -49,7 +49,7 @@ public class AbilityPicker extends JXPanel implements MouseWheelListener { private static final String IMAGE_RIGHT_PATH = "/game/right.png"; private static final String IMAGE_RIGHT_HOVERED_PATH = "/game/right_hovered.png"; - private static Color SELECTED_COLOR = new Color(64, 147, 208); + private static final Color SELECTED_COLOR = new Color(64, 147, 208); private static Color BORDER_COLOR = new Color(0, 0, 0, 50); private boolean selected = false; diff --git a/Mage.Client/src/main/java/mage/client/components/ability/BackgroundPainter.java b/Mage.Client/src/main/java/mage/client/components/ability/BackgroundPainter.java index 81784aac1a4..f374b2efcf6 100644 --- a/Mage.Client/src/main/java/mage/client/components/ability/BackgroundPainter.java +++ b/Mage.Client/src/main/java/mage/client/components/ability/BackgroundPainter.java @@ -14,9 +14,9 @@ import java.awt.geom.RoundRectangle2D; */ public class BackgroundPainter extends AbstractPainter { - private Color bgColor = Color.black; + private final Color bgColor = Color.black; - float bgalpha = 0.6f; + final float bgalpha = 0.6f; public BackgroundPainter() { super(); diff --git a/Mage.Client/src/main/java/mage/client/components/ability/MageScrollButton.java b/Mage.Client/src/main/java/mage/client/components/ability/MageScrollButton.java index d5465fadead..0b51ad1d101 100644 --- a/Mage.Client/src/main/java/mage/client/components/ability/MageScrollButton.java +++ b/Mage.Client/src/main/java/mage/client/components/ability/MageScrollButton.java @@ -16,10 +16,10 @@ import javax.swing.plaf.metal.MetalScrollButton; */ public class MageScrollButton extends MetalScrollButton { - private static ImageIcon buttonLeft; - private static ImageIcon buttonRight; - private static ImageIcon buttonUp; - private static ImageIcon buttonDown; + private static final ImageIcon buttonLeft; + private static final ImageIcon buttonRight; + private static final ImageIcon buttonUp; + private static final ImageIcon buttonDown; private int width; diff --git a/Mage.Client/src/main/java/mage/client/components/ability/MageScrollbarUI.java b/Mage.Client/src/main/java/mage/client/components/ability/MageScrollbarUI.java index 50a1a9faa52..0aaf5d176e8 100644 --- a/Mage.Client/src/main/java/mage/client/components/ability/MageScrollbarUI.java +++ b/Mage.Client/src/main/java/mage/client/components/ability/MageScrollbarUI.java @@ -27,7 +27,7 @@ import javax.swing.plaf.metal.MetalScrollBarUI; */ public class MageScrollbarUI extends MetalScrollBarUI { - private static int ANTI_WIDTH = -3; + private static final int ANTI_WIDTH = -3; @Override public void installUI(JComponent c) { diff --git a/Mage.Client/src/main/java/mage/client/components/ext/MageFloatPane.java b/Mage.Client/src/main/java/mage/client/components/ext/MageFloatPane.java index b076702f251..57af47dc7e9 100644 --- a/Mage.Client/src/main/java/mage/client/components/ext/MageFloatPane.java +++ b/Mage.Client/src/main/java/mage/client/components/ext/MageFloatPane.java @@ -21,11 +21,9 @@ public class MageFloatPane extends JEditorPane { } public void setCard(final String text) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - setText(text); - setCaretPosition(0); - } + SwingUtilities.invokeLater(() -> { + setText(text); + setCaretPosition(0); }); } } \ No newline at end of file diff --git a/Mage.Client/src/main/java/mage/client/components/ext/dlg/DialogManager.java b/Mage.Client/src/main/java/mage/client/components/ext/dlg/DialogManager.java index 2c9dc93239f..2eeafeddb48 100644 --- a/Mage.Client/src/main/java/mage/client/components/ext/dlg/DialogManager.java +++ b/Mage.Client/src/main/java/mage/client/components/ext/dlg/DialogManager.java @@ -279,7 +279,7 @@ public class DialogManager extends JComponent implements MouseListener, @Override public void mouseDragged(MouseEvent e) { - if (bDragged == true) { + if (bDragged) { dx = e.getX() - mx; dy = e.getY() - my; diff --git a/Mage.Client/src/main/java/mage/client/components/ext/dlg/impl/ChoiceDialog.java b/Mage.Client/src/main/java/mage/client/components/ext/dlg/impl/ChoiceDialog.java index b9dccca8050..9294a12a070 100644 --- a/Mage.Client/src/main/java/mage/client/components/ext/dlg/impl/ChoiceDialog.java +++ b/Mage.Client/src/main/java/mage/client/components/ext/dlg/impl/ChoiceDialog.java @@ -184,11 +184,7 @@ public class ChoiceDialog extends IDialogPanel { jButtonOK.setBounds(new Rectangle(w / 2 - 40, h - 50, 60, 60)); jButtonOK.setToolTipText("Ok"); - jButtonOK.setObserver(new Command() { - public void execute() { - DialogManager.getManager(gameId).fadeOut((DialogContainer) getParent()); - } - }); + jButtonOK.setObserver(() -> DialogManager.getManager(gameId).fadeOut((DialogContainer) getParent())); } return jButtonOK; } @@ -204,27 +200,24 @@ public class ChoiceDialog extends IDialogPanel { jButtonPrevPage.setBounds(new Rectangle(w / 2 - 125, h - 50, 60, 60)); jButtonPrevPage.setVisible(false); - jButtonPrevPage.setObserver(new Command() { - - public void execute() { - if (page == 1) { - return; - } - - AudioManager.playPrevPage(); - - page--; - getJButtonPrevPage().setVisible(false); - getJButtonOK().setVisible(false); - getJButtonNextPage().setVisible(false); - revalidate(); - displayCards(params.getCards(), params.gameId, params.bigCard); - if (page != 1) { - getJButtonPrevPage().setVisible(true); - } - getJButtonOK().setVisible(true); - getJButtonNextPage().setVisible(true); + jButtonPrevPage.setObserver(() -> { + if (page == 1) { + return; } + + AudioManager.playPrevPage(); + + page--; + getJButtonPrevPage().setVisible(false); + getJButtonOK().setVisible(false); + getJButtonNextPage().setVisible(false); + revalidate(); + displayCards(params.getCards(), params.gameId, params.bigCard); + if (page != 1) { + getJButtonPrevPage().setVisible(true); + } + getJButtonOK().setVisible(true); + getJButtonNextPage().setVisible(true); }); } return jButtonPrevPage; diff --git a/Mage.Client/src/main/java/mage/client/components/ext/dlg/impl/StackDialog.java b/Mage.Client/src/main/java/mage/client/components/ext/dlg/impl/StackDialog.java index 3748528ca45..a8720e4deae 100644 --- a/Mage.Client/src/main/java/mage/client/components/ext/dlg/impl/StackDialog.java +++ b/Mage.Client/src/main/java/mage/client/components/ext/dlg/impl/StackDialog.java @@ -32,9 +32,9 @@ public class StackDialog extends IDialogPanel { private HoverButton jButtonResponse = null; private JLayeredPane jLayeredPane; - private FeedbackPanel feedbackPanel; + private final FeedbackPanel feedbackPanel; - private UUID gameId; + private final UUID gameId; private class CustomLabel extends JLabel { @@ -51,7 +51,7 @@ public class StackDialog extends IDialogPanel { } private static final long serialVersionUID = 1L; - }; + } /** * This is the default constructor diff --git a/Mage.Client/src/main/java/mage/client/components/tray/MageTray.java b/Mage.Client/src/main/java/mage/client/components/tray/MageTray.java index f016f0edd24..c18789322c2 100644 --- a/Mage.Client/src/main/java/mage/client/components/tray/MageTray.java +++ b/Mage.Client/src/main/java/mage/client/components/tray/MageTray.java @@ -1,8 +1,7 @@ package mage.client.components.tray; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; + import mage.client.MageFrame; import org.apache.log4j.Logger; import org.mage.plugins.card.utils.impl.ImageManagerImpl; @@ -38,14 +37,11 @@ public class MageTray { trayIcon = new TrayIcon(mainImage); trayIcon.setImageAutoSize(true); - trayIcon.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - stopBlink(); - MageFrame frame = MageFrame.getInstance(); - frame.setVisible(true); - frame.setState(Frame.NORMAL); - } + trayIcon.addActionListener(e -> { + stopBlink(); + MageFrame frame = MageFrame.getInstance(); + frame.setVisible(true); + frame.setState(Frame.NORMAL); }); final SystemTray tray = SystemTray.getSystemTray(); @@ -59,47 +55,17 @@ public class MageTray { MenuItem aboutItem = new MenuItem("About Mage"); MenuItem exitItem = new MenuItem("Exit"); - imagesItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - MageFrame.getInstance().downloadImages(); - } - }); + imagesItem.addActionListener(e -> MageFrame.getInstance().downloadImages()); - iconsItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - MageFrame.getInstance().downloadAdditionalResources(); - } - }); + iconsItem.addActionListener(e -> MageFrame.getInstance().downloadAdditionalResources()); - stopBlinkItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - stopBlink(); - } - }); + stopBlinkItem.addActionListener(e -> stopBlink()); - preferencesItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - MageFrame.getInstance().btnPreferencesActionPerformed(null); - } - }); + preferencesItem.addActionListener(e -> MageFrame.getInstance().btnPreferencesActionPerformed(null)); - aboutItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - MageFrame.getInstance().btnAboutActionPerformed(null); - } - }); + aboutItem.addActionListener(e -> MageFrame.getInstance().btnAboutActionPerformed(null)); - exitItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - MageFrame.getInstance().exitApp(); - } - }); + exitItem.addActionListener(e -> MageFrame.getInstance().exitApp()); popup.add(imagesItem); popup.add(iconsItem); @@ -129,23 +95,20 @@ public class MageTray { synchronized (MageTray.class) { if (state == 0) { state = 1; - new Thread(new Runnable() { - @Override - public void run() { - try { - int i = 0; - while (state != 3) { - trayIcon.setImage(i == 0 ? mainImage : flashedImage); - Thread.sleep(600); - i = i == 0 ? 1 : 0; - } - trayIcon.setImage(mainImage); - state = 0; - } catch (InterruptedException e) { - e.printStackTrace(); + new Thread(() -> { + try { + int i = 0; + while (state != 3) { + trayIcon.setImage(i == 0 ? mainImage : flashedImage); + Thread.sleep(600); + i = i == 0 ? 1 : 0; } - + trayIcon.setImage(mainImage); + state = 0; + } catch (InterruptedException e) { + e.printStackTrace(); } + }).start(); } } diff --git a/Mage.Client/src/main/java/mage/client/deck/generator/DeckGenerator.java b/Mage.Client/src/main/java/mage/client/deck/generator/DeckGenerator.java index 97471ed50b7..1da57aa8470 100644 --- a/Mage.Client/src/main/java/mage/client/deck/generator/DeckGenerator.java +++ b/Mage.Client/src/main/java/mage/client/deck/generator/DeckGenerator.java @@ -31,7 +31,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Random; import java.util.Set; import mage.cards.Card; import mage.cards.decks.Deck; diff --git a/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorCMC.java b/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorCMC.java index e56f2d8a61f..351e95a29d1 100644 --- a/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorCMC.java +++ b/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorCMC.java @@ -69,7 +69,8 @@ public enum DeckGeneratorCMC { add(new CMC(7, 100, 0.15f)); }}); - private ArrayList poolCMCs60, poolCMCs40; + private final ArrayList poolCMCs60; + private final ArrayList poolCMCs40; DeckGeneratorCMC(ArrayList CMCs60, ArrayList CMCs40) { this.poolCMCs60 = CMCs60; diff --git a/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorDialog.java b/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorDialog.java index eee152d4969..287579efcb6 100644 --- a/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorDialog.java +++ b/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorDialog.java @@ -28,9 +28,7 @@ package mage.client.deck.generator; import java.awt.*; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.text.SimpleDateFormat; @@ -193,12 +191,9 @@ public class DeckGeneratorDialog { // Advanced checkbox (enable/disable advanced configuration) cAdvanced = new JCheckBox("Advanced"); cAdvanced.setToolTipText("Enable advanced configuration options"); - cAdvanced.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent itemEvent) { - boolean enable = cAdvanced.isSelected(); - enableAdvancedPanel(enable); - } + cAdvanced.addItemListener(itemEvent -> { + boolean enable = cAdvanced.isSelected(); + enableAdvancedPanel(enable); }); // Advanced Checkbox @@ -216,23 +211,17 @@ public class DeckGeneratorDialog { mainPanel.add(advancedPanel, c); btnGenerate = new JButton("Ok"); - btnGenerate.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - btnGenerate.setEnabled(false); - colorsChooser.setEnabled(false); - selectedColors = (String) colorsChooser.getSelectedItem(); - dlg.setVisible(false); - MageFrame.getPreferences().put("genDeckColor", selectedColors); - } + btnGenerate.addActionListener(e -> { + btnGenerate.setEnabled(false); + colorsChooser.setEnabled(false); + selectedColors = (String) colorsChooser.getSelectedItem(); + dlg.setVisible(false); + MageFrame.getPreferences().put("genDeckColor", selectedColors); }); btnCancel = new JButton("Cancel"); - btnCancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - dlg.setVisible(false); - selectedColors = null; - } + btnCancel.addActionListener(e -> { + dlg.setVisible(false); + selectedColors = null; }); JButton[] options = {btnGenerate, btnCancel}; JOptionPane optionPane = new JOptionPane(mainPanel, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, options, options[1]); @@ -308,12 +297,9 @@ public class DeckGeneratorDialog { c.gridy = 2; btnReset = new JButton("Reset"); btnReset.setToolTipText("Reset advanced dialog to default values"); - btnReset.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - cbCMC.setSelectedItem(DeckGeneratorCMC.Default); - adjustingSliderPanel.resetValues(); - } + btnReset.addActionListener(actionEvent -> { + cbCMC.setSelectedItem(DeckGeneratorCMC.Default); + adjustingSliderPanel.resetValues(); }); advancedPanel.add(btnReset, c); diff --git a/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorPool.java b/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorPool.java index b5dcd45edf7..a9fae68040a 100644 --- a/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorPool.java +++ b/Mage.Client/src/main/java/mage/client/deck/generator/DeckGeneratorPool.java @@ -44,12 +44,12 @@ public class DeckGeneratorPool { - public static int DEFAULT_CREATURE_PERCENTAGE = 38; - public static int DEFAULT_NON_CREATURE_PERCENTAGE = 21; - public static int DEFAULT_LAND_PERCENTAGE = 41; + public static final int DEFAULT_CREATURE_PERCENTAGE = 38; + public static final int DEFAULT_NON_CREATURE_PERCENTAGE = 21; + public static final int DEFAULT_LAND_PERCENTAGE = 41; private final List allowedColors; - private boolean colorlessAllowed; + private final boolean colorlessAllowed; private final List poolCMCs; private final int creatureCount; private final int nonCreatureCount; @@ -58,14 +58,14 @@ public class DeckGeneratorPool private final int deckSize; // Count how many copies of the card exists in the deck to check we don't go over 4 copies (or 1 for singleton) - private Map cardCounts = new HashMap<>(); + private final Map cardCounts = new HashMap<>(); // If there is only a single color selected to generate a deck private boolean monoColored = false; // List of cards so far in the deck - private List deckCards = new ArrayList<>(); + private final List deckCards = new ArrayList<>(); // List of reserve cards found to fix up undersized decks - private List reserveSpells = new ArrayList<>(); - private Deck deck; + private final List reserveSpells = new ArrayList<>(); + private final Deck deck; /** * Creates a card pool with specified criterea used when generating a deck. diff --git a/Mage.Client/src/main/java/mage/client/deck/generator/RatioAdjustingSliderPanel.java b/Mage.Client/src/main/java/mage/client/deck/generator/RatioAdjustingSliderPanel.java index 2355c088ab7..219bd7ad277 100644 --- a/Mage.Client/src/main/java/mage/client/deck/generator/RatioAdjustingSliderPanel.java +++ b/Mage.Client/src/main/java/mage/client/deck/generator/RatioAdjustingSliderPanel.java @@ -29,8 +29,6 @@ package mage.client.deck.generator; import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; import java.awt.*; import java.util.*; import java.util.List; @@ -41,13 +39,13 @@ import java.util.List; public class RatioAdjustingSliderPanel extends JPanel { private JStorageSlider creatureSlider, nonCreatureSlider, landSlider; - private List textLabels = new ArrayList<>(); + private final List textLabels = new ArrayList<>(); private AdjustingSliderGroup sg; private class JStorageSlider extends JSlider { // Slider stores its initial value to revert to when reset - private int defaultValue; + private final int defaultValue; private int previousValue; public JStorageSlider(int min, int max, int value) { @@ -86,12 +84,7 @@ public class RatioAdjustingSliderPanel extends JPanel { storageSliders = new ArrayList<>(); for(JStorageSlider slider: sliders) { storageSliders.add(slider); - slider.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - fireSliderChangedEvent((JStorageSlider) e.getSource()); - } - }); + slider.addChangeListener(e -> fireSliderChangedEvent((JStorageSlider) e.getSource())); } } public void fireSliderChangedEvent(JStorageSlider source) { @@ -177,19 +170,16 @@ public class RatioAdjustingSliderPanel extends JPanel { final JLabel label = new JLabel(" " + String.valueOf(slider.getValue()) + "%"); - slider.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - String value = String.valueOf(slider.getValue()); - StringBuilder labelBuilder = new StringBuilder(); - // Pad with spaces so all percentage labels are of equal size - for(int i = 0; i < (5-value.length()); i++) { - labelBuilder.append(" "); - } - labelBuilder.append(value); - labelBuilder.append("%"); - label.setText(labelBuilder.toString()); + slider.addChangeListener(e -> { + String value = String.valueOf(slider.getValue()); + StringBuilder labelBuilder = new StringBuilder(); + // Pad with spaces so all percentage labels are of equal size + for(int i = 0; i < (5-value.length()); i++) { + labelBuilder.append(" "); } + labelBuilder.append(value); + labelBuilder.append("%"); + label.setText(labelBuilder.toString()); }); return label; } diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/CardSelector.java b/Mage.Client/src/main/java/mage/client/deckeditor/CardSelector.java index fe676343a9c..2c1d985d301 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/CardSelector.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/CardSelector.java @@ -83,12 +83,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene private boolean limited = false; private final SortSetting sortSetting; - private final ActionListener searchAction = new ActionListener() { - @Override - public void actionPerformed(ActionEvent evt) { - jButtonSearchActionPerformed(evt); - } - }; + private final ActionListener searchAction = evt -> jButtonSearchActionPerformed(evt); /** * Creates new form CardSelector @@ -494,11 +489,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbRed.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbRed.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/color_red.png"))); // NOI18N tbRed.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbRed.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbRedActionPerformed(evt); - } - }); + tbRed.addActionListener(evt -> tbRedActionPerformed(evt)); tbColor.add(tbRed); tbGreen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/color_green_off.png"))); // NOI18N @@ -510,11 +501,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbGreen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/color_green.png"))); // NOI18N tbGreen.setVerifyInputWhenFocusTarget(false); tbGreen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbGreen.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbGreenActionPerformed(evt); - } - }); + tbGreen.addActionListener(evt -> tbGreenActionPerformed(evt)); tbColor.add(tbGreen); tbBlue.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/color_blueOff.png"))); // NOI18N @@ -525,11 +512,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbBlue.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbBlue.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/color_blue.png"))); // NOI18N tbBlue.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbBlue.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbBlueActionPerformed(evt); - } - }); + tbBlue.addActionListener(evt -> tbBlueActionPerformed(evt)); tbColor.add(tbBlue); tbBlack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/color_black_off.png"))); // NOI18N @@ -540,11 +523,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbBlack.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbBlack.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/color_black.png"))); // NOI18N tbBlack.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbBlack.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbBlackActionPerformed(evt); - } - }); + tbBlack.addActionListener(evt -> tbBlackActionPerformed(evt)); tbColor.add(tbBlack); tbWhite.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/color_white_off.png"))); // NOI18N @@ -555,11 +534,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbWhite.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbWhite.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/color_white.png"))); // NOI18N tbWhite.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbWhite.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbWhiteActionPerformed(evt); - } - }); + tbWhite.addActionListener(evt -> tbWhiteActionPerformed(evt)); tbColor.add(tbWhite); tbColorless.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/colorless_off.png"))); // NOI18N @@ -570,11 +545,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbColorless.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbColorless.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/colorless.png"))); // NOI18N tbColorless.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbColorless.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbColorlessActionPerformed(evt); - } - }); + tbColorless.addActionListener(evt -> tbColorlessActionPerformed(evt)); tbColor.add(tbColorless); tbColor.add(jSeparator1); @@ -583,11 +554,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene cbExpansionSet.setMinimumSize(new java.awt.Dimension(250, 25)); cbExpansionSet.setName("cbExpansionSet"); // NOI18N cbExpansionSet.setPreferredSize(new java.awt.Dimension(250, 25)); - cbExpansionSet.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbExpansionSetActionPerformed(evt); - } - }); + cbExpansionSet.addActionListener(evt -> cbExpansionSetActionPerformed(evt)); tbColor.add(cbExpansionSet); tbColor.add(jSeparator2); @@ -596,22 +563,14 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene btnBooster.setFocusable(false); btnBooster.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnBooster.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnBooster.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnBoosterActionPerformed(evt); - } - }); + btnBooster.addActionListener(evt -> btnBoosterActionPerformed(evt)); tbColor.add(btnBooster); btnClear.setText("Clear"); btnClear.setFocusable(false); btnClear.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnClear.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnClear.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnClearActionPerformed(evt); - } - }); + btnClear.addActionListener(evt -> btnClearActionPerformed(evt)); tbColor.add(btnClear); tbTypes.setFloatable(false); @@ -627,11 +586,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbLand.setFocusable(false); tbLand.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbLand.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbLand.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbLandActionPerformed(evt); - } - }); + tbLand.addActionListener(evt -> tbLandActionPerformed(evt)); tbTypes.add(tbLand); tbCreatures.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/type_creatures.png"))); // NOI18N @@ -642,11 +597,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbCreatures.setFocusable(false); tbCreatures.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbCreatures.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbCreatures.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbCreaturesActionPerformed(evt); - } - }); + tbCreatures.addActionListener(evt -> tbCreaturesActionPerformed(evt)); tbTypes.add(tbCreatures); tbArifiacts.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/type_artifact.png"))); // NOI18N @@ -657,11 +608,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbArifiacts.setFocusable(false); tbArifiacts.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbArifiacts.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbArifiacts.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbArifiactsActionPerformed(evt); - } - }); + tbArifiacts.addActionListener(evt -> tbArifiactsActionPerformed(evt)); tbTypes.add(tbArifiacts); tbSorceries.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/type_sorcery.png"))); // NOI18N @@ -672,11 +619,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbSorceries.setFocusable(false); tbSorceries.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbSorceries.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbSorceries.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbSorceriesActionPerformed(evt); - } - }); + tbSorceries.addActionListener(evt -> tbSorceriesActionPerformed(evt)); tbTypes.add(tbSorceries); tbInstants.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/type_instant.png"))); // NOI18N @@ -687,11 +630,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbInstants.setFocusable(false); tbInstants.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbInstants.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbInstants.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbInstantsActionPerformed(evt); - } - }); + tbInstants.addActionListener(evt -> tbInstantsActionPerformed(evt)); tbTypes.add(tbInstants); tbEnchantments.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/type_enchantment.png"))); // NOI18N @@ -702,11 +641,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbEnchantments.setFocusable(false); tbEnchantments.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbEnchantments.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbEnchantments.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbEnchantmentsActionPerformed(evt); - } - }); + tbEnchantments.addActionListener(evt -> tbEnchantmentsActionPerformed(evt)); tbTypes.add(tbEnchantments); tbPlaneswalkers.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/type_planeswalker.png"))); // NOI18N @@ -717,11 +652,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene tbPlaneswalkers.setFocusable(false); tbPlaneswalkers.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); tbPlaneswalkers.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - tbPlaneswalkers.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - tbPlaneswalkersActionPerformed(evt); - } - }); + tbPlaneswalkers.addActionListener(evt -> tbPlaneswalkersActionPerformed(evt)); tbTypes.add(tbPlaneswalkers); tbTypes.add(jSeparator6); @@ -730,11 +661,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene chkPiles.setFocusable(false); chkPiles.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); chkPiles.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - chkPiles.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - chkPilesActionPerformed(evt); - } - }); + chkPiles.addActionListener(evt -> chkPilesActionPerformed(evt)); tbTypes.add(chkPiles); tbTypes.add(jSeparator3); @@ -742,11 +669,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene cbSortBy.setMaximumSize(new java.awt.Dimension(120, 20)); cbSortBy.setMinimumSize(new java.awt.Dimension(120, 20)); cbSortBy.setPreferredSize(new java.awt.Dimension(120, 20)); - cbSortBy.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbSortByActionPerformed(evt); - } - }); + cbSortBy.addActionListener(evt -> cbSortByActionPerformed(evt)); tbTypes.add(cbSortBy); tbTypes.add(jSeparator4); @@ -761,11 +684,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene jToggleListView.setMaximumSize(new java.awt.Dimension(37, 22)); jToggleListView.setMinimumSize(new java.awt.Dimension(37, 22)); jToggleListView.setPreferredSize(new java.awt.Dimension(37, 22)); - jToggleListView.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jToggleListViewActionPerformed(evt); - } - }); + jToggleListView.addActionListener(evt -> jToggleListViewActionPerformed(evt)); tbTypes.add(jToggleListView); bgView.add(jToggleCardView); @@ -780,11 +699,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene jToggleCardView.setName(""); // NOI18N jToggleCardView.setPreferredSize(new java.awt.Dimension(37, 22)); jToggleCardView.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - jToggleCardView.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jToggleCardViewActionPerformed(evt); - } - }); + jToggleCardView.addActionListener(evt -> jToggleCardViewActionPerformed(evt)); tbTypes.add(jToggleCardView); cardSelectorScrollPane.setToolTipText("Double click to add the card to the main deck.
\nALT + Double click to add the card to the sideboard."); @@ -798,11 +713,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene jButtonAddToMain.setMaximumSize(new java.awt.Dimension(42, 23)); jButtonAddToMain.setMinimumSize(new java.awt.Dimension(42, 23)); jButtonAddToMain.setPreferredSize(new java.awt.Dimension(40, 28)); - jButtonAddToMain.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jButtonAddToMainActionPerformed(evt); - } - }); + jButtonAddToMain.addActionListener(evt -> jButtonAddToMainActionPerformed(evt)); jButtonAddToSideboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/sideboard_in.png"))); // NOI18N jButtonAddToSideboard.setToolTipText("Add selected cards to sideboard.
\nAlternative: ALT key + Double click the card in card selector to move a card to the sideboard."); @@ -810,11 +721,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene jButtonAddToSideboard.setMaximumSize(new java.awt.Dimension(100, 30)); jButtonAddToSideboard.setMinimumSize(new java.awt.Dimension(10, 30)); jButtonAddToSideboard.setPreferredSize(new java.awt.Dimension(40, 28)); - jButtonAddToSideboard.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jButtonAddToSideboardActionPerformed(evt); - } - }); + jButtonAddToSideboard.addActionListener(evt -> jButtonAddToSideboardActionPerformed(evt)); jLabelSearch.setText("Search:"); jLabelSearch.setToolTipText("Searches for card names and in the rule text of the card."); @@ -823,19 +730,11 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene jButtonSearch.setText("Search"); jButtonSearch.setToolTipText("Performs the search."); - jButtonSearch.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jButtonSearchActionPerformed(evt); - } - }); + jButtonSearch.addActionListener(evt -> jButtonSearchActionPerformed(evt)); jButtonClean.setText("Clear"); jButtonClean.setToolTipText("Clears the search field."); - jButtonClean.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jButtonCleanActionPerformed(evt); - } - }); + jButtonClean.addActionListener(evt -> jButtonCleanActionPerformed(evt)); cardCountLabel.setText("Card count:"); cardCountLabel.setToolTipText("Number of cards currently shown."); @@ -848,11 +747,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene jButtonRemoveFromMain.setMaximumSize(new java.awt.Dimension(42, 23)); jButtonRemoveFromMain.setMinimumSize(new java.awt.Dimension(42, 23)); jButtonRemoveFromMain.setPreferredSize(new java.awt.Dimension(40, 28)); - jButtonRemoveFromMain.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jButtonRemoveFromMainActionPerformed(evt); - } - }); + jButtonRemoveFromMain.addActionListener(evt -> jButtonRemoveFromMainActionPerformed(evt)); jButtonRemoveFromSideboard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/sideboard_out.png"))); // NOI18N jButtonRemoveFromSideboard.setToolTipText("Remove selected cards from sideboard."); @@ -860,11 +755,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene jButtonRemoveFromSideboard.setMaximumSize(new java.awt.Dimension(10, 30)); jButtonRemoveFromSideboard.setMinimumSize(new java.awt.Dimension(100, 30)); jButtonRemoveFromSideboard.setPreferredSize(new java.awt.Dimension(40, 28)); - jButtonRemoveFromSideboard.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jButtonRemoveFromSideboardActionPerformed(evt); - } - }); + jButtonRemoveFromSideboard.addActionListener(evt -> jButtonRemoveFromSideboardActionPerformed(evt)); javax.swing.GroupLayout cardSelectorBottomPanelLayout = new javax.swing.GroupLayout(cardSelectorBottomPanel); cardSelectorBottomPanel.setLayout(cardSelectorBottomPanelLayout); @@ -1132,12 +1023,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene } public void refresh() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - currentView.refresh(); - } - }); + SwingUtilities.invokeLater(() -> currentView.refresh()); } private TableModel mainModel; diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/DeckArea.java b/Mage.Client/src/main/java/mage/client/deckeditor/DeckArea.java index 9326c8d9d9a..8437a0b310c 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/DeckArea.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/DeckArea.java @@ -55,9 +55,9 @@ import mage.view.CardsView; */ public class DeckArea extends javax.swing.JPanel { - private CardEventSource maindeckVirtualEvent = new CardEventSource(); - private CardEventSource sideboardVirtualEvent = new CardEventSource(); - private Set hiddenCards = new HashSet<>(); + private final CardEventSource maindeckVirtualEvent = new CardEventSource(); + private final CardEventSource sideboardVirtualEvent = new CardEventSource(); + private final Set hiddenCards = new HashSet<>(); private Deck lastDeck = new Deck(); private BigCard lastBigCard = null; private int dividerLocationNormal = 0; diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/DeckEditorPanel.java b/Mage.Client/src/main/java/mage/client/deckeditor/DeckEditorPanel.java index 63f4f7c48f6..53333ae05df 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/DeckEditorPanel.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/DeckEditorPanel.java @@ -44,6 +44,7 @@ import java.util.concurrent.TimeUnit; import javax.swing.*; import javax.swing.Timer; import javax.swing.filechooser.FileFilter; + import mage.cards.Card; import mage.cards.Sets; import mage.cards.decks.Deck; @@ -73,7 +74,6 @@ import mage.view.SimpleCardView; import org.apache.log4j.Logger; /** - * * @author BetaSteward_at_googlemail.com */ public class DeckEditorPanel extends javax.swing.JPanel { @@ -82,7 +82,7 @@ public class DeckEditorPanel extends javax.swing.JPanel { private final JFileChooser fcSelectDeck; private final JFileChooser fcImportDeck; private Deck deck = new Deck(); - private Map temporaryCards = new HashMap<>(); // Cards dragged out of one part of the view into another + private final Map temporaryCards = new HashMap<>(); // Cards dragged out of one part of the view into another private boolean isShowCardInfo = false; private UUID tableId; private DeckEditorMode mode; @@ -108,21 +108,18 @@ public class DeckEditorPanel extends javax.swing.JPanel { jSplitPane1.setOpaque(false); restoreDividerLocationsAndDeckAreaSettings(); countdown = new Timer(1000, - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (--timeout > 0) { - setTimeout(timeout); - } else { - if (updateDeckTask != null) { - updateDeckTask.cancel(true); + e -> { + if (--timeout > 0) { + setTimeout(timeout); + } else { + if (updateDeckTask != null) { + updateDeckTask.cancel(true); + } + setTimeout(0); + countdown.stop(); + removeDeckEditor(); } - setTimeout(0); - countdown.stop(); - removeDeckEditor(); - } - } - }); + }); // Set up tracking to save the deck editor settings when the deck editor is hidden. addHierarchyListener((HierarchyEvent e) -> { @@ -265,213 +262,204 @@ public class DeckEditorPanel extends javax.swing.JPanel { for (ICardGrid component : this.cardSelector.getCardGridComponents()) { component.clearCardEventListeners(); component.addCardEventListener( - new Listener() { - @Override - public void event(Event event) { - switch (event.getEventName()) { - case "double-click": - moveSelectorCardToDeck(event); - break; - case "alt-double-click": - if (mode == DeckEditorMode.FREE_BUILDING) { - moveSelectorCardToSideboard(event); - } else { - // because in match mode selector is used as sideboard the card goes to deck also for shift click + (Listener) event -> { + switch (event.getEventName()) { + case "double-click": moveSelectorCardToDeck(event); - } - break; - case "remove-main": - DeckEditorPanel.this.deckArea.getDeckList().removeSelection(); - break; - case "remove-sideboard": - DeckEditorPanel.this.deckArea.getSideboardList().removeSelection(); - break; - } - refreshDeck(); - } - }); + break; + case "alt-double-click": + if (mode == DeckEditorMode.FREE_BUILDING) { + moveSelectorCardToSideboard(event); + } else { + // because in match mode selector is used as sideboard the card goes to deck also for shift click + moveSelectorCardToDeck(event); + } + break; + case "remove-main": + DeckEditorPanel.this.deckArea.getDeckList().removeSelection(); + break; + case "remove-sideboard": + DeckEditorPanel.this.deckArea.getSideboardList().removeSelection(); + break; + } + refreshDeck(); + }); } this.deckArea.clearDeckEventListeners(); this.deckArea.addDeckEventListener( - new Listener() { - @Override - public void event(Event event) { - if (mode.equals(DeckEditorMode.FREE_BUILDING)) { - switch (event.getEventName()) { - case "double-click": { - SimpleCardView cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getCards()) { - if (card.getId().equals(cardView.getId())) { - deck.getCards().remove(card); - break; + (Listener) event -> { + if (mode == DeckEditorMode.FREE_BUILDING){ + switch (event.getEventName()) { + case "double-click": { + SimpleCardView cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getCards()) { + if (card.getId().equals(cardView.getId())) { + deck.getCards().remove(card); + break; + } } + hidePopup(); + refreshDeck(); + break; } - hidePopup(); - refreshDeck(); - break; - } - case "alt-double-click": { - SimpleCardView cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getCards()) { - if (card.getId().equals(cardView.getId())) { - deck.getCards().remove(card); - deck.getSideboard().add(card); - break; + case "alt-double-click": { + SimpleCardView cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getCards()) { + if (card.getId().equals(cardView.getId())) { + deck.getCards().remove(card); + deck.getSideboard().add(card); + break; + } } + hidePopup(); + refreshDeck(); + break; } - hidePopup(); - refreshDeck(); - break; - } - case "set-number": { - setCardNumberToCardsList(event, deck.getCards()); - break; - } - case "remove-specific-card": { - SimpleCardView cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getCards()) { - if (card.getId().equals(cardView.getId())) { - deck.getCards().remove(card); - storeTemporaryCard(card); - break; + case "set-number": { + setCardNumberToCardsList(event, deck.getCards()); + break; + } + case "remove-specific-card": { + SimpleCardView cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getCards()) { + if (card.getId().equals(cardView.getId())) { + deck.getCards().remove(card); + storeTemporaryCard(card); + break; + } } + break; + } + case "add-specific-card": { + SimpleCardView cardView = (CardView) event.getSource(); + deck.getCards().add(retrieveTemporaryCard(cardView)); + break; } - break; } - case "add-specific-card": { - SimpleCardView cardView = (CardView) event.getSource(); - deck.getCards().add(retrieveTemporaryCard(cardView)); - break; + }else{ + // constructing phase or sideboarding during match -> card goes always to sideboard + switch (event.getEventName()) { + case "double-click": + case "alt-double-click": { + SimpleCardView cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getCards()) { + if (card.getId().equals(cardView.getId())) { + deck.getCards().remove(card); + deck.getSideboard().add(card); + cardSelector.loadSideboard(new ArrayList<>(deck.getSideboard()), getBigCard()); + break; + } + } + hidePopup(); + refreshDeck(); + break; + } + case "remove-specific-card": { + SimpleCardView cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getCards()) { + if (card.getId().equals(cardView.getId())) { + deck.getCards().remove(card); + storeTemporaryCard(card); + break; + } + } + break; + } + case "add-specific-card": { + SimpleCardView cardView = (CardView) event.getSource(); + deck.getCards().add(retrieveTemporaryCard(cardView)); + break; + } } } - } else { - // constructing phase or sideboarding during match -> card goes always to sideboard - switch (event.getEventName()) { - case "double-click": - case "alt-double-click": { - SimpleCardView cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getCards()) { - if (card.getId().equals(cardView.getId())) { - deck.getCards().remove(card); - deck.getSideboard().add(card); - cardSelector.loadSideboard(new ArrayList<>(deck.getSideboard()), getBigCard()); - break; - } - } - hidePopup(); - refreshDeck(); - break; - } - case "remove-specific-card": { - SimpleCardView cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getCards()) { - if (card.getId().equals(cardView.getId())) { - deck.getCards().remove(card); - storeTemporaryCard(card); - break; - } - } - break; - } - case "add-specific-card": { - SimpleCardView cardView = (CardView) event.getSource(); - deck.getCards().add(retrieveTemporaryCard(cardView)); - break; - } - } - } - } - }); + }); this.deckArea.clearSideboardEventListeners(); this.deckArea.addSideboardEventListener( - new Listener() { - @Override - public void event(Event event) { - if (mode.equals(DeckEditorMode.FREE_BUILDING)) { - // normal edit mode - switch (event.getEventName()) { - case "double-click": - // remove card from sideboard (don't add it to deck) - SimpleCardView cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getSideboard()) { - if (card.getId().equals(cardView.getId())) { - deck.getSideboard().remove(card); - break; + (Listener) event -> { + if (mode == DeckEditorMode.FREE_BUILDING) { + // normal edit mode + switch (event.getEventName()) { + case "double-click": + // remove card from sideboard (don't add it to deck) + SimpleCardView cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getSideboard()) { + if (card.getId().equals(cardView.getId())) { + deck.getSideboard().remove(card); + break; + } } - } - hidePopup(); - refreshDeck(); - break; - case "alt-double-click": - // remove card from sideboard - cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getSideboard()) { - if (card.getId().equals(cardView.getId())) { - deck.getSideboard().remove(card); - deck.getCards().add(card); - break; + hidePopup(); + refreshDeck(); + break; + case "alt-double-click": + // remove card from sideboard + cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getSideboard()) { + if (card.getId().equals(cardView.getId())) { + deck.getSideboard().remove(card); + deck.getCards().add(card); + break; + } } + hidePopup(); + refreshDeck(); + break; + case "set-number": { + setCardNumberToCardsList(event, deck.getSideboard()); + break; + } + case "remove-specific-card": { + cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getSideboard()) { + if (card.getId().equals(cardView.getId())) { + deck.getSideboard().remove(card); + storeTemporaryCard(card); + break; + } + } + break; + } + case "add-specific-card": { + cardView = (CardView) event.getSource(); + deck.getSideboard().add(retrieveTemporaryCard(cardView)); + break; } - hidePopup(); - refreshDeck(); - break; - case "set-number": { - setCardNumberToCardsList(event, deck.getSideboard()); - break; } - case "remove-specific-card": { - cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getSideboard()) { - if (card.getId().equals(cardView.getId())) { - deck.getSideboard().remove(card); - storeTemporaryCard(card); - break; + } else { + // construct phase or sideboarding during match + switch (event.getEventName()) { + case "remove-specific-card": { + SimpleCardView cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getSideboard()) { + if (card.getId().equals(cardView.getId())) { + deck.getSideboard().remove(card); + storeTemporaryCard(card); + break; + } } + break; } - break; - } - case "add-specific-card": { - cardView = (CardView) event.getSource(); - deck.getSideboard().add(retrieveTemporaryCard(cardView)); - break; + case "add-specific-card": { + SimpleCardView cardView = (CardView) event.getSource(); + deck.getSideboard().add(retrieveTemporaryCard(cardView)); + break; + } + case "double-click": + case "alt-double-click": + SimpleCardView cardView = (SimpleCardView) event.getSource(); + for (Card card : deck.getSideboard()) { + if (card.getId().equals(cardView.getId())) { + deck.getSideboard().remove(card); + deck.getCards().add(card); + break; + } + } + hidePopup(); + refreshDeck(); + break; } } - } else { - // construct phase or sideboarding during match - switch (event.getEventName()) { - case "remove-specific-card": { - SimpleCardView cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getSideboard()) { - if (card.getId().equals(cardView.getId())) { - deck.getSideboard().remove(card); - storeTemporaryCard(card); - break; - } - } - break; - } - case "add-specific-card": { - SimpleCardView cardView = (CardView) event.getSource(); - deck.getSideboard().add(retrieveTemporaryCard(cardView)); - break; - } - case "double-click": - case "alt-double-click": - SimpleCardView cardView = (SimpleCardView) event.getSource(); - for (Card card : deck.getSideboard()) { - if (card.getId().equals(cardView.getId())) { - deck.getSideboard().remove(card); - deck.getCards().add(card); - break; - } - } - hidePopup(); - refreshDeck(); - break; - } - } - } - }); + }); refreshDeck(); this.setVisible(true); @@ -485,7 +473,7 @@ public class DeckEditorPanel extends javax.swing.JPanel { List toDelete = new ArrayList<>(); for (Card card : cards) { if (card.getName().equals(cardView.getName()) - && card.getCardNumber() == cardView.getCardNumber() + && Objects.equals(card.getCardNumber(), cardView.getCardNumber()) && card.getExpansionSetCode().equals(cardView.getExpansionSetCode())) { cardsFound++; if (cardsFound > numberToSet) { @@ -515,9 +503,8 @@ public class DeckEditorPanel extends javax.swing.JPanel { CardInfo cardInfo = CardRepository.instance.findCard(cardView.getExpansionSetCode(), cardView.getCardNumber()); Card card = null; if (mode == DeckEditorMode.SIDEBOARDING || mode == DeckEditorMode.LIMITED_BUILDING) { - Iterator sideboard = deck.getSideboard().iterator(); - while (sideboard.hasNext()) { - card = (Card) sideboard.next(); + for (Object o : deck.getSideboard()) { + card = (Card) o; if (card.getId().equals(cardView.getId())) { break; } @@ -611,7 +598,7 @@ public class DeckEditorPanel extends javax.swing.JPanel { AudioManager.playOnCountdown1(); } if (timeToSubmit > 0) { - timeToSubmit --; + timeToSubmit--; btnSubmitTimer.setText("Submit (" + timeToSubmit + ")"); btnSubmitTimer.setToolTipText("Submit your deck in " + timeToSubmit + " seconds!"); } @@ -658,105 +645,62 @@ public class DeckEditorPanel extends javax.swing.JPanel { lblDeckName.setText("Deck Name:"); btnSave.setText("Save"); - btnSave.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnSaveActionPerformed(evt); - } - }); + btnSave.addActionListener(evt -> btnSaveActionPerformed(evt)); btnLoad.setText("Load"); - btnLoad.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnLoadActionPerformed(evt); - } - }); + btnLoad.addActionListener(evt -> btnLoadActionPerformed(evt)); btnNew.setText("New"); - btnNew.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnNewActionPerformed(evt); - } - }); + btnNew.addActionListener(evt -> btnNewActionPerformed(evt)); btnExit.setText("Exit"); - btnExit.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnExitActionPerformed(evt); - } - }); + btnExit.addActionListener(evt -> btnExitActionPerformed(evt)); btnImport.setText("Import"); btnImport.setName("btnImport"); // NOI18N - btnImport.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - Object[] options = {"File", "Clipboard", "Append from Clipboard"}; + btnImport.addActionListener(evt -> { + Object[] options = {"File", "Clipboard", "Append from Clipboard"}; - int n = JOptionPane.showOptionDialog(MageFrame.getDesktop(), - "Where would you like to import from?", - "Deck import", - JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, - null, - options, - options[0] - ); + int n = JOptionPane.showOptionDialog(MageFrame.getDesktop(), + "Where would you like to import from?", + "Deck import", + JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, + options, + options[0] + ); - logger.info(n); + logger.info(n); - switch (n) { - case 0: - btnImportActionPerformed(evt); - break; - case 1: - btnImportFromClipboardActionPerformed(evt); - case 2: - btnImportFromClipboardActionWAppendPerformed(evt); - } + switch (n) { + case 0: + btnImportActionPerformed(evt); + break; + case 1: + btnImportFromClipboardActionPerformed(evt); + case 2: + btnImportFromClipboardActionWAppendPerformed(evt); } }); btnSubmit.setText("Submit"); btnSubmitTimer.setToolTipText("Submit your deck now!"); btnSubmit.setName("btnSubmit"); // NOI18N - btnSubmit.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnSubmitActionPerformed(evt); - } - }); + btnSubmit.addActionListener(evt -> btnSubmitActionPerformed(evt)); btnSubmitTimer.setText("Submit (60s)"); btnSubmitTimer.setToolTipText("Submit your deck in one minute!"); btnSubmitTimer.setName("btnSubmitTimer"); - btnSubmitTimer.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnSubmitTimerActionPerformed(evt); - } - }); + btnSubmitTimer.addActionListener(evt -> btnSubmitTimerActionPerformed(evt)); btnAddLand.setText("Add Land"); btnAddLand.setName("btnAddLand"); // NOI18N - btnAddLand.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnAddLandActionPerformed(evt); - } - }); + btnAddLand.addActionListener(evt -> btnAddLandActionPerformed(evt)); btnGenDeck.setText("Generate"); btnGenDeck.setName("btnGenDeck"); - btnGenDeck.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnGenDeckActionPerformed(evt); - } - }); + btnGenDeck.addActionListener(evt -> btnGenDeckActionPerformed(evt)); txtTimeRemaining.setEditable(false); txtTimeRemaining.setForeground(java.awt.Color.red); @@ -767,84 +711,84 @@ public class DeckEditorPanel extends javax.swing.JPanel { jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(jPanel1Layout.createSequentialGroup() - .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) /*.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE))*/ - .addGroup(jPanel1Layout.createSequentialGroup() - .addGap(6, 6, 6) - .addComponent(lblDeckName) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(txtDeckName, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE)) - .addComponent(cardInfoPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addComponent(bigCard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addGroup(jPanel1Layout.createSequentialGroup() - .addContainerGap() - .addComponent(btnSave) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnLoad) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnNew) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnExit)) - .addGroup(jPanel1Layout.createSequentialGroup() - .addContainerGap() - .addComponent(btnImport) - .addContainerGap() - .addComponent(btnGenDeck) - .addContainerGap() - .addComponent(btnAddLand) - .addContainerGap() - .addComponent(btnSubmit) - .addContainerGap() - .addComponent(btnSubmitTimer)) - .addGroup(jPanel1Layout.createSequentialGroup() - .addContainerGap() - .addComponent(txtTimeRemaining)) - ) - .addContainerGap())); + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(6, 6, 6) + .addComponent(lblDeckName) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(txtDeckName, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE)) + .addComponent(cardInfoPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(bigCard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(btnSave) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnLoad) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnNew) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnExit)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(btnImport) + .addContainerGap() + .addComponent(btnGenDeck) + .addContainerGap() + .addComponent(btnAddLand) + .addContainerGap() + .addComponent(btnSubmit) + .addContainerGap() + .addComponent(btnSubmitTimer)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(txtTimeRemaining)) + ) + .addContainerGap())); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(jPanel1Layout.createSequentialGroup() - .addContainerGap() - .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(txtDeckName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addComponent(lblDeckName)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(btnSave) - .addComponent(btnLoad) - .addComponent(btnNew) - .addComponent(btnExit)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(btnImport) - .addComponent(btnGenDeck) - .addComponent(btnAddLand) - .addComponent(btnSubmit) - .addComponent(btnSubmitTimer)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(txtTimeRemaining)) - //.addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, isShowCardInfo ? 30 : 159, Short.MAX_VALUE) - .addComponent(cardInfoPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 104, Short.MAX_VALUE) - .addComponent(bigCard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))); + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(txtDeckName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(lblDeckName)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(btnSave) + .addComponent(btnLoad) + .addComponent(btnNew) + .addComponent(btnExit)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(btnImport) + .addComponent(btnGenDeck) + .addComponent(btnAddLand) + .addComponent(btnSubmit) + .addComponent(btnSubmitTimer)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(txtTimeRemaining)) + //.addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, isShowCardInfo ? 30 : 159, Short.MAX_VALUE) + .addComponent(cardInfoPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 104, Short.MAX_VALUE) + .addComponent(bigCard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE) - .addGap(0, 0, 0) - .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 604, Short.MAX_VALUE))); + .addGroup(layout.createSequentialGroup() + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0) + .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 604, Short.MAX_VALUE))); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE)); + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE)); } /** @@ -1054,17 +998,15 @@ public class DeckEditorPanel extends javax.swing.JPanel { timeToSubmit = 60; this.btnSubmitTimer.setEnabled(false); - ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Callable() { - public Object call() throws Exception { - if (updateDeckTask != null) { - updateDeckTask.cancel(true); - } - - if (SessionHandler.submitDeck(tableId, deck.getDeckCardLists())) { - removeDeckEditor(); - } - return null; + ScheduledFuture scheduledFuture = scheduledExecutorService.schedule((Callable) () -> { + if (updateDeckTask != null) { + updateDeckTask.cancel(true); } + + if (SessionHandler.submitDeck(tableId, deck.getDeckCardLists())) { + removeDeckEditor(); + } + return null; }, 60, TimeUnit.SECONDS); }//GEN-LAST:event_btnSubmitTimerActionPerformed @@ -1081,7 +1023,7 @@ public class DeckEditorPanel extends javax.swing.JPanel { deck = Deck.load(DeckImporterUtil.importDeck(path), true, true); } catch (GameException ex) { JOptionPane.showMessageDialog(MageFrame.getDesktop(), ex.getMessage(), "Error loading generated deck", JOptionPane.ERROR_MESSAGE); - }catch (DeckGeneratorException ex) { + } catch (DeckGeneratorException ex) { JOptionPane.showMessageDialog(MageFrame.getDesktop(), ex.getMessage(), "Generator error", JOptionPane.ERROR_MESSAGE); } finally { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/DeckImportFromClipboardDialog.java b/Mage.Client/src/main/java/mage/client/deckeditor/DeckImportFromClipboardDialog.java index c082e75bd2f..e0704958d29 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/DeckImportFromClipboardDialog.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/DeckImportFromClipboardDialog.java @@ -23,18 +23,8 @@ public class DeckImportFromClipboardDialog extends JDialog { setModal(true); getRootPane().setDefaultButton(buttonOK); - buttonOK.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - onOK(); - } - }); - buttonCancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - onCancel(); - } - }); + buttonOK.addActionListener(e -> onOK()); + buttonCancel.addActionListener(e -> onCancel()); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @@ -45,12 +35,7 @@ public class DeckImportFromClipboardDialog extends JDialog { }); // Close on "ESC" - contentPane.registerKeyboardAction(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - onCancel(); - } - }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } private void onOK() { @@ -94,21 +79,15 @@ public class DeckImportFromClipboardDialog extends JDialog { javax.swing.border.TitledBorder.TOP, new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12), java.awt.Color.BLACK), contentPane.getBorder())); - contentPane.addPropertyChangeListener(new java.beans.PropertyChangeListener() { - @Override - public void propertyChange(java.beans.PropertyChangeEvent e) { - if ("border".equals(e.getPropertyName())) { - throw new RuntimeException(); - } + contentPane.addPropertyChangeListener(e -> { + if ("border".equals(e.getPropertyName())) { + throw new RuntimeException(); } }); - contentPane.addPropertyChangeListener(new java.beans.PropertyChangeListener() { - @Override - public void propertyChange(java.beans.PropertyChangeEvent e) { - if ("border".equals(e.getPropertyName())) { - throw new RuntimeException(); - } + contentPane.addPropertyChangeListener(e -> { + if ("border".equals(e.getPropertyName())) { + throw new RuntimeException(); } }); diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/SortSetting.java b/Mage.Client/src/main/java/mage/client/deckeditor/SortSetting.java index c2f3b21503c..3301cc90397 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/SortSetting.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/SortSetting.java @@ -41,10 +41,10 @@ public abstract class SortSetting { boolean ascending; boolean pilesToggle; - String prefSortBy; - String prefSortIndex; - String prefSortAscending; - String prefPilesToggle; + final String prefSortBy; + final String prefSortIndex; + final String prefSortAscending; + final String prefPilesToggle; public SortSetting(String prefSortBy, String prefSortIndex, String prefSortAscending, String prefPilesToggle) { this.prefSortBy = prefSortBy; diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/CollectionViewerPanel.java b/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/CollectionViewerPanel.java index 86d3848a4bb..3e09760bb3d 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/CollectionViewerPanel.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/CollectionViewerPanel.java @@ -31,8 +31,6 @@ import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; @@ -58,8 +56,8 @@ public final class CollectionViewerPanel extends JPanel { private static final Logger logger = Logger.getLogger(CollectionViewerPanel.class); - protected static String LAYOYT_CONFIG_KEY = "collectionViewerLayoutConfig"; - protected static String FORMAT_CONFIG_KEY = "collectionViewerFormat"; + protected static final String LAYOYT_CONFIG_KEY = "collectionViewerLayoutConfig"; + protected static final String FORMAT_CONFIG_KEY = "collectionViewerFormat"; public CollectionViewerPanel() { initComponents(); @@ -107,26 +105,20 @@ public final class CollectionViewerPanel extends JPanel { small3x3.setForeground(Color.white); boolean selected3x3 = MageFrame.getPreferences().get(LAYOYT_CONFIG_KEY, MageBook.LAYOUT_3x3).equals(MageBook.LAYOUT_3x3); small3x3.setSelected(selected3x3); - small3x3.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - big4x4.setSelected(false); - mageBook.updateSize(MageBook.LAYOUT_3x3); - MageFrame.getPreferences().put(LAYOYT_CONFIG_KEY, MageBook.LAYOUT_3x3); - } + small3x3.addActionListener(e -> { + big4x4.setSelected(false); + mageBook.updateSize(MageBook.LAYOUT_3x3); + MageFrame.getPreferences().put(LAYOYT_CONFIG_KEY, MageBook.LAYOUT_3x3); }); jPanel1.add(small3x3); big4x4 = new JRadioButton("4x4"); big4x4.setForeground(Color.white); big4x4.setSelected(!selected3x3); - big4x4.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - small3x3.setSelected(false); - mageBook.updateSize(MageBook.LAYOUT_4x4); - MageFrame.getPreferences().put(LAYOYT_CONFIG_KEY, MageBook.LAYOUT_4x4); - } + big4x4.addActionListener(e -> { + small3x3.setSelected(false); + mageBook.updateSize(MageBook.LAYOUT_4x4); + MageFrame.getPreferences().put(LAYOYT_CONFIG_KEY, MageBook.LAYOUT_4x4); }); jPanel1.add(big4x4); @@ -143,31 +135,18 @@ public final class CollectionViewerPanel extends JPanel { jPanel1.add(buttonPanel); JButton prev = new JButton("Prev"); - prev.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - mageBook.prev(); - } - }); + prev.addActionListener(e -> mageBook.prev()); buttonPanel.add(prev); JButton next = new JButton("Next"); - next.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - mageBook.next(); - } - }); + next.addActionListener(e -> mageBook.next()); buttonPanel.add(next); - formats.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (mageBook != null) { - String format = (String)formats.getSelectedItem(); - MageFrame.getPreferences().put(CollectionViewerPanel.FORMAT_CONFIG_KEY, format); - mageBook.updateDispayedSets(format); - } + formats.addActionListener(e -> { + if (mageBook != null) { + String format = (String)formats.getSelectedItem(); + MageFrame.getPreferences().put(CollectionViewerPanel.FORMAT_CONFIG_KEY, format); + mageBook.updateDispayedSets(format); } }); @@ -197,12 +176,7 @@ public final class CollectionViewerPanel extends JPanel { ); btnExit.setText("Exit"); - btnExit.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnExitActionPerformed(evt); - } - }); + btnExit.addActionListener(evt -> btnExitActionPerformed(evt)); } diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/MageBook.java b/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/MageBook.java index 4a0f99bbb9a..89554efe22b 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/MageBook.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/MageBook.java @@ -36,7 +36,6 @@ import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.UUID; import javax.imageio.ImageIO; @@ -52,7 +51,6 @@ import mage.client.MageFrame; import mage.client.cards.BigCard; import mage.client.components.HoverButton; import mage.client.plugins.impl.Plugins; -import mage.client.util.Command; import mage.client.util.Config; import mage.client.util.ImageHelper; import mage.client.util.NaturalOrderCardNumberComparator; @@ -110,32 +108,26 @@ public class MageBook extends JComponent { pageLeft = new HoverButton(null, image, image, image, new Rectangle(64, 64)); pageLeft.setBounds(0, 0, 64, 64); pageLeft.setVisible(false); - pageLeft.setObserver(new Command() { - @Override - public void execute() { - currentPage--; - if (currentPage == 0) { - pageLeft.setVisible(false); - } - pageRight.setVisible(true); - AudioManager.playPrevPage(); - showCards(); + pageLeft.setObserver(() -> { + currentPage--; + if (currentPage == 0) { + pageLeft.setVisible(false); } + pageRight.setVisible(true); + AudioManager.playPrevPage(); + showCards(); }); image = ImageHelper.loadImage(RIGHT_PAGE_BUTTON_IMAGE_PATH); pageRight = new HoverButton(null, image, image, image, new Rectangle(64, 64)); pageRight.setBounds(conf.WIDTH - 2 * LEFT_RIGHT_PAGES_WIDTH - 64, 0, 64, 64); pageRight.setVisible(false); - pageRight.setObserver(new Command() { - @Override - public void execute() { - currentPage++; - pageLeft.setVisible(true); - pageRight.setVisible(false); - AudioManager.playNextPage(); - showCards(); - } + pageRight.setObserver(() -> { + currentPage++; + pageLeft.setVisible(true); + pageRight.setVisible(false); + AudioManager.playNextPage(); + showCards(); }); addSetTabs(); @@ -179,21 +171,18 @@ public class MageBook extends JComponent { tab.setBounds(0, y, 39, 120); final String _set = set; final int _index = count; - tab.setObserver(new Command() { - @Override - public void execute() { - if (!currentSet.equals(_set) || currentPage != 0) { - AudioManager.playAnotherTab(); - synchronized (MageBook.this) { - selectedTab = _index; - } - currentPage = 0; - currentSet = _set; - pageLeft.setVisible(false); - pageRight.setVisible(false); - addSetTabs(); - showCards(); + tab.setObserver(() -> { + if (!currentSet.equals(_set) || currentPage != 0) { + AudioManager.playAnotherTab(); + synchronized (MageBook.this) { + selectedTab = _index; } + currentPage = 0; + currentSet = _set; + pageLeft.setVisible(false); + pageRight.setVisible(false); + addSetTabs(); + showCards(); } }); tabs.add(tab); @@ -269,7 +258,7 @@ public class MageBook extends JComponent { CardCriteria criteria = new CardCriteria(); criteria.setCodes(set); List cards = CardRepository.instance.findCards(criteria); - Collections.sort(cards, new NaturalOrderCardNumberComparator()); + cards.sort(new NaturalOrderCardNumberComparator()); int start = page * conf.CARDS_PER_PAGE; int end = page * conf.CARDS_PER_PAGE + conf.CARDS_PER_PAGE; if (end > cards.size()) { @@ -334,12 +323,15 @@ public class MageBook extends JComponent { } public void updateSize(String size) { - if (size.equals(LAYOUT_3x3)) { - this.conf = new _3x3Configuration(); - } else if (size.equals(LAYOUT_4x4)) { - this.conf = new _4x4Configuration(); - } else { - return; + switch (size) { + case LAYOUT_3x3: + this.conf = new _3x3Configuration(); + break; + case LAYOUT_4x4: + this.conf = new _4x4Configuration(); + break; + default: + return; } currentPage = 0; pageLeft.setVisible(false); @@ -412,7 +404,7 @@ public class MageBook extends JComponent { private ImagePanel jPanelCenter; private JPanel jPanelRight; private JLayeredPane jLayeredPane; - private BigCard bigCard; + private final BigCard bigCard; private HoverButton pageLeft; private HoverButton pageRight; @@ -423,7 +415,7 @@ public class MageBook extends JComponent { private static final Logger log = Logger.getLogger(MageBook.class); private Dimension cardDimension; private java.util.List setsToDisplay = new ArrayList<>(); - private java.util.List tabs = new ArrayList<>(); + private final java.util.List tabs = new ArrayList<>(); private int selectedTab; private static final String CENTER_PANEL_IMAGE_PATH = "/book_bg.jpg"; diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/TestMageBook.java b/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/TestMageBook.java index ca384c13074..341fa3b4cd2 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/TestMageBook.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/collection/viewer/TestMageBook.java @@ -1,6 +1,7 @@ package mage.client.deckeditor.collection.viewer; -import javax.swing.JFrame; +import javax.swing.*; + import mage.cards.repository.CardScanner; import mage.client.plugins.impl.Plugins; import org.mage.card.arcane.ManaSymbols; @@ -14,7 +15,7 @@ public class TestMageBook extends JFrame { ManaSymbols.loadImages(); CardScanner.scan(); JFrame frame = new TestMageBook(); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(new MageBook(null)); frame.pack(); frame.setVisible(true); diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/table/TableModel.java b/Mage.Client/src/main/java/mage/client/deckeditor/table/TableModel.java index 3eded527004..987ccff8c9d 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/table/TableModel.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/table/TableModel.java @@ -36,7 +36,6 @@ import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.util.ArrayList; -import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; @@ -76,7 +75,7 @@ public class TableModel extends AbstractTableModel implements ICardGrid { private static final Logger log = Logger.getLogger(TableModel.class); - protected CardEventSource cardEventSource = new CardEventSource(); + protected final CardEventSource cardEventSource = new CardEventSource(); protected BigCard bigCard; protected UUID gameId; private final Map cards = new LinkedHashMap<>(); @@ -437,7 +436,7 @@ public class TableModel extends AbstractTableModel implements ICardGrid { recentAscending = ascending; MageCardComparator sorter = new MageCardComparator(column, ascending); - Collections.sort(view, sorter); + view.sort(sorter); fireTableDataChanged(); diff --git a/Mage.Client/src/main/java/mage/client/dialog/AboutDialog.java b/Mage.Client/src/main/java/mage/client/dialog/AboutDialog.java index 8f6572b5a44..2722fe681a1 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/AboutDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/AboutDialog.java @@ -77,11 +77,7 @@ public class AboutDialog extends MageDialog { setTitle("About XMage"); btnOk.setText("OK"); - btnOk.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnOkActionPerformed(evt); - } - }); + btnOk.addActionListener(this::btnOkActionPerformed); jLabel1.setText("XMage client"); diff --git a/Mage.Client/src/main/java/mage/client/dialog/AddLandDialog.java b/Mage.Client/src/main/java/mage/client/dialog/AddLandDialog.java index 5748b13cd47..1220c618675 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/AddLandDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/AddLandDialog.java @@ -29,7 +29,6 @@ package mage.client.dialog; import java.util.HashSet; import java.util.List; -import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; @@ -73,7 +72,7 @@ public class AddLandDialog extends MageDialog { public void showDialog(Deck deck, DeckEditorMode mode) { this.deck = deck; SortedSet landSetNames = new TreeSet<>(); - if (!mode.equals(DeckEditorMode.FREE_BUILDING)) { + if (mode!=DeckEditorMode.FREE_BUILDING) { // decide from which sets basic lands are taken from for (String setCode : deck.getExpansionSetCodes()) { ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode); @@ -183,44 +182,32 @@ public class AddLandDialog extends MageDialog { lblForest.setText("Forest"); - spnForest.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1))); + spnForest.setModel(new javax.swing.SpinnerNumberModel(0, 0, null, 1)); lblIsland.setText("Island"); - spnIsland.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1))); + spnIsland.setModel(new javax.swing.SpinnerNumberModel(0, 0, null, 1)); lblMountain.setText("Mountain"); - spnMountain.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1))); + spnMountain.setModel(new javax.swing.SpinnerNumberModel(0, 0, null, 1)); lblPains.setText("Plains"); - spnPlains.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1))); + spnPlains.setModel(new javax.swing.SpinnerNumberModel(0, 0, null, 1)); lblSwamp.setText("Swamp"); - spnSwamp.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1))); + spnSwamp.setModel(new javax.swing.SpinnerNumberModel(0, 0, null, 1)); btnAdd.setText("Add"); - btnAdd.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnAddActionPerformed(evt); - } - }); + btnAdd.addActionListener(evt -> btnAddActionPerformed(evt)); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); btnAutoAdd.setText("Suggest"); - btnAutoAdd.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnAutoAddActionPerformed(evt); - } - }); + btnAutoAdd.addActionListener(evt -> btnAutoAddActionPerformed(evt)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); diff --git a/Mage.Client/src/main/java/mage/client/dialog/CardInfoWindowDialog.java b/Mage.Client/src/main/java/mage/client/dialog/CardInfoWindowDialog.java index 92884966252..e4a697854a5 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/CardInfoWindowDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/CardInfoWindowDialog.java @@ -65,13 +65,13 @@ public class CardInfoWindowDialog extends MageDialog { private static final Logger LOGGER = Logger.getLogger(CardInfoWindowDialog.class); - public static enum ShowType { + public enum ShowType { REVEAL, REVEAL_TOP_LIBRARY, LOOKED_AT, EXILE, GRAVEYARD, OTHER - }; + } - private ShowType showType; + private final ShowType showType; private boolean positioned; - private String name; + private final String name; public CardInfoWindowDialog(ShowType showType, String name) { this.name = name; @@ -185,22 +185,19 @@ public class CardInfoWindowDialog extends MageDialog { } private void showAndPositionWindow() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - int width = CardInfoWindowDialog.this.getWidth(); - int height = CardInfoWindowDialog.this.getHeight(); - if (width > 0 && height > 0) { - Point centered = SettingsManager.getInstance().getComponentPosition(width, height); - if (!positioned) { - int xPos = centered.x / 2; - int yPos = centered.y / 2; - CardInfoWindowDialog.this.setLocation(xPos, yPos); - show(); - positioned = true; - } - GuiDisplayUtil.keepComponentInsideFrame(centered.x, centered.y, CardInfoWindowDialog.this); + SwingUtilities.invokeLater(() -> { + int width = CardInfoWindowDialog.this.getWidth(); + int height = CardInfoWindowDialog.this.getHeight(); + if (width > 0 && height > 0) { + Point centered = SettingsManager.getInstance().getComponentPosition(width, height); + if (!positioned) { + int xPos = centered.x / 2; + int yPos = centered.y / 2; + CardInfoWindowDialog.this.setLocation(xPos, yPos); + show(); + positioned = true; } + GuiDisplayUtil.keepComponentInsideFrame(centered.x, centered.y, CardInfoWindowDialog.this); } }); } diff --git a/Mage.Client/src/main/java/mage/client/dialog/ConnectDialog.java b/Mage.Client/src/main/java/mage/client/dialog/ConnectDialog.java index 0c4b5dd9eca..a738721cfe2 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/ConnectDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/ConnectDialog.java @@ -34,7 +34,6 @@ package mage.client.dialog; import java.awt.Cursor; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -78,15 +77,10 @@ public class ConnectDialog extends MageDialog { private static final Logger logger = Logger.getLogger(ConnectDialog.class); private Connection connection; private ConnectTask task; - private RegisterUserDialog registerUserDialog; - private ResetPasswordDialog resetPasswordDialog; + private final RegisterUserDialog registerUserDialog; + private final ResetPasswordDialog resetPasswordDialog; - private final ActionListener connectAction = new ActionListener() { - @Override - public void actionPerformed(ActionEvent evt) { - btnConnectActionPerformed(evt); - } - }; + private final ActionListener connectAction = evt -> btnConnectActionPerformed(evt); /** * Creates new form ConnectDialog @@ -179,11 +173,7 @@ public class ConnectDialog extends MageDialog { btnFind.setText("Find..."); btnFind.setToolTipText("Shows the list of public servers"); btnFind.setName("findServerBtn"); // NOI18N - btnFind.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - findPublicServerActionPerformed(evt); - } - }); + btnFind.addActionListener(evt -> findPublicServerActionPerformed(evt)); lblPort.setLabelFor(txtPort); lblPort.setText("Port:"); @@ -207,56 +197,28 @@ public class ConnectDialog extends MageDialog { chkAutoConnect.setText("Automatically connect to this server next time"); chkAutoConnect.setToolTipText("If active this connect dialog will not be shown if you choose to connect.
\nInstead XMage tries to connect to the last server you were connected to."); - chkAutoConnect.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - chkAutoConnectActionPerformed(evt); - } - }); + chkAutoConnect.addActionListener(evt -> chkAutoConnectActionPerformed(evt)); chkForceUpdateDB.setText("Force update of card database"); chkForceUpdateDB.setToolTipText("If active the comparison of the server cards database to the client database will be enforced.
If not, the comparison will only done if the database version of the client is lower than the version of the server."); - chkForceUpdateDB.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - chkForceUpdateDBActionPerformed(evt); - } - }); + chkForceUpdateDB.addActionListener(evt -> chkForceUpdateDBActionPerformed(evt)); jProxySettingsButton.setText("Proxy Settings..."); - jProxySettingsButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jProxySettingsButtonActionPerformed(evt); - } - }); + jProxySettingsButton.addActionListener(evt -> jProxySettingsButtonActionPerformed(evt)); btnConnect.setText("Connect"); - btnConnect.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnConnectActionPerformed(evt); - } - }); + btnConnect.addActionListener(evt -> btnConnectActionPerformed(evt)); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); btnRegister.setText("Register new user"); btnRegister.setToolTipText("XMage now supports user authentication.
Register your account before you log in."); - btnRegister.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnRegisterActionPerformed(evt); - } - }); + btnRegister.addActionListener(evt -> btnRegisterActionPerformed(evt)); btnForgotPassword.setText("Forgot password"); btnForgotPassword.setToolTipText("You can reset your password if you have registered
your account with an email address."); - btnForgotPassword.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnForgotPasswordActionPerformed(evt); - } - }); + btnForgotPassword.addActionListener(evt -> btnForgotPasswordActionPerformed(evt)); btnFind1.setText("X"); btnFind1.setToolTipText("Connect to xmage.de"); @@ -268,11 +230,7 @@ public class ConnectDialog extends MageDialog { btnFind1.setMinimumSize(new java.awt.Dimension(42, 23)); btnFind1.setName("connectXmageDeBtn"); // NOI18N btnFind1.setPreferredSize(new java.awt.Dimension(23, 23)); - btnFind1.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - connectXmageDe(evt); - } - }); + btnFind1.addActionListener(evt -> connectXmageDe(evt)); btnFind2.setText("L"); btnFind2.setToolTipText("Connect to localhost"); @@ -282,11 +240,7 @@ public class ConnectDialog extends MageDialog { btnFind2.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); btnFind2.setName("connectLocalhostBtn"); // NOI18N btnFind2.setPreferredSize(new java.awt.Dimension(23, 23)); - btnFind2.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - connectLocalhost(evt); - } - }); + btnFind2.addActionListener(evt -> connectLocalhost(evt)); btnFind3.setText("W"); btnFind3.setToolTipText("Connect to woogerworks"); @@ -296,11 +250,7 @@ public class ConnectDialog extends MageDialog { btnFind3.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); btnFind3.setName("connectWoogerworksBtn"); // NOI18N btnFind3.setPreferredSize(new java.awt.Dimension(23, 23)); - btnFind3.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - connectWoogerworks(evt); - } - }); + btnFind3.addActionListener(evt -> connectWoogerworks(evt)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); diff --git a/Mage.Client/src/main/java/mage/client/dialog/ErrorDialog.java b/Mage.Client/src/main/java/mage/client/dialog/ErrorDialog.java index 4412d60732d..c11a8c1a54b 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/ErrorDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/ErrorDialog.java @@ -76,11 +76,7 @@ public class ErrorDialog extends MageDialog { setTitle("Error"); btnOK.setText("OK"); - btnOK.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnOKActionPerformed(evt); - } - }); + btnOK.addActionListener(this::btnOKActionPerformed); lblMessage.setColumns(20); lblMessage.setEditable(false); diff --git a/Mage.Client/src/main/java/mage/client/dialog/FeedbackDialog.java b/Mage.Client/src/main/java/mage/client/dialog/FeedbackDialog.java index 864a4103f58..e42f74b3cb3 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/FeedbackDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/FeedbackDialog.java @@ -28,7 +28,6 @@ package mage.client.dialog; -import mage.client.MageFrame; import mage.client.SessionHandler; import org.apache.log4j.Logger; @@ -43,7 +42,7 @@ public class FeedbackDialog extends javax.swing.JDialog { private static final Logger log = Logger.getLogger(PreferencesDialog.class); - private String[] feedbackTypes = {"", "Bug or \"something doesn't work\"", + private final String[] feedbackTypes = {"", "Bug or \"something doesn't work\"", "Feature or \"I need that function\"", "Thank you or \"Devs, you are so cool!\"", "Question or \"I'm so curious about\""}; @@ -186,18 +185,10 @@ public class FeedbackDialog extends javax.swing.JDialog { jTabbedPane1.addTab("Give feedback", jPanel6); sendButton.setText("Send"); - sendButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - sendButtonActionPerformed(evt); - } - }); + sendButton.addActionListener(evt -> sendButtonActionPerformed(evt)); cancelButton.setText("Cancel"); - cancelButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cancelButtonActionPerformed(evt); - } - }); + cancelButton.addActionListener(evt -> cancelButtonActionPerformed(evt)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); @@ -294,14 +285,12 @@ public class FeedbackDialog extends javax.swing.JDialog { * @param args the command line arguments */ public static void main(String args[]) { - java.awt.EventQueue.invokeLater(new Runnable() { - public void run() { - if (!dialog.isVisible()) { - dialog.setLocation(300, 200); - dialog.setVisible(true); - } else { - dialog.requestFocus(); - } + java.awt.EventQueue.invokeLater(() -> { + if (!dialog.isVisible()) { + dialog.setLocation(300, 200); + dialog.setVisible(true); + } else { + dialog.requestFocus(); } }); } diff --git a/Mage.Client/src/main/java/mage/client/dialog/GameEndDialog.java b/Mage.Client/src/main/java/mage/client/dialog/GameEndDialog.java index b471904258a..17a6122fc90 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/GameEndDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/GameEndDialog.java @@ -61,7 +61,7 @@ import mage.view.PlayerView; */ public class GameEndDialog extends MageDialog { - private final DateFormat df = DateFormat.getDateTimeInstance();; + private final DateFormat df = DateFormat.getDateTimeInstance(); /** Creates new form GameEndDialog @@ -290,11 +290,7 @@ public class GameEndDialog extends MageDialog { tabPane.addTab("Statistics", tabStatistics); btnOk.setText("OK"); - btnOk.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnOkActionPerformed(evt); - } - }); + btnOk.addActionListener(evt -> btnOkActionPerformed(evt)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); diff --git a/Mage.Client/src/main/java/mage/client/dialog/JoinTableDialog.java b/Mage.Client/src/main/java/mage/client/dialog/JoinTableDialog.java index 44ca907a1e3..50d74717f36 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/JoinTableDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/JoinTableDialog.java @@ -85,18 +85,10 @@ public class JoinTableDialog extends MageDialog { setTitle("Join Table"); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); btnOK.setText("OK"); - btnOK.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnOKActionPerformed(evt); - } - }); + btnOK.addActionListener(evt -> btnOKActionPerformed(evt)); lblPassword.setText("Password:"); diff --git a/Mage.Client/src/main/java/mage/client/dialog/MageDialog.java b/Mage.Client/src/main/java/mage/client/dialog/MageDialog.java index 284119777d2..ef6e29b4268 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/MageDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/MageDialog.java @@ -97,12 +97,7 @@ public class MageDialog extends javax.swing.JInternalFrame { stopModal(); } else { try { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - stopModal(); - } - }); + SwingUtilities.invokeAndWait(() -> stopModal()); } catch (InterruptedException ex) { LOGGER.fatal("MageDialog error", ex); } catch (InvocationTargetException ex) { diff --git a/Mage.Client/src/main/java/mage/client/dialog/NewTableDialog.java b/Mage.Client/src/main/java/mage/client/dialog/NewTableDialog.java index 95158581c34..37ef502484a 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/NewTableDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/NewTableDialog.java @@ -32,7 +32,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.ListIterator; import java.util.UUID; import javax.swing.*; @@ -145,11 +144,7 @@ public class NewTableDialog extends MageDialog { lblGameType.setText("Game Type:"); - cbGameType.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbGameTypeActionPerformed(evt); - } - }); + cbGameType.addActionListener(evt -> cbGameTypeActionPerformed(evt)); chkRollbackTurnsAllowed.setText("Allow rollbacks"); chkRollbackTurnsAllowed.setToolTipText("Allow to rollback to the start of previous turns
\nif all players agree.\n"); @@ -163,11 +158,7 @@ public class NewTableDialog extends MageDialog { lblNumPlayers.setLabelFor(spnNumPlayers); lblNumPlayers.setText("Players"); - spnNumPlayers.addChangeListener(new javax.swing.event.ChangeListener() { - public void stateChanged(javax.swing.event.ChangeEvent evt) { - numPlayersChanged(evt); - } - }); + spnNumPlayers.addChangeListener(evt -> numPlayersChanged(evt)); lblRange.setLabelFor(cbRange); lblRange.setText("Range of Influence"); @@ -188,11 +179,7 @@ public class NewTableDialog extends MageDialog { lblNumWins.setText("Wins"); lblNumWins.setToolTipText("How many games has a player to win to win the match."); - spnNumWins.addChangeListener(new javax.swing.event.ChangeListener() { - public void stateChanged(javax.swing.event.ChangeEvent evt) { - spnNumWinsnumPlayersChanged(evt); - } - }); + spnNumWins.addChangeListener(evt -> spnNumWinsnumPlayersChanged(evt)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel1.setText("Player 1 (You)"); @@ -203,18 +190,10 @@ public class NewTableDialog extends MageDialog { pnlOtherPlayers.setLayout(new java.awt.GridLayout(0, 1)); btnOK.setText("OK"); - btnOK.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnOKActionPerformed(evt); - } - }); + btnOK.addActionListener(evt -> btnOKActionPerformed(evt)); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); lblQuitRatio.setText("Allowed quit %"); lblEdhPowerLevel.setText("EDH power level"); @@ -534,12 +513,7 @@ public class NewTableDialog extends MageDialog { playerPanel.init(players.size() + 2, playerType); players.add(playerPanel); playerPanel.addPlayerTypeEventListener( - new Listener() { - @Override - public void event(Event event) { - drawPlayers(); - } - } + (Listener) event -> drawPlayers() ); } @@ -697,12 +671,11 @@ public class NewTableDialog extends MageDialog { PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_SKILL_LEVEL, options.getSkillLevel().toString()); PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_QUIT_RATIO, Integer.toString(options.getQuitRatio())); StringBuilder playerTypesString = new StringBuilder(); - ListIterator iterator = players.listIterator(); - while (iterator.hasNext()) { + for (Object player : players) { if (playerTypesString.length() > 0) { playerTypesString.append(","); } - TablePlayerPanel tpp = (TablePlayerPanel) iterator.next(); + TablePlayerPanel tpp = (TablePlayerPanel) player; playerTypesString.append(tpp.getPlayerType()); } PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_PLAYER_TYPES, playerTypesString.toString()); diff --git a/Mage.Client/src/main/java/mage/client/dialog/NewTournamentDialog.java b/Mage.Client/src/main/java/mage/client/dialog/NewTournamentDialog.java index c07368669ba..709d7369e15 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/NewTournamentDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/NewTournamentDialog.java @@ -65,7 +65,6 @@ import mage.game.draft.DraftOptions; import mage.game.draft.DraftOptions.TimingOption; import mage.game.tournament.LimitedOptions; import mage.game.tournament.TournamentOptions; -import mage.remote.Session; import mage.view.GameTypeView; import mage.view.TableView; import mage.view.TournamentTypeView; @@ -215,11 +214,7 @@ public class NewTournamentDialog extends MageDialog { lblTournamentType.setText("Tournament Type:"); cbTournamentType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); - cbTournamentType.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbTournamentTypeActionPerformed(evt); - } - }); + cbTournamentType.addActionListener(evt -> cbTournamentTypeActionPerformed(evt)); lbDeckType.setText("Deck Type:"); lbDeckType.setFocusable(false); @@ -227,11 +222,7 @@ public class NewTournamentDialog extends MageDialog { lblGameType.setText("Game Type:"); lblGameType.setFocusable(false); - cbGameType.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbGameTypeActionPerformed(evt); - } - }); + cbGameType.addActionListener(evt -> cbGameTypeActionPerformed(evt)); lblFreeMulligans.setText("Free Mulligans:"); @@ -240,30 +231,18 @@ public class NewTournamentDialog extends MageDialog { lblNumWins.setText("Wins:"); spnNumWins.setToolTipText("To win a match a player has to win this number of games."); - spnNumWins.addChangeListener(new javax.swing.event.ChangeListener() { - public void stateChanged(javax.swing.event.ChangeEvent evt) { - spnNumWinsnumPlayersChanged(evt); - } - }); + spnNumWins.addChangeListener(evt -> spnNumWinsnumPlayersChanged(evt)); lblDraftCube.setText("Draft Cube:"); cbDraftCube.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); - cbDraftCube.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbDraftCubeActionPerformed(evt); - } - }); + cbDraftCube.addActionListener(evt -> cbDraftCubeActionPerformed(evt)); lblNumRounds.setText("Number of Swiss Rounds:"); lblNumRounds.setToolTipText("The number of rounds the swiss tournament has in total.
\nThe tournaments ends after that number of rounds or
\nif there are less than two players left in the tournament."); spnNumRounds.setToolTipText("The number of rounds the swiss tournament has in total.
\nThe tournaments ends after that number of rounds or
\nif there are less than two players left in the tournament."); - spnNumRounds.addChangeListener(new javax.swing.event.ChangeListener() { - public void stateChanged(javax.swing.event.ChangeEvent evt) { - spnNumRoundsnumPlayersChanged(evt); - } - }); + spnNumRounds.addChangeListener(evt -> spnNumRoundsnumPlayersChanged(evt)); lblPacks.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N lblPacks.setText("Packs"); @@ -273,28 +252,16 @@ public class NewTournamentDialog extends MageDialog { lblNbrPlayers.setText("Players:"); - spnNumPlayers.addChangeListener(new javax.swing.event.ChangeListener() { - public void stateChanged(javax.swing.event.ChangeEvent evt) { - spnNumPlayersStateChanged(evt); - } - }); + spnNumPlayers.addChangeListener(evt -> spnNumPlayersStateChanged(evt)); lblNbrSeats.setText("Seats:"); - spnNumSeats.addChangeListener(new javax.swing.event.ChangeListener() { - public void stateChanged(javax.swing.event.ChangeEvent evt) { - spnNumSeatsStateChanged(evt); - } - }); + spnNumSeats.addChangeListener(evt -> spnNumSeatsStateChanged(evt)); jLabel6.setText("Timing:"); cbDraftTiming.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); - cbDraftTiming.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbDraftTimingActionPerformed(evt); - } - }); + cbDraftTiming.addActionListener(evt -> cbDraftTimingActionPerformed(evt)); javax.swing.GroupLayout pnlDraftOptionsLayout = new javax.swing.GroupLayout(pnlDraftOptions); pnlDraftOptions.setLayout(pnlDraftOptionsLayout); @@ -348,18 +315,10 @@ public class NewTournamentDialog extends MageDialog { ); btnOk.setText("OK"); - btnOk.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnOkActionPerformed(evt); - } - }); + btnOk.addActionListener(evt -> btnOkActionPerformed(evt)); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); pnlRandomPacks.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlRandomPacks.setToolTipText(""); @@ -887,13 +846,7 @@ public class NewTournamentDialog extends MageDialog { btnSelectRandomPacks.setAlignmentX(Component.LEFT_ALIGNMENT); btnSelectRandomPacks.setText("Select packs to be included in the pool"); btnSelectRandomPacks.setToolTipText(RandomPacksSelectorDialog.randomDraftDescription); - btnSelectRandomPacks.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - showRandomPackSelectorDialog(); - - } - }); + btnSelectRandomPacks.addActionListener(evt -> showRandomPackSelectorDialog()); pnlRandomPacks.add(btnSelectRandomPacks); } this.pack(); @@ -925,12 +878,7 @@ public class NewTournamentDialog extends MageDialog { pack.setModel(new DefaultComboBoxModel(ExpansionRepository.instance.getWithBoostersSortedByReleaseDate())); pnlPacks.add(pack); packs.add(pack); - pack.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - packActionPerformed(evt); - } - }); + pack.addActionListener(evt -> packActionPerformed(evt)); } this.pack(); this.revalidate(); @@ -980,12 +928,9 @@ public class NewTournamentDialog extends MageDialog { this.pnlOtherPlayers.removeAll(); for (TournamentPlayerPanel panel: players) { this.pnlOtherPlayers.add(panel); - panel.getPlayerType().addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - if (!automaticChange) { - playerActionPerformed(evt); - } + panel.getPlayerType().addActionListener(evt -> { + if (!automaticChange) { + playerActionPerformed(evt); } }); } diff --git a/Mage.Client/src/main/java/mage/client/dialog/PickChoiceDialog.java b/Mage.Client/src/main/java/mage/client/dialog/PickChoiceDialog.java index dbf884f23de..6b63e6cfecb 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/PickChoiceDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/PickChoiceDialog.java @@ -134,28 +134,16 @@ public class PickChoiceDialog extends MageDialog { btnAutoSelect.setText("Auto select"); btnAutoSelect.setToolTipText("If you select an effect with \"Auto select\", this effect will be selected the next time automatically first."); - btnAutoSelect.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnAutoSelectActionPerformed(evt); - } - }); + btnAutoSelect.addActionListener(evt -> btnAutoSelectActionPerformed(evt)); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); btnOk.setText("OK"); - btnOk.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnOkActionPerformed(evt); - } - }); + btnOk.addActionListener(evt -> btnOkActionPerformed(evt)); lstChoices.setModel(new javax.swing.AbstractListModel() { - String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; + final String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); diff --git a/Mage.Client/src/main/java/mage/client/dialog/PickNumberDialog.java b/Mage.Client/src/main/java/mage/client/dialog/PickNumberDialog.java index a3f3c85f217..81eeb13f298 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/PickNumberDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/PickNumberDialog.java @@ -90,21 +90,13 @@ public class PickNumberDialog extends MageDialog { jScrollPane1 = new javax.swing.JScrollPane(); lblMessage = new javax.swing.JTextPane(); - spnAmount.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), null, null, Integer.valueOf(1))); + spnAmount.setModel(new javax.swing.SpinnerNumberModel(1, null, null, 1)); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); btnOk.setText("OK"); - btnOk.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnOkActionPerformed(evt); - } - }); + btnOk.addActionListener(evt -> btnOkActionPerformed(evt)); jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); diff --git a/Mage.Client/src/main/java/mage/client/dialog/PickPileDialog.java b/Mage.Client/src/main/java/mage/client/dialog/PickPileDialog.java index 1e9222061fe..cba441aa7dd 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/PickPileDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/PickPileDialog.java @@ -30,8 +30,6 @@ package mage.client.dialog; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.UUID; import javax.swing.JButton; import javax.swing.JLayeredPane; @@ -69,12 +67,7 @@ public class PickPileDialog extends MageDialog { panel.add(pile1, BorderLayout.CENTER); JButton btnChoosePile1 = new JButton("Pile 1"); - btnChoosePile1.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - btnPile1ActionPerformed(e); - } - }); + btnChoosePile1.addActionListener(e -> btnPile1ActionPerformed(e)); panel.add(btnChoosePile1, BorderLayout.NORTH); JPanel panel_1 = new JPanel(); @@ -85,12 +78,7 @@ public class PickPileDialog extends MageDialog { panel_1.add(pile2, BorderLayout.CENTER); JButton btnChoosePile2 = new JButton("Pile 2"); - btnChoosePile2.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - btnPile2ActionPerformed(e); - } - }); + btnChoosePile2.addActionListener(e -> btnPile2ActionPerformed(e)); panel_1.add(btnChoosePile2, BorderLayout.NORTH); } diff --git a/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java b/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java index fc2fb9b7698..da61f41dfb0 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java @@ -320,8 +320,8 @@ public class PreferencesDialog extends javax.swing.JDialog { public static final String OPEN_CONNECTION_TAB = "Open-Connection-Tab"; public static final String OPEN_PHASES_TAB = "Open-Phases-Tab"; - public static String PHASE_ON = "on"; - public static String PHASE_OFF = "off"; + public static final String PHASE_ON = "on"; + public static final String PHASE_OFF = "off"; private static final Map PANELS = new HashMap<>(); @@ -590,11 +590,7 @@ public class PreferencesDialog extends javax.swing.JDialog { showCardName.setToolTipText("Write the card's name on the card to make the card name more recognizable."); showCardName.setActionCommand(""); showCardName.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); - showCardName.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - showCardNameActionPerformed(evt); - } - }); + showCardName.addActionListener(evt -> showCardNameActionPerformed(evt)); tooltipDelayLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); tooltipDelayLabel.setText("Delay in milliseconds for showing the card tooltip text"); @@ -636,71 +632,43 @@ public class PreferencesDialog extends javax.swing.JDialog { nonLandPermanentsInOnePile.setSelected(true); nonLandPermanentsInOnePile.setText("Put non-land permanents in same row as creatures"); nonLandPermanentsInOnePile.setToolTipText("If activated, all non land permanents are shown in one row.
\nFirst creatures than other permanents. If not activated, creatures are
\nshown in a separate row."); - nonLandPermanentsInOnePile.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - nonLandPermanentsInOnePileActionPerformed(evt); - } - }); + nonLandPermanentsInOnePile.addActionListener(evt -> nonLandPermanentsInOnePileActionPerformed(evt)); showPlayerNamesPermanently.setSelected(true); showPlayerNamesPermanently.setText("Show player names on avatar permanently"); showPlayerNamesPermanently.setToolTipText("Instead showing the names only if you hover over the avatar with the mouse, the name is shown all the time."); showPlayerNamesPermanently.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); - showPlayerNamesPermanently.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - showPlayerNamesPermanentlyActionPerformed(evt); - } - }); + showPlayerNamesPermanently.addActionListener(evt -> showPlayerNamesPermanentlyActionPerformed(evt)); showAbilityPickerForced.setSelected(true); showAbilityPickerForced.setText("Show ability picker for abilities or spells without costs"); showAbilityPickerForced.setToolTipText("This prevents you from accidently activating abilities without other costs than tapping or casting spells with 0 mana costs."); showAbilityPickerForced.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); - showAbilityPickerForced.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - showAbilityPickerForcedActionPerformed(evt); - } - }); + showAbilityPickerForced.addActionListener(evt -> showAbilityPickerForcedActionPerformed(evt)); cbAllowRequestToShowHandCards.setSelected(true); cbAllowRequestToShowHandCards.setText("Allow requests from players and spectators to show your hand cards"); cbAllowRequestToShowHandCards.setToolTipText("This is the default setting used for your matches. If activated other players or spectators
\nof your match can send a request so you can allow them to see your hand cards."); cbAllowRequestToShowHandCards.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); - cbAllowRequestToShowHandCards.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbAllowRequestToShowHandCardsActionPerformed(evt); - } - }); + cbAllowRequestToShowHandCards.addActionListener(evt -> cbAllowRequestToShowHandCardsActionPerformed(evt)); cbShowStormCounter.setSelected(true); cbShowStormCounter.setText("Show the number of spell casts during the current turn"); cbShowStormCounter.setToolTipText("Adds a little box left to the short keys line with the number
\nof spells already cast during the current turn (storm counter)."); cbShowStormCounter.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); - cbShowStormCounter.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbShowStormCounterActionPerformed(evt); - } - }); + cbShowStormCounter.addActionListener(evt -> cbShowStormCounterActionPerformed(evt)); cbConfirmEmptyManaPool.setSelected(true); cbConfirmEmptyManaPool.setText("Confirm if you want to pass a phase/step but there is still mana in your mana pool"); cbConfirmEmptyManaPool.setToolTipText("If activated you get a confirm message if you pass priority while stack is empty
\n and you still have mana in your mana pool."); cbConfirmEmptyManaPool.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); - cbConfirmEmptyManaPool.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbConfirmEmptyManaPoolActionPerformed(evt); - } - }); + cbConfirmEmptyManaPool.addActionListener(evt -> cbConfirmEmptyManaPoolActionPerformed(evt)); cbAskMoveToGraveOrder.setSelected(true); cbAskMoveToGraveOrder.setText("Ask player for setting order cards go to graveyard"); cbAskMoveToGraveOrder.setToolTipText("If activated and multiple cards go to the graveyard at the same time
\nthe player is asked to set the order of the cards."); cbAskMoveToGraveOrder.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); - cbAskMoveToGraveOrder.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbAskMoveToGraveOrderActionPerformed(evt); - } - }); + cbAskMoveToGraveOrder.addActionListener(evt -> cbAskMoveToGraveOrderActionPerformed(evt)); org.jdesktop.layout.GroupLayout main_gameLayout = new org.jdesktop.layout.GroupLayout(main_game); main_game.setLayout(main_gameLayout); @@ -744,20 +712,12 @@ public class PreferencesDialog extends javax.swing.JDialog { cbGameLogAutoSave.setSelected(true); cbGameLogAutoSave.setText("Auto save game logs (to \"../Mage.Client/gamelogs/\" directory)"); cbGameLogAutoSave.setToolTipText("The logs of all your games will be saved to the mentioned folder if this option is switched on."); - cbGameLogAutoSave.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbGameLogAutoSaveActionPerformed(evt); - } - }); + cbGameLogAutoSave.addActionListener(evt -> cbGameLogAutoSaveActionPerformed(evt)); cbDraftLogAutoSave.setSelected(true); cbDraftLogAutoSave.setText("Auto save draft logs (to \"../Mage.Client/gamelogs/\" directory)"); cbDraftLogAutoSave.setToolTipText("The logs of all your games will be saved to the mentioned folder if this option is switched on."); - cbDraftLogAutoSave.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbDraftLogAutoSaveActionPerformed(evt); - } - }); + cbDraftLogAutoSave.addActionListener(evt -> cbDraftLogAutoSaveActionPerformed(evt)); org.jdesktop.layout.GroupLayout main_gamelogLayout = new org.jdesktop.layout.GroupLayout(main_gamelog); main_gamelog.setLayout(main_gamelogLayout); @@ -1258,75 +1218,47 @@ public class PreferencesDialog extends javax.swing.JDialog { cbStopAttack.setText("Stop on declare attackers step if you skip steps (F4/F5/F7) and attackers are available"); cbStopAttack.setToolTipText("If you use F4, F5 or F7 to skip steps, you stop on declare attackers step if attackers are available. If this option is not activated, you also skip the declare attackers step with this actions. F9 does always skip the declare attackers step."); cbStopAttack.setActionCommand(""); - cbStopAttack.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbStopAttackActionPerformed(evt); - } - }); + cbStopAttack.addActionListener(evt -> cbStopAttackActionPerformed(evt)); phases_stopSettings.add(cbStopAttack); cbStopBlock.setText("Stop on your declare blockers step also if no blockers available"); cbStopBlock.setToolTipText("Also if you have no blockers to declare, the game stops at the declare blockers step."); cbStopBlock.setActionCommand(""); - cbStopBlock.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbStopBlockActionPerformed(evt); - } - }); + cbStopBlock.addActionListener(evt -> cbStopBlockActionPerformed(evt)); phases_stopSettings.add(cbStopBlock); cbStopOnAllMain.setText("Skip with F7 to next main phase (if not activated skip always to your next main phase)"); cbStopOnAllMain.setToolTipText("If activated F7 skips to next main phases (regardless of the active players)."); cbStopOnAllMain.setActionCommand(""); - cbStopOnAllMain.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbStopOnAllMainActionPerformed(evt); - } - }); + cbStopOnAllMain.addActionListener(evt -> cbStopOnAllMainActionPerformed(evt)); phases_stopSettings.add(cbStopOnAllMain); cbStopOnAllEnd.setText("Skip with F5 to next end step (if not activated only to end steps of opponents)"); cbStopOnAllEnd.setToolTipText("If activated - F5 skips to the next end step (regardless of the current player)"); cbStopOnAllEnd.setActionCommand(""); cbStopOnAllEnd.setPreferredSize(new java.awt.Dimension(300, 25)); - cbStopOnAllEnd.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbStopOnAllEndActionPerformed(evt); - } - }); + cbStopOnAllEnd.addActionListener(evt -> cbStopOnAllEndActionPerformed(evt)); phases_stopSettings.add(cbStopOnAllEnd); cbPassPriorityCast.setText("Pass priority automatically after you have put a spell on the stack"); cbPassPriorityCast.setToolTipText("If activated the system passes priority automatically for you if you have put a spell on the stack."); cbPassPriorityCast.setActionCommand(""); cbPassPriorityCast.setPreferredSize(new java.awt.Dimension(300, 25)); - cbPassPriorityCast.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbPassPriorityCastActionPerformed(evt); - } - }); + cbPassPriorityCast.addActionListener(evt -> cbPassPriorityCastActionPerformed(evt)); phases_stopSettings.add(cbPassPriorityCast); cbPassPriorityActivation.setText("Pass priority automatically after you have put an activated ability on the stack"); cbPassPriorityActivation.setToolTipText("If activated the system passes priority for you automatically after you have put an activated ability on the stack."); cbPassPriorityActivation.setActionCommand(""); cbPassPriorityActivation.setPreferredSize(new java.awt.Dimension(300, 25)); - cbPassPriorityActivation.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbPassPriorityActivationActionPerformed(evt); - } - }); + cbPassPriorityActivation.addActionListener(evt -> cbPassPriorityActivationActionPerformed(evt)); phases_stopSettings.add(cbPassPriorityActivation); cbAutoOrderTrigger.setText("Set order for your triggers automatically if all have the same text"); cbAutoOrderTrigger.setToolTipText("If activated the order to put on the stack your triggers that trigger at the same time
\nis set automatically if all have the same text."); cbAutoOrderTrigger.setActionCommand(""); cbAutoOrderTrigger.setPreferredSize(new java.awt.Dimension(300, 25)); - cbAutoOrderTrigger.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbAutoOrderTriggerActionPerformed(evt); - } - }); + cbAutoOrderTrigger.addActionListener(evt -> cbAutoOrderTriggerActionPerformed(evt)); phases_stopSettings.add(cbAutoOrderTrigger); org.jdesktop.layout.GroupLayout tabPhasesLayout = new org.jdesktop.layout.GroupLayout(tabPhases); @@ -1448,34 +1380,18 @@ public class PreferencesDialog extends javax.swing.JDialog { panelCardImages.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Card images:")); cbUseDefaultImageFolder.setText("Use default location to save images"); - cbUseDefaultImageFolder.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbUseDefaultImageFolderActionPerformed(evt); - } - }); + cbUseDefaultImageFolder.addActionListener(evt -> cbUseDefaultImageFolderActionPerformed(evt)); txtImageFolderPath.setToolTipText("The selected image will be used as background picture. You have to restart MAGE to view a changed background image."); btnBrowseImageLocation.setText("Browse..."); - btnBrowseImageLocation.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnBrowseImageLocationActionPerformed(evt); - } - }); + btnBrowseImageLocation.addActionListener(evt -> btnBrowseImageLocationActionPerformed(evt)); cbCheckForNewImages.setText("Check for new images on startup"); - cbCheckForNewImages.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbCheckForNewImagesActionPerformed(evt); - } - }); + cbCheckForNewImages.addActionListener(evt -> cbCheckForNewImagesActionPerformed(evt)); cbSaveToZipFiles.setText("Store images in zip files"); - cbSaveToZipFiles.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbSaveToZipFilesActionPerformed(evt); - } - }); + cbSaveToZipFiles.addActionListener(evt -> cbSaveToZipFilesActionPerformed(evt)); cbPreferedImageLanguage.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); @@ -1546,51 +1462,23 @@ public class PreferencesDialog extends javax.swing.JDialog { panelBackgroundImages.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Background images setting:")); cbUseDefaultBackground.setText("Use default image"); - cbUseDefaultBackground.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbUseDefaultBackgroundActionPerformed(evt); - } - }); + cbUseDefaultBackground.addActionListener(evt -> cbUseDefaultBackgroundActionPerformed(evt)); - txtBackgroundImagePath.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - txtBackgroundImagePathActionPerformed(evt); - } - }); + txtBackgroundImagePath.addActionListener(evt -> txtBackgroundImagePathActionPerformed(evt)); btnBrowseBackgroundImage.setText("Browse..."); - btnBrowseBackgroundImage.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnBrowseBackgroundImageActionPerformed(evt); - } - }); + btnBrowseBackgroundImage.addActionListener(evt -> btnBrowseBackgroundImageActionPerformed(evt)); - txtBattlefieldImagePath.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - txtBattlefieldImagePathActionPerformed(evt); - } - }); + txtBattlefieldImagePath.addActionListener(evt -> txtBattlefieldImagePathActionPerformed(evt)); btnBrowseBattlefieldImage.setText("Browse..."); - btnBrowseBattlefieldImage.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnBrowseBattlefieldImageActionPerformed(evt); - } - }); + btnBrowseBattlefieldImage.addActionListener(evt -> btnBrowseBattlefieldImageActionPerformed(evt)); cbUseDefaultBattleImage.setText("Use default battlefield image"); - cbUseDefaultBattleImage.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbUseDefaultBattleImageActionPerformed(evt); - } - }); + cbUseDefaultBattleImage.addActionListener(evt -> cbUseDefaultBattleImageActionPerformed(evt)); cbUseRandomBattleImage.setText("Select random battlefield image"); - cbUseRandomBattleImage.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbUseRandomBattleImageActionPerformed(evt); - } - }); + cbUseRandomBattleImage.addActionListener(evt -> cbUseRandomBattleImageActionPerformed(evt)); jLabel14.setText("Background:"); @@ -1650,25 +1538,13 @@ public class PreferencesDialog extends javax.swing.JDialog { jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Card rendering:")); cbCardRenderImageFallback.setText("Fall back to plain image based rendering"); - cbCardRenderImageFallback.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbCardRenderImageFallbackActionPerformed(evt); - } - }); + cbCardRenderImageFallback.addActionListener(evt -> cbCardRenderImageFallbackActionPerformed(evt)); cbCardRenderShowReminderText.setText("Show reminder text in rendered card textboxes"); - cbCardRenderShowReminderText.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbCardRenderShowReminderTextActionPerformed(evt); - } - }); + cbCardRenderShowReminderText.addActionListener(evt -> cbCardRenderShowReminderTextActionPerformed(evt)); cbCardRenderHideSetSymbol.setText("Hide set symbols on cards (more space on the type line for card types)"); - cbCardRenderHideSetSymbol.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbCardRenderHideSetSymbolActionPerformed(evt); - } - }); + cbCardRenderHideSetSymbol.addActionListener(evt -> cbCardRenderHideSetSymbolActionPerformed(evt)); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); @@ -1723,38 +1599,22 @@ public class PreferencesDialog extends javax.swing.JDialog { cbEnableGameSounds.setText("Enable game sounds"); cbEnableGameSounds.setToolTipText("Sounds that will be played for certain actions (e.g. play land, attack, etc.) during the game."); - cbEnableGameSounds.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbEnableGameSoundsActionPerformed(evt); - } - }); + cbEnableGameSounds.addActionListener(evt -> cbEnableGameSoundsActionPerformed(evt)); sounds_clips.add(cbEnableGameSounds); cbEnableDraftSounds.setText("Enable draft sounds"); cbEnableDraftSounds.setToolTipText("Sounds that will be played during drafting for card picking or warining if time runs out."); - cbEnableDraftSounds.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbEnableDraftSoundsActionPerformed(evt); - } - }); + cbEnableDraftSounds.addActionListener(evt -> cbEnableDraftSoundsActionPerformed(evt)); sounds_clips.add(cbEnableDraftSounds); cbEnableSkipButtonsSounds.setText("Enable skip button sounds"); cbEnableSkipButtonsSounds.setToolTipText("Sounds that will be played if a priority skip action (F4/F5/F7/F9) or cancel skip action (F3) is used."); - cbEnableSkipButtonsSounds.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbEnableSkipButtonsSoundsActionPerformed(evt); - } - }); + cbEnableSkipButtonsSounds.addActionListener(evt -> cbEnableSkipButtonsSoundsActionPerformed(evt)); sounds_clips.add(cbEnableSkipButtonsSounds); cbEnableOtherSounds.setText("Enable other sounds"); cbEnableOtherSounds.setToolTipText("Sounds that will be played for actions outside of games (e.g. whisper, player joins your game, player submits a deck ...)."); - cbEnableOtherSounds.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbEnableOtherSoundsActionPerformed(evt); - } - }); + cbEnableOtherSounds.addActionListener(evt -> cbEnableOtherSoundsActionPerformed(evt)); sounds_clips.add(cbEnableOtherSounds); sounds_backgroundMusic.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Music")); @@ -1762,27 +1622,15 @@ public class PreferencesDialog extends javax.swing.JDialog { cbEnableBattlefieldBGM.setText("Play music during match"); cbEnableBattlefieldBGM.setToolTipText("During your matches music will be played from the seleced folder."); cbEnableBattlefieldBGM.setActionCommand("Play automatically during matches"); - cbEnableBattlefieldBGM.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbEnableBattlefieldBGMActionPerformed(evt); - } - }); + cbEnableBattlefieldBGM.addActionListener(evt -> cbEnableBattlefieldBGMActionPerformed(evt)); jLabel16.setText("Playing from folder:"); jLabel16.setToolTipText(""); - txtBattlefieldIBGMPath.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - txtBattlefieldIBGMPathActionPerformed(evt); - } - }); + txtBattlefieldIBGMPath.addActionListener(evt -> txtBattlefieldIBGMPathActionPerformed(evt)); btnBattlefieldBGMBrowse.setText("Browse..."); - btnBattlefieldBGMBrowse.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnBattlefieldBGMBrowseActionPerformed(evt); - } - }); + btnBattlefieldBGMBrowse.addActionListener(evt -> btnBattlefieldBGMBrowseActionPerformed(evt)); org.jdesktop.layout.GroupLayout sounds_backgroundMusicLayout = new org.jdesktop.layout.GroupLayout(sounds_backgroundMusic); sounds_backgroundMusic.setLayout(sounds_backgroundMusicLayout); @@ -2337,11 +2185,7 @@ public class PreferencesDialog extends javax.swing.JDialog { lblProxyType.setText("Proxy:"); - cbProxyType.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbProxyTypeActionPerformed(evt); - } - }); + cbProxyType.addActionListener(evt -> cbProxyTypeActionPerformed(evt)); pnlProxySettings.setBorder(javax.swing.BorderFactory.createEtchedBorder()); @@ -2359,18 +2203,10 @@ public class PreferencesDialog extends javax.swing.JDialog { lblProxyPassword.setText("Password:"); - txtPasswordField.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - txtPasswordFieldActionPerformed(evt); - } - }); + txtPasswordField.addActionListener(evt -> txtPasswordFieldActionPerformed(evt)); rememberPswd.setText("Remember Password"); - rememberPswd.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - rememberPswdActionPerformed(evt); - } - }); + rememberPswd.addActionListener(evt -> rememberPswdActionPerformed(evt)); jLabel11.setFont(new java.awt.Font("Tahoma", 2, 10)); // NOI18N jLabel11.setText("Note: password won't be encrypted!"); @@ -2517,11 +2353,7 @@ public class PreferencesDialog extends javax.swing.JDialog { controlsDescriptionLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP); bttnResetControls.setText("Reset to default"); - bttnResetControls.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - bttnResetControlsActionPerformed(evt); - } - }); + bttnResetControls.addActionListener(evt -> bttnResetControlsActionPerformed(evt)); org.jdesktop.layout.GroupLayout tabControlsLayout = new org.jdesktop.layout.GroupLayout(tabControls); tabControls.setLayout(tabControlsLayout); @@ -2613,22 +2445,14 @@ public class PreferencesDialog extends javax.swing.JDialog { saveButton.setMinimumSize(new java.awt.Dimension(100, 30)); saveButton.setPreferredSize(new java.awt.Dimension(100, 30)); saveButton.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM); - saveButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - saveButtonActionPerformed(evt); - } - }); + saveButton.addActionListener(evt -> saveButtonActionPerformed(evt)); exitButton.setText("Exit"); exitButton.setMaximumSize(new java.awt.Dimension(100, 30)); exitButton.setMinimumSize(new java.awt.Dimension(100, 30)); exitButton.setPreferredSize(new java.awt.Dimension(100, 30)); exitButton.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM); - exitButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - exitButtonActionPerformed(evt); - } - }); + exitButton.addActionListener(evt -> exitButtonActionPerformed(evt)); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); @@ -3097,7 +2921,7 @@ public class PreferencesDialog extends javax.swing.JDialog { }//GEN-LAST:event_cbCardRenderHideSetSymbolActionPerformed private void bttnResetControlsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bttnResetControlsActionPerformed - getKeybindButtons().stream().forEach((bttn) -> { + getKeybindButtons().forEach((bttn) -> { String id = bttn.getKey(); int keyCode = getDefaultControlKey(id); bttn.setKeyCode(keyCode); @@ -3166,43 +2990,40 @@ public class PreferencesDialog extends javax.swing.JDialog { } } final int openedTab = param; - java.awt.EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - if (!dialog.isVisible()) { - Preferences prefs = MageFrame.getPreferences(); + java.awt.EventQueue.invokeLater(() -> { + if (!dialog.isVisible()) { + Preferences prefs = MageFrame.getPreferences(); - // Main & Phases - loadPhases(prefs); + // Main & Phases + loadPhases(prefs); - // Gui Size - loadGuiSize(prefs); + // Gui Size + loadGuiSize(prefs); - // Images - loadImagesSettings(prefs); + // Images + loadImagesSettings(prefs); - // Sounds - loadSoundSettings(prefs); + // Sounds + loadSoundSettings(prefs); - // Connection - loadProxySettings(prefs); + // Connection + loadProxySettings(prefs); - // Controls - loadControlSettings(prefs); + // Controls + loadControlSettings(prefs); - // Selected avatar - loadSelectedAvatar(prefs); + // Selected avatar + loadSelectedAvatar(prefs); - dialog.reset(); - // open specified tab before displaying - openTab(openedTab); + dialog.reset(); + // open specified tab before displaying + openTab(openedTab); - dialog.setLocation(300, 200); + dialog.setLocation(300, 200); - dialog.setVisible(true); - } else { - dialog.requestFocus(); - } + dialog.setVisible(true); + } else { + dialog.requestFocus(); } }); } diff --git a/Mage.Client/src/main/java/mage/client/dialog/QuestionDialog.java b/Mage.Client/src/main/java/mage/client/dialog/QuestionDialog.java index 0bbb3f17c11..b25a77fc9be 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/QuestionDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/QuestionDialog.java @@ -75,18 +75,10 @@ public class QuestionDialog extends MageDialog { lblQuestion.setText("question"); btnNo.setText("No"); - btnNo.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnNoActionPerformed(evt); - } - }); + btnNo.addActionListener(evt -> btnNoActionPerformed(evt)); btnYes.setText("Yes"); - btnYes.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnYesActionPerformed(evt); - } - }); + btnYes.addActionListener(evt -> btnYesActionPerformed(evt)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); diff --git a/Mage.Client/src/main/java/mage/client/dialog/RandomPacksSelectorDialog.java b/Mage.Client/src/main/java/mage/client/dialog/RandomPacksSelectorDialog.java index 22deb50a895..da1b709bcfe 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/RandomPacksSelectorDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/RandomPacksSelectorDialog.java @@ -135,19 +135,11 @@ public class RandomPacksSelectorDialog extends javax.swing.JDialog { btnNone.setText("Select none"); btnNone.setActionCommand("none"); - btnNone.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnNoneActionPerformed(evt); - } - }); + btnNone.addActionListener(evt -> btnNoneActionPerformed(evt)); pnlSelect.add(btnNone); btnAll.setText("Select all"); - btnAll.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnAllActionPerformed(evt); - } - }); + btnAll.addActionListener(evt -> btnAllActionPerformed(evt)); pnlSelect.add(btnAll); pnlApply.setLayout(new javax.swing.BoxLayout(pnlApply, javax.swing.BoxLayout.LINE_AXIS)); @@ -158,11 +150,7 @@ public class RandomPacksSelectorDialog extends javax.swing.JDialog { } else if (isRichManDraft) { btnApply.setToolTipText("At least 1 pack must be selected"); } - btnApply.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnApplyActionPerformed(evt); - } - }); + btnApply.addActionListener(evt -> btnApplyActionPerformed(evt)); pnlApply.add(btnApply); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); diff --git a/Mage.Client/src/main/java/mage/client/dialog/RegisterUserDialog.java b/Mage.Client/src/main/java/mage/client/dialog/RegisterUserDialog.java index 44449e8db10..b226a1090ce 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/RegisterUserDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/RegisterUserDialog.java @@ -14,7 +14,7 @@ import org.apache.log4j.Logger; public class RegisterUserDialog extends MageDialog { private static final Logger logger = Logger.getLogger(ConnectDialog.class); - private ConnectDialog connectDialog; + private final ConnectDialog connectDialog; private Connection connection; private ConnectTask task; @@ -78,25 +78,13 @@ public class RegisterUserDialog extends MageDialog { lblPassword.setLabelFor(txtPassword); lblPassword.setText("Password:"); - txtUserName.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - txtUserNameActionPerformed(evt); - } - }); + txtUserName.addActionListener(evt -> txtUserNameActionPerformed(evt)); btnRegister.setText("Register"); - btnRegister.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnRegisterActionPerformed(evt); - } - }); + btnRegister.addActionListener(evt -> btnRegisterActionPerformed(evt)); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); lblStatus.setToolTipText(""); @@ -112,7 +100,7 @@ public class RegisterUserDialog extends MageDialog { lblEmailReasoning.setFont(new java.awt.Font("Lucida Grande", 0, 10)); // NOI18N lblEmailReasoning.setLabelFor(txtEmail); - lblEmailReasoning.setText("(used for password reset)"); + lblEmailReasoning.setText("(used for password reset and sending initial password)"); lblEmailReasoning.setToolTipText(""); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); diff --git a/Mage.Client/src/main/java/mage/client/dialog/ResetPasswordDialog.java b/Mage.Client/src/main/java/mage/client/dialog/ResetPasswordDialog.java index e1c2cd65a73..0b99f9a2c89 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/ResetPasswordDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/ResetPasswordDialog.java @@ -14,7 +14,7 @@ import org.apache.log4j.Logger; public class ResetPasswordDialog extends MageDialog { private static final Logger logger = Logger.getLogger(ResetPasswordDialog.class); - private ConnectDialog connectDialog; + private final ConnectDialog connectDialog; private Connection connection; private GetAuthTokenTask getAuthTokenTask; private ResetPasswordTask resetPasswordTask; @@ -88,11 +88,7 @@ public class ResetPasswordDialog extends MageDialog { lblPasswordConfirmation.setText("New password:"); btnSubmitNewPassword.setText("Submit a new password"); - btnSubmitNewPassword.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnSubmitNewPasswordActionPerformed(evt); - } - }); + btnSubmitNewPassword.addActionListener(evt -> btnSubmitNewPasswordActionPerformed(evt)); lblPasswordConfirmationReasoning.setFont(new java.awt.Font("Lucida Grande", 0, 10)); // NOI18N lblPasswordConfirmationReasoning.setLabelFor(txtPasswordConfirmation); @@ -157,11 +153,7 @@ public class ResetPasswordDialog extends MageDialog { lblEmail.setText("Email:"); btnGetAuthToken.setText("Email an auth token"); - btnGetAuthToken.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnGetAuthTokenActionPerformed(evt); - } - }); + btnGetAuthToken.addActionListener(evt -> btnGetAuthTokenActionPerformed(evt)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); @@ -196,11 +188,7 @@ public class ResetPasswordDialog extends MageDialog { ); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); lblServer.setLabelFor(txtServer); lblServer.setText("Server:"); diff --git a/Mage.Client/src/main/java/mage/client/dialog/ShowCardsDialog.java b/Mage.Client/src/main/java/mage/client/dialog/ShowCardsDialog.java index b66eaf03202..62deb0011a5 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/ShowCardsDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/ShowCardsDialog.java @@ -129,21 +129,18 @@ public class ShowCardsDialog extends MageDialog { this.repaint(); this.setModal(modal); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!positioned) { - int width = ShowCardsDialog.this.getWidth(); - int height = ShowCardsDialog.this.getHeight(); - if (width > 0 && height > 0) { - Point centered = SettingsManager.getInstance().getComponentPosition(width, height); - ShowCardsDialog.this.setLocation(centered.x, centered.y); - positioned = true; - GuiDisplayUtil.keepComponentInsideScreen(centered.x, centered.y, ShowCardsDialog.this); - } + SwingUtilities.invokeLater(() -> { + if (!positioned) { + int width = ShowCardsDialog.this.getWidth(); + int height = ShowCardsDialog.this.getHeight(); + if (width > 0 && height > 0) { + Point centered = SettingsManager.getInstance().getComponentPosition(width, height); + ShowCardsDialog.this.setLocation(centered.x, centered.y); + positioned = true; + GuiDisplayUtil.keepComponentInsideScreen(centered.x, centered.y, ShowCardsDialog.this); } - ShowCardsDialog.this.setVisible(true); } + ShowCardsDialog.this.setVisible(true); }); } diff --git a/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java b/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java index 90c0d5c4113..23300752f43 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java @@ -206,34 +206,18 @@ public class TableWaitingDialog extends MageDialog { btnMoveUp.setText("Move Up"); btnMoveUp.setEnabled(false); - btnMoveUp.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnMoveUpActionPerformed(evt); - } - }); + btnMoveUp.addActionListener(evt -> btnMoveUpActionPerformed(evt)); btnMoveDown.setText("Move Down"); btnMoveDown.setEnabled(false); - btnMoveDown.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnMoveDownActionPerformed(evt); - } - }); + btnMoveDown.addActionListener(evt -> btnMoveDownActionPerformed(evt)); btnCancel.setText("Cancel"); - btnCancel.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCancelActionPerformed(evt); - } - }); + btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt)); btnStart.setText("Start"); btnStart.setEnabled(false); - btnStart.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnStartActionPerformed(evt); - } - }); + btnStart.addActionListener(evt -> btnStartActionPerformed(evt)); jSplitPane1.setDividerLocation(300); jSplitPane1.setDividerSize(3); diff --git a/Mage.Client/src/main/java/mage/client/dialog/UserRequestDialog.java b/Mage.Client/src/main/java/mage/client/dialog/UserRequestDialog.java index e797ab06c40..bfc3238eb9f 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/UserRequestDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/UserRequestDialog.java @@ -35,7 +35,6 @@ package mage.client.dialog; import java.awt.Dimension; import java.awt.Font; import javax.swing.JComponent; -import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import javax.swing.plaf.basic.BasicInternalFrameUI; import mage.client.MageFrame; import mage.client.util.GUISizeHelper; @@ -76,7 +75,7 @@ public class UserRequestDialog extends MageDialog { btn3.setMinimumSize(new Dimension(50 + 4 * font.getSize(), 2 * font.getSize() + 10)); btn3.setMaximumSize(new Dimension(50 + 4 * font.getSize(), 2 * font.getSize() + 10)); btn3.setPreferredSize(new Dimension(50 + 4 * font.getSize(), 2 * font.getSize() + 10)); - JComponent c = (BasicInternalFrameTitlePane) ((BasicInternalFrameUI) this.getUI()).getNorthPane(); + JComponent c = ((BasicInternalFrameUI) this.getUI()).getNorthPane(); c.setMinimumSize(new Dimension(c.getMinimumSize().width, font.getSize() + 10)); c.setMaximumSize(new Dimension(c.getMaximumSize().width, font.getSize() + 10)); c.setPreferredSize(new Dimension(c.getPreferredSize().width, font.getSize() + 10)); @@ -138,31 +137,19 @@ public class UserRequestDialog extends MageDialog { btn3.setMaximumSize(new java.awt.Dimension(150, 50)); btn3.setMinimumSize(new java.awt.Dimension(75, 25)); btn3.setPreferredSize(new java.awt.Dimension(150, 50)); - btn3.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btn3ActionPerformed(evt); - } - }); + btn3.addActionListener(evt -> btn3ActionPerformed(evt)); btn2.setText("btn2"); btn2.setMaximumSize(new java.awt.Dimension(150, 50)); btn2.setMinimumSize(new java.awt.Dimension(75, 25)); btn2.setPreferredSize(new java.awt.Dimension(150, 50)); - btn2.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btn2ActionPerformed(evt); - } - }); + btn2.addActionListener(evt -> btn2ActionPerformed(evt)); btn1.setText("btn1"); btn1.setMaximumSize(new java.awt.Dimension(150, 50)); btn1.setMinimumSize(new java.awt.Dimension(75, 25)); btn1.setPreferredSize(new java.awt.Dimension(150, 50)); - btn1.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btn1ActionPerformed(evt); - } - }); + btn1.addActionListener(evt -> btn1ActionPerformed(evt)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); diff --git a/Mage.Client/src/main/java/mage/client/draft/DraftPanel.java b/Mage.Client/src/main/java/mage/client/draft/DraftPanel.java index 7abe7279524..a7222635692 100644 --- a/Mage.Client/src/main/java/mage/client/draft/DraftPanel.java +++ b/Mage.Client/src/main/java/mage/client/draft/DraftPanel.java @@ -105,7 +105,7 @@ public class DraftPanel extends javax.swing.JPanel { // all cards picked protected SimpleCardsView pickedCards; // all cards picked - protected SimpleCardsView pickedCardsShown = new SimpleCardsView(); + protected final SimpleCardsView pickedCardsShown = new SimpleCardsView(); // id of card with popup menu protected UUID cardIdPopupMenu; @@ -145,17 +145,14 @@ public class DraftPanel extends javax.swing.JPanel { draftLeftPane.setOpaque(false); countdown = new Timer(1000, - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (--timeout > 0) { - setTimeout(timeout); - } else { - setTimeout(0); - countdown.stop(); + e -> { + if (--timeout > 0) { + setTimeout(timeout); + } else { + setTimeout(0); + countdown.stop(); + } } - } - } ); } @@ -306,18 +303,15 @@ public class DraftPanel extends javax.swing.JPanel { loadCardsToPickedCardsArea(draftPickView.getPicks()); this.draftPicks.clearCardEventListeners(); - this.draftPicks.addCardEventListener(new Listener() { - @Override - public void event(Event event) { - if (event.getEventName().equals("show-popup-menu")) { - if (event.getSource() != null) { - // Popup Menu Card - cardIdPopupMenu = ((SimpleCardView) event.getSource()).getId(); - popupMenuCardPanel.show(event.getComponent(), event.getxPos(), event.getyPos()); - } else { - // Popup Menu area - popupMenuPickedArea.show(event.getComponent(), event.getxPos(), event.getyPos()); - } + this.draftPicks.addCardEventListener((Listener) event -> { + if (event.getEventName().equals("show-popup-menu")) { + if (event.getSource() != null) { + // Popup Menu Card + cardIdPopupMenu = ((SimpleCardView) event.getSource()).getId(); + popupMenuCardPanel.show(event.getComponent(), event.getxPos(), event.getyPos()); + } else { + // Popup Menu area + popupMenuPickedArea.show(event.getComponent(), event.getxPos(), event.getyPos()); } } } @@ -327,25 +321,22 @@ public class DraftPanel extends javax.swing.JPanel { draftBooster.loadBooster(CardsViewUtil.convertSimple(draftPickView.getBooster()), bigCard); this.draftBooster.clearCardEventListeners(); this.draftBooster.addCardEventListener( - new Listener() { - @Override - public void event(Event event) { - if (event.getEventName().equals("pick-a-card")) { - SimpleCardView source = (SimpleCardView) event.getSource(); - DraftPickView view = SessionHandler.sendCardPick(draftId, source.getId(), cardsHidden); - if (view != null) { - loadCardsToPickedCardsArea(view.getPicks()); - draftBooster.loadBooster(EMPTY_VIEW, bigCard); - Plugins.getInstance().getActionCallback().hideOpenComponents(); - setMessage("Waiting for other players"); + (Listener) event -> { + if (event.getEventName().equals("pick-a-card")) { + SimpleCardView source = (SimpleCardView) event.getSource(); + DraftPickView view = SessionHandler.sendCardPick(draftId, source.getId(), cardsHidden); + if (view != null) { + loadCardsToPickedCardsArea(view.getPicks()); + draftBooster.loadBooster(EMPTY_VIEW, bigCard); + Plugins.getInstance().getActionCallback().hideOpenComponents(); + setMessage("Waiting for other players"); + } + } + if (event.getEventName().equals("mark-a-card")) { + SimpleCardView source = (SimpleCardView) event.getSource(); + SessionHandler.sendCardMark(draftId, source.getId()); } } - if (event.getEventName().equals("mark-a-card")) { - SimpleCardView source = (SimpleCardView) event.getSource(); - SessionHandler.sendCardMark(draftId, source.getId()); - } - } - } ); setMessage("Pick a card"); if (!MageFrame.getInstance().isActive()) { @@ -422,12 +413,7 @@ public class DraftPanel extends javax.swing.JPanel { popupMenuPickedArea.add(menuItem); // Confirm (F9) - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - showAgainAllHiddenCards(); - } - }); + menuItem.addActionListener(e -> showAgainAllHiddenCards()); // popupMenuPickedArea.addSeparator(); } @@ -440,12 +426,7 @@ public class DraftPanel extends javax.swing.JPanel { popupMenuCardPanel.add(menuItem); // Hide Card - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - hideThisCard(cardIdPopupMenu); - } - }); + menuItem.addActionListener(e -> hideThisCard(cardIdPopupMenu)); // popupMenuCardPanel.addSeparator(); } @@ -608,11 +589,7 @@ public class DraftPanel extends javax.swing.JPanel { draftLeftPane.setVerifyInputWhenFocusTarget(false); btnQuitTournament.setText("Quit Tournament"); - btnQuitTournament.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnQuitTournamentActionPerformed(evt); - } - }); + btnQuitTournament.addActionListener(evt -> btnQuitTournamentActionPerformed(evt)); lblPack1.setText("Pack 1:"); diff --git a/Mage.Client/src/main/java/mage/client/game/AbilityPicker.java b/Mage.Client/src/main/java/mage/client/game/AbilityPicker.java index 536e63bd1ae..c06d991b4d6 100644 --- a/Mage.Client/src/main/java/mage/client/game/AbilityPicker.java +++ b/Mage.Client/src/main/java/mage/client/game/AbilityPicker.java @@ -88,7 +88,7 @@ public class AbilityPicker extends JPopupMenu implements PopupMenuListener { private class AbilityPickerAction extends AbstractAction { - private UUID id; + private final UUID id; public AbilityPickerAction(UUID id, String choice) { this.id = id; diff --git a/Mage.Client/src/main/java/mage/client/game/BattlefieldPanel.java b/Mage.Client/src/main/java/mage/client/game/BattlefieldPanel.java index 908a25dc4f8..da32bb08cba 100644 --- a/Mage.Client/src/main/java/mage/client/game/BattlefieldPanel.java +++ b/Mage.Client/src/main/java/mage/client/game/BattlefieldPanel.java @@ -299,13 +299,10 @@ public class BattlefieldPanel extends javax.swing.JLayeredPane { } } else if (comp instanceof MagePermanent) { if (((MagePermanent) comp).getOriginal().getId().equals(permanentId)) { - Thread t = new Thread(new Runnable() { - @Override - public void run() { - Plugins.getInstance().onRemoveCard((MagePermanent) comp, count); - comp.setVisible(false); - BattlefieldPanel.this.jPanel.remove(comp); - } + Thread t = new Thread(() -> { + Plugins.getInstance().onRemoveCard((MagePermanent) comp, count); + comp.setVisible(false); + BattlefieldPanel.this.jPanel.remove(comp); }); t.start(); } diff --git a/Mage.Client/src/main/java/mage/client/game/FeedbackPanel.java b/Mage.Client/src/main/java/mage/client/game/FeedbackPanel.java index 45ee23a874c..5c53cabc321 100644 --- a/Mage.Client/src/main/java/mage/client/game/FeedbackPanel.java +++ b/Mage.Client/src/main/java/mage/client/game/FeedbackPanel.java @@ -52,7 +52,6 @@ import static mage.constants.Constants.Option.ORIGINAL_ID; import static mage.constants.Constants.Option.SECOND_MESSAGE; import static mage.constants.Constants.Option.SPECIAL_BUTTON; import mage.constants.PlayerAction; -import mage.remote.Session; import org.apache.log4j.Logger; /** @@ -184,17 +183,14 @@ public class FeedbackPanel extends javax.swing.JPanel { * Close game window by pressing OK button after 8 seconds */ private void endWithTimeout() { - Runnable task = new Runnable() { - @Override - public void run() { - LOGGER.info("Ending game..."); - Component c = MageFrame.getGame(gameId); - while (c != null && !(c instanceof GamePane)) { - c = c.getParent(); - } - if (c != null && ((GamePane) c).isVisible()) { // check if GamePanel still visible - FeedbackPanel.this.btnRight.doClick(); - } + Runnable task = () -> { + LOGGER.info("Ending game..."); + Component c = MageFrame.getGame(gameId); + while (c != null && !(c instanceof GamePane)) { + c = c.getParent(); + } + if (c != null && c.isVisible()) { // check if GamePanel still visible + FeedbackPanel.this.btnRight.doClick(); } }; WORKER.schedule(task, 8, TimeUnit.SECONDS); @@ -255,36 +251,16 @@ public class FeedbackPanel extends javax.swing.JPanel { setBackground(new java.awt.Color(0, 0, 0, 80)); btnRight.setText("Cancel"); - btnRight.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnRightActionPerformed(evt); - } - }); + btnRight.addActionListener(evt -> btnRightActionPerformed(evt)); btnLeft.setText("OK"); - btnLeft.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnLeftActionPerformed(evt); - } - }); + btnLeft.addActionListener(evt -> btnLeftActionPerformed(evt)); btnSpecial.setText("Special"); - btnSpecial.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnSpecialActionPerformed(evt); - } - }); + btnSpecial.addActionListener(evt -> btnSpecialActionPerformed(evt)); btnUndo.setText("Undo"); - btnUndo.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnUndoActionPerformed(evt); - } - }); + btnUndo.addActionListener(evt -> btnUndoActionPerformed(evt)); } diff --git a/Mage.Client/src/main/java/mage/client/game/GamePane.java b/Mage.Client/src/main/java/mage/client/game/GamePane.java index b0c445fdfa1..6e100198521 100644 --- a/Mage.Client/src/main/java/mage/client/game/GamePane.java +++ b/Mage.Client/src/main/java/mage/client/game/GamePane.java @@ -50,12 +50,9 @@ public class GamePane extends MagePane { public GamePane() { this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); initComponents(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - gamePanel.setJLayeredPane(getLayeredPane()); - gamePanel.installComponents(); - } + SwingUtilities.invokeLater(() -> { + gamePanel.setJLayeredPane(getLayeredPane()); + gamePanel.installComponents(); }); } diff --git a/Mage.Client/src/main/java/mage/client/game/GamePanel.java b/Mage.Client/src/main/java/mage/client/game/GamePanel.java index b22e28db511..c4fbcc0bd08 100644 --- a/Mage.Client/src/main/java/mage/client/game/GamePanel.java +++ b/Mage.Client/src/main/java/mage/client/game/GamePanel.java @@ -31,7 +31,6 @@ import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; -import static java.awt.Component.LEFT_ALIGNMENT; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; @@ -53,7 +52,6 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -263,20 +261,12 @@ public final class GamePanel extends javax.swing.JPanel { } }; - resizeTimer = new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent evt) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - resizeTimer.stop(); - setGUISize(); - feedbackPanel.changeGUISize(); + resizeTimer = new Timer(1000, evt -> SwingUtilities.invokeLater(() -> { + resizeTimer.stop(); + setGUISize(); + feedbackPanel.changeGUISize(); - } - }); - } - }); + })); pnlHelperHandButtonsStackArea.addComponentListener(componentAdapterPlayField); initComponents = false; @@ -1124,12 +1114,7 @@ public final class GamePanel extends javax.swing.JPanel { private void removeClosedCardInfoWindows(Map windowMap) { // Remove closed window objects from the maps - for (Iterator> iterator = windowMap.entrySet().iterator(); iterator.hasNext();) { - Map.Entry entry = iterator.next(); - if (entry.getValue().isClosed()) { - iterator.remove(); - } - } + windowMap.entrySet().removeIf(entry -> entry.getValue().isClosed()); } public void ask(String question, GameView gameView, int messageId, Map options) { @@ -1700,20 +1685,10 @@ public final class GamePanel extends javax.swing.JPanel { final BasicSplitPaneUI myUi = (BasicSplitPaneUI) jSplitPane0.getUI(); final BasicSplitPaneDivider divider = myUi.getDivider(); final JButton upArrowButton = (JButton) divider.getComponent(0); - upArrowButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - PreferencesDialog.saveValue(PreferencesDialog.KEY_BIG_CARD_TOGGLED, "up"); - } - }); + upArrowButton.addActionListener(actionEvent -> PreferencesDialog.saveValue(PreferencesDialog.KEY_BIG_CARD_TOGGLED, "up")); final JButton downArrowButton = (JButton) divider.getComponent(1); - downArrowButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - PreferencesDialog.saveValue(PreferencesDialog.KEY_BIG_CARD_TOGGLED, "down"); - } - }); + downArrowButton.addActionListener(actionEvent -> PreferencesDialog.saveValue(PreferencesDialog.KEY_BIG_CARD_TOGGLED, "down")); KeyStroke ksAltEReleased = KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.ALT_MASK, true); this.getInputMap(c).put(ksAltEReleased, "ENLARGE_RELEASE"); @@ -1772,44 +1747,19 @@ public final class GamePanel extends javax.swing.JPanel { stackObjects.setBackgroundColor(new Color(0, 0, 0, 40)); btnStopReplay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/control_stop.png"))); - btnStopReplay.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnStopReplayActionPerformed(evt); - } - }); + btnStopReplay.addActionListener(evt -> btnStopReplayActionPerformed(evt)); btnNextPlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/control_stop_right.png"))); - btnNextPlay.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnNextPlayActionPerformed(evt); - } - }); + btnNextPlay.addActionListener(evt -> btnNextPlayActionPerformed(evt)); btnPlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/control_right.png"))); - btnPlay.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnPlayActionPerformed(evt); - } - }); + btnPlay.addActionListener(evt -> btnPlayActionPerformed(evt)); btnSkipForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/control_double_stop_right.png"))); - btnSkipForward.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnSkipForwardActionPerformed(evt); - } - }); + btnSkipForward.addActionListener(evt -> btnSkipForwardActionPerformed(evt)); btnPreviousPlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/control_stop_left.png"))); - btnPreviousPlay.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnPreviousPlayActionPerformed(evt); - } - }); + btnPreviousPlay.addActionListener(evt -> btnPreviousPlayActionPerformed(evt)); initPopupMenuTriggerOrder(); @@ -2251,21 +2201,18 @@ public final class GamePanel extends javax.swing.JPanel { // Event listener for the ShowCardsDialog private Listener getShowCardsEventListener(final ShowCardsDialog dialog) { - return new Listener() { - @Override - public void event(Event event) { - if (event.getEventName().equals("show-popup-menu")) { - if (event.getComponent() != null && event.getComponent() instanceof CardPanel) { - JPopupMenu menu = ((CardPanel) event.getComponent()).getPopupMenu(); - if (menu != null) { - cardViewPopupMenu = ((CardView) event.getSource()); - menu.show(event.getComponent(), event.getxPos(), event.getyPos()); - } + return (Listener) event -> { + if (event.getEventName().equals("show-popup-menu")) { + if (event.getComponent() != null && event.getComponent() instanceof CardPanel) { + JPopupMenu menu = ((CardPanel) event.getComponent()).getPopupMenu(); + if (menu != null) { + cardViewPopupMenu = ((CardView) event.getSource()); + menu.show(event.getComponent(), event.getxPos(), event.getyPos()); } } - if (event.getEventName().equals("action-consumed")) { - dialog.removeDialog(); - } + } + if (event.getEventName().equals("action-consumed")) { + dialog.removeDialog(); } }; } @@ -2312,12 +2259,7 @@ public final class GamePanel extends javax.swing.JPanel { private void initPopupMenuTriggerOrder() { - ActionListener actionListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - handleTriggerOrderPopupMenuEvent(e); - } - }; + ActionListener actionListener = e -> handleTriggerOrderPopupMenuEvent(e); popupMenuTriggerOrder = new JPopupMenu(); @@ -2366,7 +2308,7 @@ public final class GamePanel extends javax.swing.JPanel { } // Use Cmd on OSX since Ctrl+click is already used to simulate right click - private static int holdPriorityMask = System.getProperty("os.name").contains("Mac OS X") ? InputEvent.META_DOWN_MASK : InputEvent.CTRL_DOWN_MASK; + private static final int holdPriorityMask = System.getProperty("os.name").contains("Mac OS X") ? InputEvent.META_DOWN_MASK : InputEvent.CTRL_DOWN_MASK; public void handleEvent(AWTEvent event) { if (event instanceof InputEvent) { diff --git a/Mage.Client/src/main/java/mage/client/game/HelperPanel.java b/Mage.Client/src/main/java/mage/client/game/HelperPanel.java index 0aae26c5d37..79d3ddb8a6d 100644 --- a/Mage.Client/src/main/java/mage/client/game/HelperPanel.java +++ b/Mage.Client/src/main/java/mage/client/game/HelperPanel.java @@ -48,7 +48,7 @@ import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; -import mage.client.MageFrame; + import mage.client.SessionHandler; import mage.client.components.MageTextArea; import mage.client.game.FeedbackPanel.FeedbackMode; @@ -59,7 +59,6 @@ import static mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_ID_YES; import static mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_RESET_ALL; import static mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_TEXT_NO; import static mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_TEXT_YES; -import mage.remote.Session; /** * Panel with buttons that copy the state of feedback panel. @@ -200,52 +199,30 @@ public class HelperPanel extends JPanel { }; btnLeft.addMouseListener(checkPopupAdapter); - btnLeft.addActionListener(new ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - if (linkLeft != null) { - clickButton(linkLeft); - } + btnLeft.addActionListener(evt -> { + if (linkLeft != null) { + clickButton(linkLeft); } }); btnRight.addMouseListener(checkPopupAdapter); - btnRight.addActionListener(new ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - if (linkRight != null) { - clickButton(linkRight); - } + btnRight.addActionListener(evt -> { + if (linkRight != null) { + clickButton(linkRight); } }); - btnSpecial.addActionListener(new ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - if (linkSpecial != null) { - clickButton(linkSpecial); - } + btnSpecial.addActionListener(evt -> { + if (linkSpecial != null) { + clickButton(linkSpecial); } }); - btnUndo.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - if (linkUndo != null) { - { - Thread worker = new Thread() { - @Override - public void run() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - linkUndo.doClick(); - } - }); - } - }; - worker.start(); - } + btnUndo.addActionListener(evt -> { + if (linkUndo != null) { + { + Thread worker = new Thread(() -> SwingUtilities.invokeLater(() -> linkUndo.doClick())); + worker.start(); } } }); @@ -279,19 +256,11 @@ public class HelperPanel extends JPanel { } private void clickButton(final JButton button) { - Thread worker = new Thread() { - @Override - public void run() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setState("", false, "", false, null); - setSpecial("", false); - button.doClick(); - } - }); - } - }; + Thread worker = new Thread(() -> SwingUtilities.invokeLater(() -> { + setState("", false, "", false, null); + setSpecial("", false); + button.doClick(); + })); worker.start(); } @@ -363,12 +332,7 @@ public class HelperPanel extends JPanel { private void initPopupMenuTriggerOrder() { - ActionListener actionListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - handleAutoAnswerPopupMenuEvent(e); - } - }; + ActionListener actionListener = e -> handleAutoAnswerPopupMenuEvent(e); popupMenuAskYes = new JPopupMenu(); popupMenuAskNo = new JPopupMenu(); diff --git a/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java b/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java index 9c11e67c9c2..8650c9d1758 100644 --- a/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java +++ b/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java @@ -29,7 +29,6 @@ package mage.client.game; import java.awt.Color; import java.awt.Dimension; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; @@ -158,44 +157,41 @@ public class PlayAreaPanel extends javax.swing.JPanel { JMenuItem menuItem; - ActionListener skipListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - switch (e.getActionCommand()) { - case "F2": { - if (gamePanel.getFeedbackPanel() != null) { - gamePanel.getFeedbackPanel().pressOKYesOrDone(); - } - break; - } - case "F3": { - SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_CANCEL_ALL_ACTIONS, gameId, null); - break; - } - case "F4": { - SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_TURN, gameId, null); - break; - } - case "F5": { - SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_TURN_END_STEP, gameId, null); - break; - } - case "F6": { - SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_TURN_SKIP_STACK, gameId, null); - break; - } - case "F7": { - SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_MAIN_PHASE, gameId, null); - break; - } - case "F9": { - SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_MY_NEXT_TURN, gameId, null); - break; - } - case "F11": { - SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_END_STEP_BEFORE_MY_NEXT_TURN, gameId, null); - break; + ActionListener skipListener = e -> { + switch (e.getActionCommand()) { + case "F2": { + if (gamePanel.getFeedbackPanel() != null) { + gamePanel.getFeedbackPanel().pressOKYesOrDone(); } + break; + } + case "F3": { + SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_CANCEL_ALL_ACTIONS, gameId, null); + break; + } + case "F4": { + SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_TURN, gameId, null); + break; + } + case "F5": { + SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_TURN_END_STEP, gameId, null); + break; + } + case "F6": { + SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_TURN_SKIP_STACK, gameId, null); + break; + } + case "F7": { + SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_MAIN_PHASE, gameId, null); + break; + } + case "F9": { + SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_MY_NEXT_TURN, gameId, null); + break; + } + case "F11": { + SessionHandler.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_END_STEP_BEFORE_MY_NEXT_TURN, gameId, null); + break; } } }; @@ -216,13 +212,10 @@ public class PlayAreaPanel extends javax.swing.JPanel { holdPriorityMenuItem.setMnemonic(KeyEvent.VK_P); holdPriorityMenuItem.setToolTipText("Hold priority after casting a spell or activating an ability, instead of automatically passing priority."); popupMenu.add(holdPriorityMenuItem); - holdPriorityMenuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - boolean holdPriority = ((JCheckBoxMenuItem) e.getSource()).getState(); - gamePanel.setMenuStates(manaPoolMenuItem1.getState(), manaPoolMenuItem2.getState(), useFirstManaAbilityItem.getState(), holdPriority); - gamePanel.holdPriority(holdPriority); - } + holdPriorityMenuItem.addActionListener(e -> { + boolean holdPriority = ((JCheckBoxMenuItem) e.getSource()).getState(); + gamePanel.setMenuStates(manaPoolMenuItem1.getState(), manaPoolMenuItem2.getState(), useFirstManaAbilityItem.getState(), holdPriority); + gamePanel.holdPriority(holdPriority); }); JMenu skipMenu = new JMenu("Skip"); @@ -287,14 +280,11 @@ public class PlayAreaPanel extends javax.swing.JPanel { manaPoolMenu.add(manaPoolMenuItem1); // Auto pay mana from mana pool - manaPoolMenuItem1.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - boolean manaPoolAutomatic = ((JCheckBoxMenuItem) e.getSource()).getState(); - PreferencesDialog.saveValue(KEY_GAME_MANA_AUTOPAYMENT, manaPoolAutomatic ? "true" : "false"); - gamePanel.setMenuStates(manaPoolAutomatic, manaPoolMenuItem2.getState(), useFirstManaAbilityItem.getState(), holdPriorityMenuItem.getState()); - SessionHandler.sendPlayerAction(manaPoolAutomatic ? PlayerAction.MANA_AUTO_PAYMENT_ON : PlayerAction.MANA_AUTO_PAYMENT_OFF, gameId, null); - } + manaPoolMenuItem1.addActionListener(e -> { + boolean manaPoolAutomatic = ((JCheckBoxMenuItem) e.getSource()).getState(); + PreferencesDialog.saveValue(KEY_GAME_MANA_AUTOPAYMENT, manaPoolAutomatic ? "true" : "false"); + gamePanel.setMenuStates(manaPoolAutomatic, manaPoolMenuItem2.getState(), useFirstManaAbilityItem.getState(), holdPriorityMenuItem.getState()); + SessionHandler.sendPlayerAction(manaPoolAutomatic ? PlayerAction.MANA_AUTO_PAYMENT_ON : PlayerAction.MANA_AUTO_PAYMENT_OFF, gameId, null); }); manaPoolMenuItem2 = new JCheckBoxMenuItem("No automatic usage for mana already in the pool", true); @@ -305,14 +295,11 @@ public class PlayAreaPanel extends javax.swing.JPanel { manaPoolMenu.add(manaPoolMenuItem2); // Auto pay mana from mana pool - manaPoolMenuItem2.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - boolean manaPoolAutomaticRestricted = ((JCheckBoxMenuItem) e.getSource()).getState(); - PreferencesDialog.saveValue(KEY_GAME_MANA_AUTOPAYMENT_ONLY_ONE, manaPoolAutomaticRestricted ? "true" : "false"); - gamePanel.setMenuStates(manaPoolMenuItem1.getState(), manaPoolAutomaticRestricted, useFirstManaAbilityItem.getState(), holdPriorityMenuItem.getState()); - SessionHandler.sendPlayerAction(manaPoolAutomaticRestricted ? PlayerAction.MANA_AUTO_PAYMENT_RESTRICTED_ON : PlayerAction.MANA_AUTO_PAYMENT_RESTRICTED_OFF, gameId, null); - } + manaPoolMenuItem2.addActionListener(e -> { + boolean manaPoolAutomaticRestricted = ((JCheckBoxMenuItem) e.getSource()).getState(); + PreferencesDialog.saveValue(KEY_GAME_MANA_AUTOPAYMENT_ONLY_ONE, manaPoolAutomaticRestricted ? "true" : "false"); + gamePanel.setMenuStates(manaPoolMenuItem1.getState(), manaPoolAutomaticRestricted, useFirstManaAbilityItem.getState(), holdPriorityMenuItem.getState()); + SessionHandler.sendPlayerAction(manaPoolAutomaticRestricted ? PlayerAction.MANA_AUTO_PAYMENT_RESTRICTED_ON : PlayerAction.MANA_AUTO_PAYMENT_RESTRICTED_OFF, gameId, null); }); useFirstManaAbilityItem = new JCheckBoxMenuItem("Use first mana ability when tapping lands", false); @@ -323,14 +310,11 @@ public class PlayAreaPanel extends javax.swing.JPanel { manaPoolMenu.add(useFirstManaAbilityItem); // Use first mana ability of lands - useFirstManaAbilityItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - boolean useFirstManaAbility = ((JCheckBoxMenuItem) e.getSource()).getState(); - PreferencesDialog.saveValue(KEY_USE_FIRST_MANA_ABILITY, useFirstManaAbility ? "true" : "false"); - gamePanel.setMenuStates(manaPoolMenuItem1.getState(), manaPoolMenuItem2.getState(), useFirstManaAbility, holdPriorityMenuItem.getState()); - SessionHandler.sendPlayerAction(useFirstManaAbility ? PlayerAction.USE_FIRST_MANA_ABILITY_ON : PlayerAction.USE_FIRST_MANA_ABILITY_OFF, gameId, null); - } + useFirstManaAbilityItem.addActionListener(e -> { + boolean useFirstManaAbility = ((JCheckBoxMenuItem) e.getSource()).getState(); + PreferencesDialog.saveValue(KEY_USE_FIRST_MANA_ABILITY, useFirstManaAbility ? "true" : "false"); + gamePanel.setMenuStates(manaPoolMenuItem1.getState(), manaPoolMenuItem2.getState(), useFirstManaAbility, holdPriorityMenuItem.getState()); + SessionHandler.sendPlayerAction(useFirstManaAbility ? PlayerAction.USE_FIRST_MANA_ABILITY_ON : PlayerAction.USE_FIRST_MANA_ABILITY_OFF, gameId, null); }); JMenu automaticConfirmsMenu = new JMenu("Automatic confirms"); @@ -342,36 +326,21 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.setToolTipText("Reset all effects that were added to the list of auto select replacement effects this game."); automaticConfirmsMenu.add(menuItem); // Reset the replacement effcts that were auto selected for the game - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SessionHandler.sendPlayerAction(PlayerAction.RESET_AUTO_SELECT_REPLACEMENT_EFFECTS, gameId, null); - } - }); + menuItem.addActionListener(e -> SessionHandler.sendPlayerAction(PlayerAction.RESET_AUTO_SELECT_REPLACEMENT_EFFECTS, gameId, null)); menuItem = new JMenuItem("Triggered abilities - reset auto stack order"); menuItem.setMnemonic(KeyEvent.VK_T); menuItem.setToolTipText("Deletes all triggered ability order settings you added during the game."); automaticConfirmsMenu.add(menuItem); // Reset the replacement effcts that were auto selected for the game - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SessionHandler.sendPlayerAction(PlayerAction.TRIGGER_AUTO_ORDER_RESET_ALL, gameId, null); - } - }); + menuItem.addActionListener(e -> SessionHandler.sendPlayerAction(PlayerAction.TRIGGER_AUTO_ORDER_RESET_ALL, gameId, null)); menuItem = new JMenuItem("Use requests - reset automatic answers"); menuItem.setMnemonic(KeyEvent.VK_T); menuItem.setToolTipText("Deletes all defined automatic answers for Yes/No usage requests."); automaticConfirmsMenu.add(menuItem); // Reset the replacement effcts that were auto selected for the game - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SessionHandler.sendPlayerAction(PlayerAction.REQUEST_AUTO_ANSWER_RESET_ALL, gameId, null); - } - }); + menuItem.addActionListener(e -> SessionHandler.sendPlayerAction(PlayerAction.REQUEST_AUTO_ANSWER_RESET_ALL, gameId, null)); JMenu handCardsMenu = new JMenu("Cards on hand"); handCardsMenu.setMnemonic(KeyEvent.VK_H); @@ -383,12 +352,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { handCardsMenu.add(menuItem); // Request to see hand cards - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SessionHandler.sendPlayerAction(PlayerAction.REQUEST_PERMISSION_TO_SEE_HAND_CARDS, gameId, playerId); - } - }); + menuItem.addActionListener(e -> SessionHandler.sendPlayerAction(PlayerAction.REQUEST_PERMISSION_TO_SEE_HAND_CARDS, gameId, playerId)); } else { allowViewHandCardsMenuItem = new JCheckBoxMenuItem("Allow requests to show from other users", allowRequestToShowHandCards); allowViewHandCardsMenuItem.setMnemonic(KeyEvent.VK_A); @@ -396,13 +360,10 @@ public class PlayAreaPanel extends javax.swing.JPanel { handCardsMenu.add(allowViewHandCardsMenuItem); // Requests allowed - allowViewHandCardsMenuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - boolean requestsAllowed = ((JCheckBoxMenuItem) e.getSource()).getState(); - PreferencesDialog.setPrefValue(KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, requestsAllowed); - SessionHandler.sendPlayerAction(requestsAllowed ? PlayerAction.PERMISSION_REQUESTS_ALLOWED_ON : PlayerAction.PERMISSION_REQUESTS_ALLOWED_OFF, gameId, null); - } + allowViewHandCardsMenuItem.addActionListener(e -> { + boolean requestsAllowed = ((JCheckBoxMenuItem) e.getSource()).getState(); + PreferencesDialog.setPrefValue(KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, requestsAllowed); + SessionHandler.sendPlayerAction(requestsAllowed ? PlayerAction.PERMISSION_REQUESTS_ALLOWED_ON : PlayerAction.PERMISSION_REQUESTS_ALLOWED_OFF, gameId, null); }); menuItem = new JMenuItem("Revoke all permission(s) to see your hand cards"); @@ -411,21 +372,13 @@ public class PlayAreaPanel extends javax.swing.JPanel { handCardsMenu.add(menuItem); // revoke permissions to see hand cards - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SessionHandler.sendPlayerAction(PlayerAction.REVOKE_PERMISSIONS_TO_SEE_HAND_CARDS, gameId, null); - } - }); + menuItem.addActionListener(e -> SessionHandler.sendPlayerAction(PlayerAction.REVOKE_PERMISSIONS_TO_SEE_HAND_CARDS, gameId, null)); } if (options.rollbackTurnsAllowed) { - ActionListener rollBackActionListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int turnsToRollBack = Integer.parseInt(e.getActionCommand()); - SessionHandler.sendPlayerAction(PlayerAction.ROLLBACK_TURNS, gameId, turnsToRollBack); - } + ActionListener rollBackActionListener = e -> { + int turnsToRollBack = Integer.parseInt(e.getActionCommand()); + SessionHandler.sendPlayerAction(PlayerAction.ROLLBACK_TURNS, gameId, turnsToRollBack); }; JMenu rollbackMainItem = new JMenu("Rollback"); @@ -463,26 +416,23 @@ public class PlayAreaPanel extends javax.swing.JPanel { concedeMenu.setMnemonic(KeyEvent.VK_C); popupMenu.add(concedeMenu); - ActionListener concedeListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - switch (e.getActionCommand()) { - case "Game": { - UserRequestMessage message = new UserRequestMessage("Confirm concede game", "Are you sure you want to concede the game?"); - message.setButton1("No", null); - message.setButton2("Yes", PlayerAction.CLIENT_CONCEDE_GAME); - message.setGameId(gameId); - MageFrame.getInstance().showUserRequestDialog(message); - break; - } - case "Match": { - UserRequestMessage message = new UserRequestMessage("Confirm concede match", "Are you sure you want to concede the complete match?"); - message.setButton1("No", null); - message.setButton2("Yes", PlayerAction.CLIENT_CONCEDE_MATCH); - message.setGameId(gameId); - MageFrame.getInstance().showUserRequestDialog(message); - break; - } + ActionListener concedeListener = e -> { + switch (e.getActionCommand()) { + case "Game": { + UserRequestMessage message = new UserRequestMessage("Confirm concede game", "Are you sure you want to concede the game?"); + message.setButton1("No", null); + message.setButton2("Yes", PlayerAction.CLIENT_CONCEDE_GAME); + message.setGameId(gameId); + MageFrame.getInstance().showUserRequestDialog(message); + break; + } + case "Match": { + UserRequestMessage message = new UserRequestMessage("Confirm concede match", "Are you sure you want to concede the complete match?"); + message.setButton1("No", null); + message.setButton2("Yes", PlayerAction.CLIENT_CONCEDE_MATCH); + message.setGameId(gameId); + MageFrame.getInstance().showUserRequestDialog(message); + break; } } }; @@ -531,27 +481,19 @@ public class PlayAreaPanel extends javax.swing.JPanel { popupMenu.add(menuItem); // Stop watching - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - UserRequestMessage message = new UserRequestMessage("Confirm stop watching game", "Are you sure you want to stop watching the game?"); - message.setButton1("No", null); - message.setButton2("Yes", PlayerAction.CLIENT_STOP_WATCHING); - message.setGameId(gameId); - MageFrame.getInstance().showUserRequestDialog(message); - } + menuItem.addActionListener(e -> { + UserRequestMessage message = new UserRequestMessage("Confirm stop watching game", "Are you sure you want to stop watching the game?"); + message.setButton1("No", null); + message.setButton2("Yes", PlayerAction.CLIENT_STOP_WATCHING); + message.setGameId(gameId); + MageFrame.getInstance().showUserRequestDialog(message); }); menuItem = new JMenuItem("Request permission to see hand cards"); popupMenu.add(menuItem); // Request to see hand cards - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SessionHandler.sendPlayerAction(PlayerAction.REQUEST_PERMISSION_TO_SEE_HAND_CARDS, gameId, playerId); - } - }); + menuItem.addActionListener(e -> SessionHandler.sendPlayerAction(PlayerAction.REQUEST_PERMISSION_TO_SEE_HAND_CARDS, gameId, playerId)); battlefieldPanel.getMainPanel().addMouseListener(new MouseAdapter() { @Override @@ -610,12 +552,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { battlefieldPanel.setTopPanelBattlefield(options.topRow); btnCheat.setText("Cheat"); - btnCheat.addActionListener(new java.awt.event.ActionListener() { - @Override - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCheatActionPerformed(evt); - } - }); + btnCheat.addActionListener(evt -> btnCheatActionPerformed(evt)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); layout.setHorizontalGroup( diff --git a/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java b/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java index 27aedcf959a..8c228cf300d 100644 --- a/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java +++ b/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java @@ -38,8 +38,6 @@ import java.awt.Dimension; import java.awt.Font; import java.awt.Image; import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.LinkedHashSet; @@ -58,7 +56,7 @@ import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.SwingConstants; import javax.swing.border.Border; import javax.swing.border.LineBorder; -import mage.MageException; + import mage.cards.decks.importer.DckDeckImporter; import mage.client.MageFrame; import mage.client.SessionHandler; @@ -68,7 +66,6 @@ import mage.client.components.MageRoundPane; import mage.client.components.ext.dlg.DialogManager; import mage.client.dialog.PreferencesDialog; import mage.client.util.CardsViewUtil; -import mage.client.util.Command; import mage.client.util.ImageHelper; import mage.client.util.gui.BufferedImageBuilder; import mage.client.util.gui.countryBox.CountryUtil; @@ -141,22 +138,16 @@ public class PlayerPanelExt extends javax.swing.JPanel { if (priorityTime > 0) { long delay = 1000L; - timer = new PriorityTimer(priorityTime, delay, new mage.interfaces.Action() { - @Override - public void execute() throws MageException { - // do nothing - } + timer = new PriorityTimer(priorityTime, delay, () -> { + // do nothing }); final PriorityTimer pt = timer; - timer.setTaskOnTick(new mage.interfaces.Action() { - @Override - public void execute() throws MageException { - int priorityTimeValue = pt.getCount(); - String text = getPriorityTimeLeftString(priorityTimeValue); - PlayerPanelExt.this.avatar.setTopText(text); - PlayerPanelExt.this.timerLabel.setText(text); - PlayerPanelExt.this.avatar.repaint(); - } + timer.setTaskOnTick(() -> { + int priorityTimeValue = pt.getCount(); + String text = getPriorityTimeLeftString(priorityTimeValue); + PlayerPanelExt.this.avatar.setTopText(text); + PlayerPanelExt.this.timerLabel.setText(text); + PlayerPanelExt.this.avatar.repaint(); }); timer.init(gameId); } @@ -414,12 +405,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { avatar.setTextAlwaysVisible(true); } avatar.setTextOffsetButtonY(10); - avatar.setObserver(new Command() { - @Override - public void execute() { - SessionHandler.sendPlayerUUID(gameId, playerId); - } - }); + avatar.setObserver(() -> SessionHandler.sendPlayerUUID(gameId, playerId)); // timer area /small layout) timerLabel.setToolTipText("Time left"); @@ -462,12 +448,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { library = new HoverButton(null, resizedLibrary, resizedLibrary, resizedLibrary, r); library.setToolTipText("Library"); library.setOpaque(false); - library.setObserver(new Command() { - @Override - public void execute() { - btnLibraryActionPerformed(null); - } - }); + library.setObserver(() -> btnLibraryActionPerformed(null)); // Grave count and open graveyard button r = new Rectangle(21, 21); @@ -478,12 +459,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { grave = new HoverButton(null, resizedGrave, resizedGrave, resizedGrave, r); grave.setToolTipText("Graveyard"); grave.setOpaque(false); - grave.setObserver(new Command() { - @Override - public void execute() { - btnGraveActionPerformed(null); - } - }); + grave.setObserver(() -> btnGraveActionPerformed(null)); exileLabel = new JLabel(); exileLabel.setToolTipText("Exile"); @@ -493,12 +469,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { exileZone = new HoverButton(null, resized, resized, resized, r); exileZone.setToolTipText("Exile"); exileZone.setOpaque(false); - exileZone.setObserver(new Command() { - @Override - public void execute() { - btnExileZoneActionPerformed(null); - } - }); + exileZone.setObserver(() -> btnExileZoneActionPerformed(null)); exileZone.setBounds(25, 0, 21, 21); // Cheat button @@ -508,12 +479,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { cheat = new JButton(); cheat.setIcon(new ImageIcon(resized)); cheat.setToolTipText("Cheat button"); - cheat.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - btnCheatActionPerformed(e); - } - }); + cheat.addActionListener(e -> btnCheatActionPerformed(e)); zonesPanel = new JPanel(); zonesPanel.setPreferredSize(new Dimension(100, 60)); @@ -527,12 +493,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { commandZone = new HoverButton(null, resized, resized, resized, r); commandZone.setToolTipText("Command Zone (Commander and Emblems)"); commandZone.setOpaque(false); - commandZone.setObserver(new Command() { - @Override - public void execute() { - btnCommandZoneActionPerformed(null); - } - }); + commandZone.setObserver(() -> btnCommandZoneActionPerformed(null)); commandZone.setBounds(5, 0, 21, 21); zonesPanel.add(commandZone); @@ -569,12 +530,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { btnPlayer.setText("Player"); btnPlayer.setVisible(false); btnPlayer.setToolTipText("Player"); - btnPlayer.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SessionHandler.sendPlayerUUID(gameId, playerId); - } - }); + btnPlayer.addActionListener(e -> SessionHandler.sendPlayerUUID(gameId, playerId)); // Add mana symbols JLabel manaCountLabelW = new JLabel(); @@ -587,12 +543,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { btnWhiteMana.setToolTipText("White mana"); btnWhiteMana.setOpaque(false); - btnWhiteMana.setObserver(new Command() { - @Override - public void execute() { - btnManaActionPerformed(ManaType.WHITE); - } - }); + btnWhiteMana.setObserver(() -> btnManaActionPerformed(ManaType.WHITE)); JLabel manaCountLabelU = new JLabel(); manaCountLabelU.setToolTipText("Blue mana"); @@ -603,12 +554,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { HoverButton btnBlueMana = new HoverButton(null, imageManaU, imageManaU, imageManaU, r); btnBlueMana.setToolTipText("Blue mana"); btnBlueMana.setOpaque(false); - btnBlueMana.setObserver(new Command() { - @Override - public void execute() { - btnManaActionPerformed(ManaType.BLUE); - } - }); + btnBlueMana.setObserver(() -> btnManaActionPerformed(ManaType.BLUE)); JLabel manaCountLabelB = new JLabel(); manaCountLabelB.setToolTipText("Black mana"); @@ -619,12 +565,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { HoverButton btnBlackMana = new HoverButton(null, imageManaB, imageManaB, imageManaB, r); btnBlackMana.setToolTipText("Black mana"); btnBlackMana.setOpaque(false); - btnBlackMana.setObserver(new Command() { - @Override - public void execute() { - btnManaActionPerformed(ManaType.BLACK); - } - }); + btnBlackMana.setObserver(() -> btnManaActionPerformed(ManaType.BLACK)); JLabel manaCountLabelR = new JLabel(); manaCountLabelR.setToolTipText("Red mana"); @@ -635,12 +576,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { HoverButton btnRedMana = new HoverButton(null, imageManaR, imageManaR, imageManaR, r); btnRedMana.setToolTipText("Red mana"); btnRedMana.setOpaque(false); - btnRedMana.setObserver(new Command() { - @Override - public void execute() { - btnManaActionPerformed(ManaType.RED); - } - }); + btnRedMana.setObserver(() -> btnManaActionPerformed(ManaType.RED)); JLabel manaCountLabelG = new JLabel(); manaCountLabelG.setToolTipText("Green mana"); @@ -651,12 +587,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { HoverButton btnGreenMana = new HoverButton(null, imageManaG, imageManaG, imageManaG, r); btnGreenMana.setToolTipText("Green mana"); btnGreenMana.setOpaque(false); - btnGreenMana.setObserver(new Command() { - @Override - public void execute() { - btnManaActionPerformed(ManaType.GREEN); - } - }); + btnGreenMana.setObserver(() -> btnManaActionPerformed(ManaType.GREEN)); JLabel manaCountLabelX = new JLabel(); manaCountLabelX.setToolTipText("Colorless mana"); @@ -667,12 +598,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { HoverButton btnColorlessMana = new HoverButton(null, imageManaX, imageManaX, imageManaX, r); btnColorlessMana.setToolTipText("Colorless mana"); btnColorlessMana.setOpaque(false); - btnColorlessMana.setObserver(new Command() { - @Override - public void execute() { - btnManaActionPerformed(ManaType.COLORLESS); - } - }); + btnColorlessMana.setObserver(() -> btnManaActionPerformed(ManaType.COLORLESS)); GroupLayout gl_panelBackground = new GroupLayout(panelBackground); gl_panelBackground.setHorizontalGroup( diff --git a/Mage.Client/src/main/java/mage/client/plugins/adapters/MageActionCallback.java b/Mage.Client/src/main/java/mage/client/plugins/adapters/MageActionCallback.java index f9eeb6d5cd2..31ed09a63c3 100644 --- a/Mage.Client/src/main/java/mage/client/plugins/adapters/MageActionCallback.java +++ b/Mage.Client/src/main/java/mage/client/plugins/adapters/MageActionCallback.java @@ -7,8 +7,6 @@ import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; @@ -24,6 +22,7 @@ import javax.swing.JPopupMenu; import javax.swing.Popup; import javax.swing.PopupFactory; import javax.swing.SwingUtilities; + import mage.cards.MageCard; import mage.cards.action.ActionCallback; import mage.cards.action.TransferData; @@ -80,6 +79,7 @@ public class MageActionCallback implements ActionCallback { CLOSED, NORMAL, ROTATED } + private Date enlargeredViewOpened; private volatile EnlargedWindowState enlargedWindowState = EnlargedWindowState.CLOSED; //private volatile boolean enlargedImageWindowOpen = false; @@ -158,7 +158,7 @@ public class MageActionCallback implements ActionCallback { || !tooltipCard.equals(data.card) || SessionHandler.getSession() == null || !popupTextWindowOpen - || !enlargedWindowState.equals(EnlargedWindowState.CLOSED)) { + || enlargedWindowState != EnlargedWindowState.CLOSED) { return; } @@ -177,25 +177,22 @@ public class MageActionCallback implements ActionCallback { public void showPopup(final Component popupContainer, final Component infoPane) throws InterruptedException { final Component c = MageFrame.getUI().getComponent(MageComponents.DESKTOP_PANE); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!popupTextWindowOpen - || !enlargedWindowState.equals(EnlargedWindowState.CLOSED)) { - return; - } - if (data.locationOnScreen == null) { - data.locationOnScreen = data.component.getLocationOnScreen(); - } + SwingUtilities.invokeLater(() -> { + if (!popupTextWindowOpen + || enlargedWindowState != EnlargedWindowState.CLOSED) { + return; + } + if (data.locationOnScreen == null) { + data.locationOnScreen = data.component.getLocationOnScreen(); + } - Point location = new Point((int) data.locationOnScreen.getX() + data.popupOffsetX - 40, (int) data.locationOnScreen.getY() + data.popupOffsetY - 40); - location = GuiDisplayUtil.keepComponentInsideParent(location, parentPoint, infoPane, parentComponent); - location.translate(-parentPoint.x, -parentPoint.y); - popupContainer.setLocation(location); - popupContainer.setVisible(true); - c.repaint(); - } - } + Point location = new Point((int) data.locationOnScreen.getX() + data.popupOffsetX - 40, (int) data.locationOnScreen.getY() + data.popupOffsetY - 40); + location = GuiDisplayUtil.keepComponentInsideParent(location, parentPoint, infoPane, parentComponent); + location.translate(-parentPoint.x, -parentPoint.y); + popupContainer.setLocation(location); + popupContainer.setVisible(true); + c.repaint(); + } ); } }); @@ -257,7 +254,7 @@ public class MageActionCallback implements ActionCallback { if (this.startedDragging && prevCardPanel != null && card != null) { for (Component component : card.getCardArea().getComponents()) { if (component instanceof CardPanel) { - if (cardPanels.contains((CardPanel) component)) { + if (cardPanels.contains(component)) { component.setLocation(component.getLocation().x, component.getLocation().y - GO_DOWN_ON_DRAG_Y_OFFSET); } } @@ -331,7 +328,7 @@ public class MageActionCallback implements ActionCallback { for (Component component : container.getComponents()) { if (component instanceof CardPanel) { if (!component.equals(card)) { - if (!cardPanels.contains((CardPanel) component)) { + if (!cardPanels.contains(component)) { component.setLocation(component.getLocation().x, component.getLocation().y + GO_DOWN_ON_DRAG_Y_OFFSET); } cardPanels.add((CardPanel) component); @@ -347,12 +344,7 @@ public class MageActionCallback implements ActionCallback { private void sortLayout(List cards, CardPanel source, boolean includeSource) { source.getLocation().x -= COMPARE_GAP_X; // this creates nice effect - Collections.sort(cards, new Comparator() { - @Override - public int compare(CardPanel cp1, CardPanel cp2) { - return Integer.valueOf(cp1.getLocation().x).compareTo(cp2.getLocation().x); - } - }); + cards.sort((cp1, cp2) -> Integer.valueOf(cp1.getLocation().x).compareTo(cp2.getLocation().x)); int dx = 0; boolean createdGapForSource = false; @@ -412,7 +404,7 @@ public class MageActionCallback implements ActionCallback { } else { popupTextWindowOpen = true; } - if (!enlargedWindowState.equals(EnlargedWindowState.CLOSED)) { + if (enlargedWindowState != EnlargedWindowState.CLOSED) { cancelTimeout(); displayEnlargedCard(mageCard.getOriginal(), transferData); } @@ -427,7 +419,6 @@ public class MageActionCallback implements ActionCallback { /** * Hides the text popup window - * */ public void hideTooltipPopup() { this.tooltipCard = null; @@ -471,13 +462,13 @@ public class MageActionCallback implements ActionCallback { @Override public void mouseWheelMoved(MouseWheelEvent e, TransferData transferData) { int notches = e.getWheelRotation(); - if (!enlargedWindowState.equals(EnlargedWindowState.CLOSED)) { + if (enlargedWindowState != EnlargedWindowState.CLOSED) { // same move direction will be ignored, opposite direction closes the enlarged window if (new Date().getTime() - enlargeredViewOpened.getTime() > 1000) { // if the opening is back more than 1 seconds close anyway hideEnlargedCard(); handleOverNewView(transferData); - } else if (enlargeMode.equals(EnlargeMode.NORMAL)) { + } else if (enlargeMode == EnlargeMode.NORMAL) { if (notches > 0) { hideEnlargedCard(); handleOverNewView(transferData); @@ -501,10 +492,10 @@ public class MageActionCallback implements ActionCallback { * Show the big card image on mouse position while hovering over a card * * @param showAlternative defines if the original image (if it's a copied - * card) or the opposite side of a transformable card will be shown + * card) or the opposite side of a transformable card will be shown */ public void enlargeCard(EnlargeMode showAlternative) { - if (enlargedWindowState.equals(EnlargedWindowState.CLOSED)) { + if (enlargedWindowState == EnlargedWindowState.CLOSED) { this.enlargeMode = showAlternative; CardView cardView = null; if (popupData != null) { @@ -525,7 +516,7 @@ public class MageActionCallback implements ActionCallback { } public void hideEnlargedCard() { - if (!enlargedWindowState.equals(EnlargedWindowState.CLOSED)) { + if (enlargedWindowState != EnlargedWindowState.CLOSED) { enlargedWindowState = EnlargedWindowState.CLOSED; try { Component cardPreviewContainer = MageFrame.getUI().getComponent(MageComponents.CARD_PREVIEW_CONTAINER); @@ -540,78 +531,75 @@ public class MageActionCallback implements ActionCallback { } private void displayEnlargedCard(final CardView cardView, final TransferData transferData) { - ThreadUtils.threadPool3.submit(new Runnable() { - @Override - public void run() { - if (cardView == null) { + ThreadUtils.threadPool3.submit(() -> { + if (cardView == null) { + return; + } + try { + if (enlargedWindowState == EnlargedWindowState.CLOSED) { return; } - try { - if (enlargedWindowState.equals(EnlargedWindowState.CLOSED)) { - return; + + MageComponents mageComponentCardPreviewContainer; + MageComponents mageComponentCardPreviewPane; + if (cardView.isToRotate()) { + if (enlargedWindowState == EnlargedWindowState.NORMAL) { + hideEnlargedCard(); + enlargedWindowState = EnlargedWindowState.ROTATED; } - - MageComponents mageComponentCardPreviewContainer; - MageComponents mageComponentCardPreviewPane; - if (cardView.isToRotate()) { - if (enlargedWindowState.equals(EnlargedWindowState.NORMAL)) { - hideEnlargedCard(); - enlargedWindowState = EnlargedWindowState.ROTATED; - } - mageComponentCardPreviewContainer = MageComponents.CARD_PREVIEW_CONTAINER_ROTATED; - mageComponentCardPreviewPane = MageComponents.CARD_PREVIEW_PANE_ROTATED; - } else { - if (enlargedWindowState.equals(EnlargedWindowState.ROTATED)) { - hideEnlargedCard(); - enlargedWindowState = EnlargedWindowState.NORMAL; - } - mageComponentCardPreviewContainer = MageComponents.CARD_PREVIEW_CONTAINER; - mageComponentCardPreviewPane = MageComponents.CARD_PREVIEW_PANE; + mageComponentCardPreviewContainer = MageComponents.CARD_PREVIEW_CONTAINER_ROTATED; + mageComponentCardPreviewPane = MageComponents.CARD_PREVIEW_PANE_ROTATED; + } else { + if (enlargedWindowState == EnlargedWindowState.ROTATED) { + hideEnlargedCard(); + enlargedWindowState = EnlargedWindowState.NORMAL; } - final Component popupContainer = MageFrame.getUI().getComponent(mageComponentCardPreviewContainer); - Component cardPreviewPane = MageFrame.getUI().getComponent(mageComponentCardPreviewPane); - Component parentComponent = SwingUtilities.getRoot(transferData.component); - if (cardPreviewPane != null && parentComponent != null) { - Point parentPoint = parentComponent.getLocationOnScreen(); - transferData.locationOnScreen = transferData.component.getLocationOnScreen(); - Point location = new Point((int) transferData.locationOnScreen.getX() + transferData.popupOffsetX - 40, (int) transferData.locationOnScreen.getY() + transferData.popupOffsetY - 40); - location = GuiDisplayUtil.keepComponentInsideParent(location, parentPoint, cardPreviewPane, parentComponent); - location.translate(-parentPoint.x, -parentPoint.y); - popupContainer.setLocation(location); - popupContainer.setVisible(true); - - MageCard mageCard = (MageCard) transferData.component; - Image image = null; - switch (enlargeMode) { - case COPY: - if (cardView instanceof PermanentView) { - image = ImageCache.getImageOriginal(((PermanentView) cardView).getOriginal()); - } - break; - case ALTERNATE: - if (cardView.getAlternateName() != null) { - if (cardView instanceof PermanentView && !cardView.isFlipCard() && !cardView.canTransform() && ((PermanentView) cardView).isCopy()) { - image = ImageCache.getImageOriginal(((PermanentView) cardView).getOriginal()); - } else { - image = ImageCache.getImageOriginalAlternateName(cardView); - } - } - break; - } - if (image == null) { - image = mageCard.getImage(); - } - // shows the card in the popup Container - BigCard bigCard = (BigCard) cardPreviewPane; - displayCardInfo(mageCard, image, bigCard); - - } else { - LOGGER.warn("No Card preview Pane in Mage Frame defined. Card: " + cardView.getName()); - } - - } catch (Exception e) { - LOGGER.warn("Problem dring display of enlarged card", e); + mageComponentCardPreviewContainer = MageComponents.CARD_PREVIEW_CONTAINER; + mageComponentCardPreviewPane = MageComponents.CARD_PREVIEW_PANE; } + final Component popupContainer = MageFrame.getUI().getComponent(mageComponentCardPreviewContainer); + Component cardPreviewPane = MageFrame.getUI().getComponent(mageComponentCardPreviewPane); + Component parentComponent = SwingUtilities.getRoot(transferData.component); + if (cardPreviewPane != null && parentComponent != null) { + Point parentPoint = parentComponent.getLocationOnScreen(); + transferData.locationOnScreen = transferData.component.getLocationOnScreen(); + Point location = new Point((int) transferData.locationOnScreen.getX() + transferData.popupOffsetX - 40, (int) transferData.locationOnScreen.getY() + transferData.popupOffsetY - 40); + location = GuiDisplayUtil.keepComponentInsideParent(location, parentPoint, cardPreviewPane, parentComponent); + location.translate(-parentPoint.x, -parentPoint.y); + popupContainer.setLocation(location); + popupContainer.setVisible(true); + + MageCard mageCard = (MageCard) transferData.component; + Image image = null; + switch (enlargeMode) { + case COPY: + if (cardView instanceof PermanentView) { + image = ImageCache.getImageOriginal(((PermanentView) cardView).getOriginal()); + } + break; + case ALTERNATE: + if (cardView.getAlternateName() != null) { + if (cardView instanceof PermanentView && !cardView.isFlipCard() && !cardView.canTransform() && ((PermanentView) cardView).isCopy()) { + image = ImageCache.getImageOriginal(((PermanentView) cardView).getOriginal()); + } else { + image = ImageCache.getImageOriginalAlternateName(cardView); + } + } + break; + } + if (image == null) { + image = mageCard.getImage(); + } + // shows the card in the popup Container + BigCard bigCard = (BigCard) cardPreviewPane; + displayCardInfo(mageCard, image, bigCard); + + } else { + LOGGER.warn("No Card preview Pane in Mage Frame defined. Card: " + cardView.getName()); + } + + } catch (Exception e) { + LOGGER.warn("Problem dring display of enlarged card", e); } }); } @@ -621,7 +609,7 @@ public class MageActionCallback implements ActionCallback { // XXX: scaled to fit width bigCard.setCard(mageCard.getOriginal().getId(), enlargeMode, image, mageCard.getOriginal().getRules(), mageCard.getOriginal().isToRotate()); // if it's an ability, show only the ability text as overlay - if (mageCard.getOriginal().isAbility() && enlargeMode.equals(EnlargeMode.NORMAL)) { + if (mageCard.getOriginal().isAbility() && enlargeMode == EnlargeMode.NORMAL) { bigCard.showTextComponent(); } else { bigCard.hideTextComponent(); @@ -637,12 +625,7 @@ public class MageActionCallback implements ActionCallback { private synchronized void startHideTimeout() { cancelTimeout(); - hideTimeout = timeoutExecutor.schedule(new Runnable() { - @Override - public void run() { - hideEnlargedCard(); - } - }, 700, TimeUnit.MILLISECONDS); + hideTimeout = timeoutExecutor.schedule(this::hideEnlargedCard, 700, TimeUnit.MILLISECONDS); } private synchronized void cancelTimeout() { diff --git a/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java b/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java index 9d35070675e..a5b8bcd5571 100644 --- a/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java +++ b/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java @@ -79,302 +79,299 @@ public class CallbackClientImpl implements CallbackClient { public synchronized void processCallback(final ClientCallback callback) { SaveObjectUtil.saveObject(callback.getData(), callback.getMethod()); callback.setData(CompressUtil.decompress(callback.getData())); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - try { - logger.debug(callback.getMessageId() + " -- " + callback.getMethod()); - switch (callback.getMethod()) { - case "startGame": { - TableClientMessage message = (TableClientMessage) callback.getData(); - GameManager.getInstance().setCurrentPlayerUUID(message.getPlayerId()); - gameStarted(message.getGameId(), message.getPlayerId()); - break; + SwingUtilities.invokeLater(() -> { + try { + logger.debug(callback.getMessageId() + " -- " + callback.getMethod()); + switch (callback.getMethod()) { + case "startGame": { + TableClientMessage message = (TableClientMessage) callback.getData(); + GameManager.getInstance().setCurrentPlayerUUID(message.getPlayerId()); + gameStarted(message.getGameId(), message.getPlayerId()); + break; + } + case "startTournament": { + TableClientMessage message = (TableClientMessage) callback.getData(); + tournamentStarted(message.getGameId(), message.getPlayerId()); + break; + } + case "startDraft": { + TableClientMessage message = (TableClientMessage) callback.getData(); + draftStarted(message.getGameId(), message.getPlayerId()); + break; + } + case "replayGame": + replayGame(callback.getObjectId()); + break; + case "showTournament": + showTournament(callback.getObjectId()); + break; + case "watchGame": + watchGame(callback.getObjectId()); + break; + case "chatMessage": { + ChatMessage message = (ChatMessage) callback.getData(); + ChatPanelBasic panel = MageFrame.getChat(callback.getObjectId()); + if (panel != null) { + // play the sound related to the message + if (message.getSoundToPlay() != null) { + switch (message.getSoundToPlay()) { + case PlayerLeft: + AudioManager.playPlayerLeft(); + break; + case PlayerQuitTournament: + AudioManager.playPlayerQuitTournament(); + break; + case PlayerSubmittedDeck: + AudioManager.playPlayerSubmittedDeck(); + break; + case PlayerWhispered: + AudioManager.playPlayerWhispered(); + break; + } + } + // send start message to chat if not done yet + if (!panel.isStartMessageDone()) { + createChatStartMessage(panel); + } + // send the message to subchat if exists and it's not a game message + if (!message.getMessageType().equals(MessageType.GAME) && panel.getConnectedChat() != null) { + panel.getConnectedChat().receiveMessage(message.getUsername(), message.getMessage(), message.getTime(), message.getMessageType(), ChatMessage.MessageColor.BLACK); + } else { + panel.receiveMessage(message.getUsername(), message.getMessage(), message.getTime(), message.getMessageType(), message.getColor()); + } + } - case "startTournament": { - TableClientMessage message = (TableClientMessage) callback.getData(); - tournamentStarted(message.getGameId(), message.getPlayerId()); - break; - } - case "startDraft": { - TableClientMessage message = (TableClientMessage) callback.getData(); - draftStarted(message.getGameId(), message.getPlayerId()); - break; - } - case "replayGame": - replayGame(callback.getObjectId()); - break; - case "showTournament": - showTournament(callback.getObjectId()); - break; - case "watchGame": - watchGame(callback.getObjectId()); - break; - case "chatMessage": { + break; + } + case "serverMessage": + if (callback.getData() != null) { ChatMessage message = (ChatMessage) callback.getData(); - ChatPanelBasic panel = MageFrame.getChat(callback.getObjectId()); - if (panel != null) { - // play the sound related to the message - if (message.getSoundToPlay() != null) { - switch (message.getSoundToPlay()) { - case PlayerLeft: - AudioManager.playPlayerLeft(); - break; - case PlayerQuitTournament: - AudioManager.playPlayerQuitTournament(); - break; - case PlayerSubmittedDeck: - AudioManager.playPlayerSubmittedDeck(); - break; - case PlayerWhispered: - AudioManager.playPlayerWhispered(); - break; - } - } - // send start message to chat if not done yet - if (!panel.isStartMessageDone()) { - createChatStartMessage(panel); - } - // send the message to subchat if exists and it's not a game message - if (!message.getMessageType().equals(MessageType.GAME) && panel.getConnectedChat() != null) { - panel.getConnectedChat().receiveMessage(message.getUsername(), message.getMessage(), message.getTime(), message.getMessageType(), ChatMessage.MessageColor.BLACK); - } else { - panel.receiveMessage(message.getUsername(), message.getMessage(), message.getTime(), message.getMessageType(), message.getColor()); - } + if (message.getColor().equals(ChatMessage.MessageColor.RED)) { + JOptionPane.showMessageDialog(null, message.getMessage(), "Server message", JOptionPane.WARNING_MESSAGE); + } else { + JOptionPane.showMessageDialog(null, message.getMessage(), "Server message", JOptionPane.INFORMATION_MESSAGE); + } + } + break; + case "joinedTable": { + TableClientMessage message = (TableClientMessage) callback.getData(); + joinedTable(message.getRoomId(), message.getTableId(), message.getFlag()); + break; + } + case "replayInit": { + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.init((GameView) callback.getData()); + } + break; + } + case "replayDone": { + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.endMessage((String) callback.getData(), callback.getMessageId()); + } + break; + } + case "replayUpdate": { + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.updateGame((GameView) callback.getData()); + } + break; + } + case "gameInit": { + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.init((GameView) callback.getData()); + } + break; + } + case "gameOver": { + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.endMessage((String) callback.getData(), callback.getMessageId()); + } + break; + } + case "gameError": + frame.showErrorDialog("Game Error", (String) callback.getData()); + break; + case "gameAsk": { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.ask(message.getMessage(), message.getGameView(), callback.getMessageId(), message.getOptions()); + } + break; + } + case "gameTarget": // e.g. Pick triggered ability + { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.pickTarget(message.getMessage(), message.getCardsView(), message.getGameView(), + message.getTargets(), message.isFlag(), message.getOptions(), callback.getMessageId()); + } + break; + } + case "gameSelect": { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.select(message.getMessage(), message.getGameView(), callback.getMessageId(), message.getOptions()); + } + break; + } + case "gameChooseAbility": { + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.pickAbility((AbilityPickerView) callback.getData()); + } + break; + } + case "gameChoosePile": { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.pickPile(message.getMessage(), message.getPile1(), message.getPile2()); + } + break; + } + case "gameChooseChoice": { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); - } - break; + if (panel != null) { + panel.getChoice(message.getChoice(), callback.getObjectId()); } - case "serverMessage": - if (callback.getData() != null) { - ChatMessage message = (ChatMessage) callback.getData(); - if (message.getColor().equals(ChatMessage.MessageColor.RED)) { - JOptionPane.showMessageDialog(null, message.getMessage(), "Server message", JOptionPane.WARNING_MESSAGE); - } else { - JOptionPane.showMessageDialog(null, message.getMessage(), "Server message", JOptionPane.INFORMATION_MESSAGE); + break; + } + case "gamePlayMana": { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.playMana(message.getMessage(), message.getGameView(), message.getOptions(), callback.getMessageId()); + } + break; + } + case "gamePlayXMana": { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.playXMana(message.getMessage(), message.getGameView(), callback.getMessageId()); + } + break; + } + case "gameSelectAmount": { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.getAmount(message.getMin(), message.getMax(), message.getMessage()); + } + break; + } + case "gameUpdate": { + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.updateGame((GameView) callback.getData()); + } + break; + } + case "endGameInfo": + MageFrame.getInstance().showGameEndDialog((GameEndView) callback.getData()); + break; + case "showUserMessage": + List messageData = (List) callback.getData(); + if (messageData.size() == 2) { + JOptionPane.showMessageDialog(null, messageData.get(1), messageData.get(0), JOptionPane.WARNING_MESSAGE); + } + break; + case "gameInform": + if (callback.getMessageId() > gameInformMessageId) { + { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + panel.inform(message.getMessage(), message.getGameView(), callback.getMessageId()); } } - break; - case "joinedTable": { - TableClientMessage message = (TableClientMessage) callback.getData(); - joinedTable(message.getRoomId(), message.getTableId(), message.getFlag()); - break; - } - case "replayInit": { - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.init((GameView) callback.getData()); - } - break; - } - case "replayDone": { - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.endMessage((String) callback.getData(), callback.getMessageId()); - } - break; - } - case "replayUpdate": { - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.updateGame((GameView) callback.getData()); - } - break; - } - case "gameInit": { - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.init((GameView) callback.getData()); - } - break; - } - case "gameOver": { - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.endMessage((String) callback.getData(), callback.getMessageId()); - } - break; - } - case "gameError": - frame.showErrorDialog("Game Error", (String) callback.getData()); - break; - case "gameAsk": { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.ask(message.getMessage(), message.getGameView(), callback.getMessageId(), message.getOptions()); - } - break; - } - case "gameTarget": // e.g. Pick triggered ability - { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.pickTarget(message.getMessage(), message.getCardsView(), message.getGameView(), - message.getTargets(), message.isFlag(), message.getOptions(), callback.getMessageId()); - } - break; - } - case "gameSelect": { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.select(message.getMessage(), message.getGameView(), callback.getMessageId(), message.getOptions()); - } - break; - } - case "gameChooseAbility": { - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.pickAbility((AbilityPickerView) callback.getData()); - } - break; - } - case "gameChoosePile": { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.pickPile(message.getMessage(), message.getPile1(), message.getPile2()); - } - break; - } - case "gameChooseChoice": { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - - if (panel != null) { - panel.getChoice(message.getChoice(), callback.getObjectId()); - } - break; - } - case "gamePlayMana": { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.playMana(message.getMessage(), message.getGameView(), message.getOptions(), callback.getMessageId()); - } - break; - } - case "gamePlayXMana": { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.playXMana(message.getMessage(), message.getGameView(), callback.getMessageId()); - } - break; - } - case "gameSelectAmount": { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.getAmount(message.getMin(), message.getMax(), message.getMessage()); - } - break; - } - case "gameUpdate": { - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.updateGame((GameView) callback.getData()); - } - break; - } - case "endGameInfo": - MageFrame.getInstance().showGameEndDialog((GameEndView) callback.getData()); - break; - case "showUserMessage": - List messageData = (List) callback.getData(); - if (messageData.size() == 2) { - JOptionPane.showMessageDialog(null, messageData.get(1), messageData.get(0), JOptionPane.WARNING_MESSAGE); - } - break; - case "gameInform": - if (callback.getMessageId() > gameInformMessageId) { - { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - panel.inform(message.getMessage(), message.getGameView(), callback.getMessageId()); - } - } // no longer needed because phase skip handling on server side now - } else { - logger.warn(new StringBuilder("message out of sequence - ignoring").append("MessageId = ").append(callback.getMessageId()).append(" method = ").append(callback.getMethod())); - //logger.warn("message out of sequence - ignoring"); - } - gameInformMessageId = messageId; - break; - case "gameInformPersonal": { - GameClientMessage message = (GameClientMessage) callback.getData(); - GamePanel panel = MageFrame.getGame(callback.getObjectId()); - if (panel != null) { - JOptionPane.showMessageDialog(panel, message.getMessage(), "Game message", - JOptionPane.INFORMATION_MESSAGE); - } - break; + } else { + logger.warn(new StringBuilder("message out of sequence - ignoring").append("MessageId = ").append(callback.getMessageId()).append(" method = ").append(callback.getMethod())); + //logger.warn("message out of sequence - ignoring"); } - case "sideboard": { - TableClientMessage message = (TableClientMessage) callback.getData(); - DeckView deckView = message.getDeck(); - Deck deck = DeckUtil.construct(deckView); - if (message.getFlag()) { - construct(deck, message.getTableId(), message.getTime()); - } else { - sideboard(deck, message.getTableId(), message.getTime()); - } - break; + gameInformMessageId = messageId; + break; + case "gameInformPersonal": { + GameClientMessage message = (GameClientMessage) callback.getData(); + GamePanel panel = MageFrame.getGame(callback.getObjectId()); + if (panel != null) { + JOptionPane.showMessageDialog(panel, message.getMessage(), "Game message", + JOptionPane.INFORMATION_MESSAGE); } - case "construct": { - TableClientMessage message = (TableClientMessage) callback.getData(); - DeckView deckView = message.getDeck(); - Deck deck = DeckUtil.construct(deckView); + break; + } + case "sideboard": { + TableClientMessage message = (TableClientMessage) callback.getData(); + DeckView deckView = message.getDeck(); + Deck deck = DeckUtil.construct(deckView); + if (message.getFlag()) { construct(deck, message.getTableId(), message.getTime()); - break; + } else { + sideboard(deck, message.getTableId(), message.getTime()); } - case "draftOver": - MageFrame.removeDraft(callback.getObjectId()); - break; - case "draftPick": { - DraftClientMessage message = (DraftClientMessage) callback.getData(); - DraftPanel panel = MageFrame.getDraft(callback.getObjectId()); - if (panel != null) { - panel.loadBooster(message.getDraftPickView()); - } - break; + break; + } + case "construct": { + TableClientMessage message = (TableClientMessage) callback.getData(); + DeckView deckView = message.getDeck(); + Deck deck = DeckUtil.construct(deckView); + construct(deck, message.getTableId(), message.getTime()); + break; + } + case "draftOver": + MageFrame.removeDraft(callback.getObjectId()); + break; + case "draftPick": { + DraftClientMessage message = (DraftClientMessage) callback.getData(); + DraftPanel panel = MageFrame.getDraft(callback.getObjectId()); + if (panel != null) { + panel.loadBooster(message.getDraftPickView()); } - case "draftUpdate": { - DraftPanel panel = MageFrame.getDraft(callback.getObjectId()); - if (panel != null) { - panel.updateDraft((DraftView) callback.getData()); - } - break; - } - case "draftInform": // if (callback.getMessageId() > messageId) { - { - DraftClientMessage message = (DraftClientMessage) callback.getData(); + break; + } + case "draftUpdate": { + DraftPanel panel = MageFrame.getDraft(callback.getObjectId()); + if (panel != null) { + panel.updateDraft((DraftView) callback.getData()); } + break; + } + case "draftInform": // if (callback.getMessageId() > messageId) { + { + DraftClientMessage message = (DraftClientMessage) callback.getData(); + } // } else { // logger.warn("message out of sequence - ignoring"); // } - break; - case "draftInit": { - DraftClientMessage message = (DraftClientMessage) callback.getData(); - DraftPanel panel = MageFrame.getDraft(callback.getObjectId()); - if (panel != null) { - panel.loadBooster(message.getDraftPickView()); - } - break; + break; + case "draftInit": { + DraftClientMessage message = (DraftClientMessage) callback.getData(); + DraftPanel panel = MageFrame.getDraft(callback.getObjectId()); + if (panel != null) { + panel.loadBooster(message.getDraftPickView()); } - case "tournamentInit": - break; - case "userRequestDialog": - frame.showUserRequestDialog((UserRequestMessage) callback.getData()); - break; + break; } - messageId = callback.getMessageId(); - } catch (Exception ex) { - handleException(ex); + case "tournamentInit": + break; + case "userRequestDialog": + frame.showUserRequestDialog((UserRequestMessage) callback.getData()); + break; } + messageId = callback.getMessageId(); + } catch (Exception ex) { + handleException(ex); } }); } @@ -391,28 +388,28 @@ public class CallbackClientImpl implements CallbackClient { .append("
Turn mousewheel up (ALT-e) - enlarge image of card the mousepointer hovers over") .append("
Turn mousewheel down (ALT-s) - enlarge original/alternate image of card the mousepointer hovers over") .append("
") - .append(KeyEvent.getKeyText((Integer) PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_CONFIRM, 113))) + .append(KeyEvent.getKeyText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_CONFIRM, 113))) .append(" - Confirm \"Ok\", \"Yes\" or \"Done\" button") .append("
") - .append(KeyEvent.getKeyText((Integer) PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_NEXT_TURN, 115))) + .append(KeyEvent.getKeyText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_NEXT_TURN, 115))) .append(" - Skip current turn but stop on declare attackers/blockers and something on the stack") .append("
") - .append(KeyEvent.getKeyText((Integer) PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_END_STEP, 116))) + .append(KeyEvent.getKeyText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_END_STEP, 116))) .append(" - Skip to next end step but stop on declare attackers/blockers and something on the stack") .append("
") - .append(KeyEvent.getKeyText((Integer) PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_SKIP_STEP, 117))) + .append(KeyEvent.getKeyText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_SKIP_STEP, 117))) .append(" - Skip current turn but stop on declare attackers/blockers") .append("
") - .append(KeyEvent.getKeyText((Integer) PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_MAIN_STEP, 118))) + .append(KeyEvent.getKeyText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_MAIN_STEP, 118))) .append(" - Skip to next main phase but stop on declare attackers/blockers and something on the stack") .append("
") - .append(KeyEvent.getKeyText((Integer) PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_YOUR_TURN, 120))) + .append(KeyEvent.getKeyText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_YOUR_TURN, 120))) .append(" - Skip everything until your next turn") .append("
") - .append(KeyEvent.getKeyText((Integer) PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_PRIOR_END, 122))) + .append(KeyEvent.getKeyText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_PRIOR_END, 122))) .append(" - Skip everything until the end step just prior to your turn") .append("
") - .append(KeyEvent.getKeyText((Integer) PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_CANCEL_SKIP, 114))) + .append(KeyEvent.getKeyText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONTROL_CANCEL_SKIP, 114))) .append(" - Undo F4/F5/F7/F9/F11") .append("
").append(System.getProperty("os.name").contains("Mac OS X") ? "Cmd" : "Ctrl").append(" + click - Hold priority while casting a spell or activating an ability").toString(), null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); diff --git a/Mage.Client/src/main/java/mage/client/table/NewPlayerPanel.java b/Mage.Client/src/main/java/mage/client/table/NewPlayerPanel.java index 71709ce7daf..7d28ba8f8ac 100644 --- a/Mage.Client/src/main/java/mage/client/table/NewPlayerPanel.java +++ b/Mage.Client/src/main/java/mage/client/table/NewPlayerPanel.java @@ -153,18 +153,10 @@ public class NewPlayerPanel extends javax.swing.JPanel { lblPlayerDeck.setText("Deck:"); btnPlayerDeck.setText("..."); - btnPlayerDeck.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnPlayerDeckActionPerformed(evt); - } - }); + btnPlayerDeck.addActionListener(evt -> btnPlayerDeckActionPerformed(evt)); btnGenerate.setText("Generate"); - btnGenerate.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnGenerateActionPerformed(evt); - } - }); + btnGenerate.addActionListener(evt -> btnGenerateActionPerformed(evt)); lblLevel.setText("Skill:"); diff --git a/Mage.Client/src/main/java/mage/client/table/PlayersChatPanel.java b/Mage.Client/src/main/java/mage/client/table/PlayersChatPanel.java index 32ffc8ecde4..365f2d6529e 100644 --- a/Mage.Client/src/main/java/mage/client/table/PlayersChatPanel.java +++ b/Mage.Client/src/main/java/mage/client/table/PlayersChatPanel.java @@ -394,7 +394,7 @@ public class PlayersChatPanel extends javax.swing.JPanel { class ColumnHeaderToolTips extends MouseMotionAdapter { int curCol; - Map tips = new HashMap<>(); + final Map tips = new HashMap<>(); public void setToolTip(Integer mCol, String tooltip) { if (tooltip == null) { diff --git a/Mage.Client/src/main/java/mage/client/table/TablePlayerPanel.java b/Mage.Client/src/main/java/mage/client/table/TablePlayerPanel.java index aefca569cf0..902aab84dd9 100644 --- a/Mage.Client/src/main/java/mage/client/table/TablePlayerPanel.java +++ b/Mage.Client/src/main/java/mage/client/table/TablePlayerPanel.java @@ -34,17 +34,14 @@ package mage.client.table; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.UUID; import javax.swing.DefaultComboBoxModel; import mage.cards.decks.importer.DeckImporterUtil; -import mage.client.MageFrame; import mage.client.SessionHandler; import mage.client.util.Config; import mage.client.util.Event; import mage.client.util.Listener; -import mage.remote.Session; /** * @@ -52,7 +49,7 @@ import mage.remote.Session; */ public class TablePlayerPanel extends javax.swing.JPanel { - protected PlayerTypeEventSource playerTypeEventSource = new PlayerTypeEventSource(); + protected final PlayerTypeEventSource playerTypeEventSource = new PlayerTypeEventSource(); /** Creates new form TablePlayerPanel */ @@ -78,7 +75,7 @@ public class TablePlayerPanel extends javax.swing.JPanel { } } - public boolean joinTable(UUID roomId, UUID tableId) throws FileNotFoundException, IOException, ClassNotFoundException { + public boolean joinTable(UUID roomId, UUID tableId) throws IOException, ClassNotFoundException { if (!this.cbPlayerType.getSelectedItem().equals("Human")) { return SessionHandler.joinTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), (String)this.cbPlayerType.getSelectedItem(), this.newPlayerPanel.getLevel(), DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()),""); } @@ -114,11 +111,7 @@ public class TablePlayerPanel extends javax.swing.JPanel { lbPlayerType.setText("Type:"); - cbPlayerType.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbPlayerTypeActionPerformed(evt); - } - }); + cbPlayerType.addActionListener(evt -> cbPlayerTypeActionPerformed(evt)); lblPlayerNum.setFont(new java.awt.Font("Tahoma", 1, 11)); lblPlayerNum.setText("Player #"); diff --git a/Mage.Client/src/main/java/mage/client/table/TablesPane.java b/Mage.Client/src/main/java/mage/client/table/TablesPane.java index b2754f06f78..78e685ae6e3 100644 --- a/Mage.Client/src/main/java/mage/client/table/TablesPane.java +++ b/Mage.Client/src/main/java/mage/client/table/TablesPane.java @@ -29,7 +29,7 @@ package mage.client.table; import java.util.UUID; import javax.swing.JComponent; -import mage.client.MageFrame; + import mage.client.MagePane; import mage.client.SessionHandler; import mage.client.plugins.impl.Plugins; diff --git a/Mage.Client/src/main/java/mage/client/table/TablesPanel.java b/Mage.Client/src/main/java/mage/client/table/TablesPanel.java index 646369c1668..4081bcdc2bc 100644 --- a/Mage.Client/src/main/java/mage/client/table/TablesPanel.java +++ b/Mage.Client/src/main/java/mage/client/table/TablesPanel.java @@ -82,6 +82,7 @@ import mage.client.dialog.PreferencesDialog; import static mage.client.dialog.PreferencesDialog.KEY_TABLES_COLUMNS_ORDER; import static mage.client.dialog.PreferencesDialog.KEY_TABLES_COLUMNS_WIDTH; import mage.client.dialog.TableWaitingDialog; +import static mage.client.table.TablesPanel.PASSWORDED; import mage.client.util.ButtonColumn; import mage.client.util.GUISizeHelper; import mage.client.util.MageTableRowSorter; @@ -109,8 +110,9 @@ public class TablesPanel extends javax.swing.JPanel { private static final Logger LOGGER = Logger.getLogger(TablesPanel.class); private static final int[] DEFAULT_COLUMNS_WIDTH = {35, 150, 120, 180, 80, 120, 80, 60, 40, 40, 60}; - private TableTableModel tableModel; - private MatchesTableModel matchesModel; + public static final String PASSWORDED = "***"; + private final TableTableModel tableModel; + private final MatchesTableModel matchesModel; private UUID roomId; private UpdateTablesTask updateTablesTask; private UpdatePlayersTask updatePlayersTask; @@ -118,15 +120,15 @@ public class TablesPanel extends javax.swing.JPanel { private JoinTableDialog joinTableDialog; private NewTableDialog newTableDialog; private NewTournamentDialog newTournamentDialog; - private GameChooser gameChooser; + private final GameChooser gameChooser; private List messages; private int currentMessage; - private MageTableRowSorter activeTablesSorter; + private final MageTableRowSorter activeTablesSorter; private final ButtonColumn actionButton1; private final ButtonColumn actionButton2; - JToggleButton[] filterButtons; + final JToggleButton[] filterButtons; /** * Creates new form TablesPanel @@ -138,7 +140,7 @@ public class TablesPanel extends javax.swing.JPanel { gameChooser = new GameChooser(); initComponents(); - // tableModel.setSession(session); + // tableModel.setSession(session); tableTables.createDefaultColumnsFromModel(); @@ -180,9 +182,9 @@ public class TablesPanel extends javax.swing.JPanel { UUID gameId = (UUID) tableModel.getValueAt(modelRow, TableTableModel.ACTION_COLUMN + 2); String action = (String) tableModel.getValueAt(modelRow, TableTableModel.ACTION_COLUMN); String deckType = (String) tableModel.getValueAt(modelRow, TableTableModel.COLUMN_DECK_TYPE); - String status = (String) tableModel.getValueAt(modelRow, TableTableModel.COLUMN_STATUS); boolean isTournament = (Boolean) tableModel.getValueAt(modelRow, TableTableModel.ACTION_COLUMN + 1); String owner = (String) tableModel.getValueAt(modelRow, TableTableModel.COLUMN_OWNER); + String pwdColumn = (String) tableModel.getValueAt(modelRow, TableTableModel.COLUMN_PASSWORD); switch (action) { case "Join": if (owner.equals(SessionHandler.getUserName()) || owner.startsWith(SessionHandler.getUserName() + ",")) { @@ -209,10 +211,10 @@ public class TablesPanel extends javax.swing.JPanel { if (isTournament) { LOGGER.info("Joining tournament " + tableId); if (deckType.startsWith("Limited")) { - if (!status.endsWith("PW")) { - SessionHandler.joinTournamentTable(roomId, tableId, SessionHandler.getUserName(), "Human", 1, null, ""); - } else { + if (PASSWORDED.equals(pwdColumn)) { joinTableDialog.showDialog(roomId, tableId, true, deckType.startsWith("Limited")); + } else { + SessionHandler.joinTournamentTable(roomId, tableId, SessionHandler.getUserName(), "Human", 1, null, ""); } } else { joinTableDialog.showDialog(roomId, tableId, true, deckType.startsWith("Limited")); @@ -266,7 +268,7 @@ public class TablesPanel extends javax.swing.JPanel { } // MageFrame.getDesktop().showTournament(tournamentId); break; - case "Show":; + case "Show": if (matchesModel.isTournament(modelRow)) { LOGGER.info("Showing tournament table " + matchesModel.getTableId(modelRow)); SessionHandler.watchTable(roomId, matchesModel.getTableId(modelRow)); @@ -505,12 +507,7 @@ public class TablesPanel extends javax.swing.JPanel { MageFrame.getUI().addButton(MageComponents.NEW_GAME_BUTTON, btnNewTable); // divider locations have to be set with delay else values set are overwritten with system defaults - Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() { - @Override - public void run() { - restoreDividerLocations(); - } - }, 300, TimeUnit.MILLISECONDS); + Executors.newSingleThreadScheduledExecutor().schedule(() -> restoreDividerLocations(), 300, TimeUnit.MILLISECONDS); } @@ -617,10 +614,10 @@ public class TablesPanel extends javax.swing.JPanel { } List> ratingFilterList = new ArrayList<>(); - if (btnRated.isSelected()){ + if (btnRated.isSelected()) { ratingFilterList.add(RowFilter.regexFilter("^Rated", TableTableModel.COLUMN_RATING)); } - if (btnUnrated.isSelected()){ + if (btnUnrated.isSelected()) { ratingFilterList.add(RowFilter.regexFilter("^Unrated", TableTableModel.COLUMN_RATING)); } @@ -670,7 +667,7 @@ public class TablesPanel extends javax.swing.JPanel { filterList.addAll(ratingFilterList); } - if (passwordFilterList.size() > 1) { + if (passwordFilterList.size() > 1) { filterList.add(RowFilter.orFilter(passwordFilterList)); } else if (passwordFilterList.size() == 1) { filterList.addAll(passwordFilterList); @@ -749,20 +746,12 @@ public class TablesPanel extends javax.swing.JPanel { btnNewTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/match_new.png"))); // NOI18N btnNewTable.setToolTipText("Creates a new match table."); btnNewTable.setMargin(new java.awt.Insets(2, 2, 2, 2)); - btnNewTable.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnNewTableActionPerformed(evt); - } - }); + btnNewTable.addActionListener(evt -> btnNewTableActionPerformed(evt)); btnNewTournament.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/tourney_new.png"))); // NOI18N btnNewTournament.setToolTipText("Creates a new tourney table."); btnNewTournament.setMargin(new java.awt.Insets(2, 2, 2, 2)); - btnNewTournament.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnNewTournamentActionPerformed(evt); - } - }); + btnNewTournament.addActionListener(evt -> btnNewTournamentActionPerformed(evt)); filterBar1.setFloatable(false); filterBar1.setForeground(new java.awt.Color(102, 102, 255)); @@ -778,11 +767,7 @@ public class TablesPanel extends javax.swing.JPanel { btnStateWaiting.setRequestFocusEnabled(false); btnStateWaiting.setVerifyInputWhenFocusTarget(false); btnStateWaiting.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnStateWaiting.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnStateWaiting.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnStateWaiting); btnStateActive.setSelected(true); @@ -794,11 +779,7 @@ public class TablesPanel extends javax.swing.JPanel { btnStateActive.setRequestFocusEnabled(false); btnStateActive.setVerifyInputWhenFocusTarget(false); btnStateActive.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnStateActive.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnStateActive.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnStateActive); btnStateFinished.setSelected(true); @@ -810,11 +791,7 @@ public class TablesPanel extends javax.swing.JPanel { btnStateFinished.setRequestFocusEnabled(false); btnStateFinished.setVerifyInputWhenFocusTarget(false); btnStateFinished.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnStateFinished.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnStateFinishedActionPerformed(evt); - } - }); + btnStateFinished.addActionListener(evt -> btnStateFinishedActionPerformed(evt)); filterBar1.add(btnStateFinished); filterBar1.add(jSeparator1); @@ -828,11 +805,7 @@ public class TablesPanel extends javax.swing.JPanel { btnTypeMatch.setRequestFocusEnabled(false); btnTypeMatch.setVerifyInputWhenFocusTarget(false); btnTypeMatch.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnTypeMatch.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnTypeMatch.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnTypeMatch); btnTypeTourneyConstructed.setSelected(true); @@ -843,11 +816,7 @@ public class TablesPanel extends javax.swing.JPanel { btnTypeTourneyConstructed.setFocusable(false); btnTypeTourneyConstructed.setRequestFocusEnabled(false); btnTypeTourneyConstructed.setVerifyInputWhenFocusTarget(false); - btnTypeTourneyConstructed.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnTypeTourneyConstructed.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnTypeTourneyConstructed); btnTypeTourneyLimited.setSelected(true); @@ -859,11 +828,7 @@ public class TablesPanel extends javax.swing.JPanel { btnTypeTourneyLimited.setMaximumSize(new java.awt.Dimension(72, 20)); btnTypeTourneyLimited.setRequestFocusEnabled(false); btnTypeTourneyLimited.setVerifyInputWhenFocusTarget(false); - btnTypeTourneyLimited.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnTypeTourneyLimited.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnTypeTourneyLimited); filterBar1.add(jSeparator4); @@ -877,11 +842,7 @@ public class TablesPanel extends javax.swing.JPanel { btnSkillBeginner.setRequestFocusEnabled(false); btnSkillBeginner.setVerifyInputWhenFocusTarget(false); btnSkillBeginner.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnSkillBeginner.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnSkillBeginner.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnSkillBeginner); btnSkillCasual.setSelected(true); @@ -894,11 +855,7 @@ public class TablesPanel extends javax.swing.JPanel { btnSkillCasual.setRequestFocusEnabled(false); btnSkillCasual.setVerifyInputWhenFocusTarget(false); btnSkillCasual.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnSkillCasual.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnSkillCasual.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnSkillCasual); btnSkillSerious.setSelected(true); @@ -911,11 +868,7 @@ public class TablesPanel extends javax.swing.JPanel { btnSkillSerious.setRequestFocusEnabled(false); btnSkillSerious.setVerifyInputWhenFocusTarget(false); btnSkillSerious.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnSkillSerious.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnSkillSerious.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnSkillSerious); filterBar1.add(jSeparator4); @@ -929,11 +882,7 @@ public class TablesPanel extends javax.swing.JPanel { btnRated.setRequestFocusEnabled(false); btnRated.setVerifyInputWhenFocusTarget(false); btnRated.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnRated.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnRated.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnRated); btnUnrated.setSelected(true); @@ -945,11 +894,7 @@ public class TablesPanel extends javax.swing.JPanel { btnUnrated.setRequestFocusEnabled(false); btnUnrated.setVerifyInputWhenFocusTarget(false); btnUnrated.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnUnrated.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnUnrated.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar1.add(btnUnrated); // second filter line @@ -966,11 +911,7 @@ public class TablesPanel extends javax.swing.JPanel { btnFormatBlock.setRequestFocusEnabled(false); btnFormatBlock.setVerifyInputWhenFocusTarget(false); btnFormatBlock.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnFormatBlock.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnFormatBlock.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnFormatBlock); btnFormatStandard.setSelected(true); @@ -982,11 +923,7 @@ public class TablesPanel extends javax.swing.JPanel { btnFormatStandard.setRequestFocusEnabled(false); btnFormatStandard.setVerifyInputWhenFocusTarget(false); btnFormatStandard.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnFormatStandard.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnFormatStandard.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnFormatStandard); btnFormatModern.setSelected(true); @@ -996,11 +933,7 @@ public class TablesPanel extends javax.swing.JPanel { btnFormatModern.setFocusable(false); btnFormatModern.setRequestFocusEnabled(false); btnFormatModern.setVerifyInputWhenFocusTarget(false); - btnFormatModern.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnFormatModern.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnFormatModern); btnFormatLegacy.setSelected(true); @@ -1012,11 +945,7 @@ public class TablesPanel extends javax.swing.JPanel { btnFormatLegacy.setRequestFocusEnabled(false); btnFormatLegacy.setVerifyInputWhenFocusTarget(false); btnFormatLegacy.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnFormatLegacy.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnFormatLegacy.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnFormatLegacy); btnFormatVintage.setSelected(true); @@ -1028,11 +957,7 @@ public class TablesPanel extends javax.swing.JPanel { btnFormatVintage.setRequestFocusEnabled(false); btnFormatVintage.setVerifyInputWhenFocusTarget(false); btnFormatVintage.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnFormatVintage.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnFormatVintage.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnFormatVintage); filterBar2.add(jSeparator3); @@ -1045,11 +970,7 @@ public class TablesPanel extends javax.swing.JPanel { btnFormatCommander.setRequestFocusEnabled(false); btnFormatCommander.setVerifyInputWhenFocusTarget(false); btnFormatCommander.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnFormatCommander.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnFormatCommander.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnFormatCommander); btnFormatTinyLeader.setSelected(true); @@ -1059,11 +980,7 @@ public class TablesPanel extends javax.swing.JPanel { btnFormatTinyLeader.setFocusable(false); btnFormatTinyLeader.setRequestFocusEnabled(false); btnFormatTinyLeader.setVerifyInputWhenFocusTarget(false); - btnFormatTinyLeader.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnFormatTinyLeader.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnFormatTinyLeader); filterBar2.add(jSeparator2); @@ -1076,11 +993,7 @@ public class TablesPanel extends javax.swing.JPanel { btnFormatLimited.setRequestFocusEnabled(false); btnFormatLimited.setVerifyInputWhenFocusTarget(false); btnFormatLimited.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnFormatLimited.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnFormatLimited.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnFormatLimited); btnFormatOther.setSelected(true); @@ -1090,11 +1003,7 @@ public class TablesPanel extends javax.swing.JPanel { btnFormatOther.setFocusable(false); btnFormatOther.setRequestFocusEnabled(false); btnFormatOther.setVerifyInputWhenFocusTarget(false); - btnFormatOther.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnFormatOther.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnFormatOther); filterBar2.add(jSeparator5); @@ -1107,11 +1016,7 @@ public class TablesPanel extends javax.swing.JPanel { btnOpen.setRequestFocusEnabled(false); btnOpen.setVerifyInputWhenFocusTarget(false); btnOpen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnOpen.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnOpen.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnOpen); btnPassword.setSelected(true); @@ -1123,22 +1028,14 @@ public class TablesPanel extends javax.swing.JPanel { btnPassword.setRequestFocusEnabled(false); btnPassword.setVerifyInputWhenFocusTarget(false); btnPassword.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnPassword.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnFilterActionPerformed(evt); - } - }); + btnPassword.addActionListener(evt -> btnFilterActionPerformed(evt)); filterBar2.add(btnPassword); btnQuickStart.setText("Quick Start"); btnQuickStart.setFocusable(false); btnQuickStart.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnQuickStart.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); - btnQuickStart.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnQuickStartActionPerformed(evt); - } - }); + btnQuickStart.addActionListener(evt -> btnQuickStartActionPerformed(evt)); javax.swing.GroupLayout jPanelTopLayout = new javax.swing.GroupLayout(jPanelTop); jPanelTop.setLayout(jPanelTopLayout); @@ -1235,11 +1132,7 @@ public class TablesPanel extends javax.swing.JPanel { jButtonFooterNext.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jButtonFooterNext.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonFooterNext.setOpaque(false); - jButtonFooterNext.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jButtonFooterNextActionPerformed(evt); - } - }); + jButtonFooterNext.addActionListener(evt -> jButtonFooterNextActionPerformed(evt)); jPanelBottom.add(jButtonFooterNext); jLabelFooterLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N @@ -1380,8 +1273,8 @@ public class TablesPanel extends javax.swing.JPanel { class TableTableModel extends AbstractTableModel { - ImageIcon tourneyIcon = new javax.swing.ImageIcon(getClass().getResource("/tables/tourney_icon.png")); - ImageIcon matchIcon = new javax.swing.ImageIcon(getClass().getResource("/tables/match_icon.png")); + final ImageIcon tourneyIcon = new javax.swing.ImageIcon(getClass().getResource("/tables/tourney_icon.png")); + final ImageIcon matchIcon = new javax.swing.ImageIcon(getClass().getResource("/tables/match_icon.png")); public static final int COLUMN_ICON = 0; public static final int COLUMN_DECK_TYPE = 1; // column the deck type is located (starting with 0) Start string is used to check for Limited @@ -1400,8 +1293,6 @@ class TableTableModel extends AbstractTableModel { private TableView[] tables = new TableView[0]; private static final DateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss"); - ; - public void loadData(Collection tables) throws MageRemoteException { this.tables = tables.toArray(new TableView[0]); @@ -1418,7 +1309,6 @@ class TableTableModel extends AbstractTableModel { return columnNames.length; } - @Override public Object getValueAt(int arg0, int arg1) { switch (arg1) { @@ -1435,7 +1325,7 @@ class TableTableModel extends AbstractTableModel { case 5: return tables[arg0].getTableStateText(); case 6: - return tables[arg0].isPassworded() ? "***" : ""; + return tables[arg0].isPassworded() ? PASSWORDED : ""; case 7: return timeFormatter.format(tables[arg0].getCreateTime()); case 8: @@ -1570,7 +1460,7 @@ class UpdatePlayersTask extends SwingWorker> { private static final Logger logger = Logger.getLogger(UpdatePlayersTask.class); - UpdatePlayersTask( UUID roomId, PlayersChatPanel chat) { + UpdatePlayersTask(UUID roomId, PlayersChatPanel chat) { this.roomId = roomId; this.chat = chat; @@ -1746,7 +1636,6 @@ class UpdateMatchesTask extends SwingWorker> { class GameChooser extends JPopupMenu { - public void init() { } diff --git a/Mage.Client/src/main/java/mage/client/table/TournamentPlayerPanel.java b/Mage.Client/src/main/java/mage/client/table/TournamentPlayerPanel.java index a32c3b58512..2f220eaddb7 100644 --- a/Mage.Client/src/main/java/mage/client/table/TournamentPlayerPanel.java +++ b/Mage.Client/src/main/java/mage/client/table/TournamentPlayerPanel.java @@ -38,9 +38,7 @@ import java.util.UUID; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import mage.cards.decks.DeckCardLists; -import mage.client.MageFrame; import mage.client.SessionHandler; -import mage.remote.Session; /** * @@ -101,11 +99,7 @@ public class TournamentPlayerPanel extends javax.swing.JPanel { jLabel1.setText("Type:"); cbPlayerType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); - cbPlayerType.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - cbPlayerTypeActionPerformed(evt); - } - }); + cbPlayerType.addActionListener(evt -> cbPlayerTypeActionPerformed(evt)); lblPlayerNum.setFont(new java.awt.Font("Tahoma", 1, 11)); lblPlayerNum.setText("Player Num:"); diff --git a/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java b/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java index 98554d35183..fea2f500e41 100644 --- a/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java +++ b/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java @@ -84,7 +84,7 @@ public class TournamentPanel extends javax.swing.JPanel { private boolean firstInitDone = false; private final TournamentPlayersTableModel playersModel; - private TournamentMatchesTableModel matchesModel; + private final TournamentMatchesTableModel matchesModel; private UpdateTournamentTask updateTask; private final DateFormat df; @@ -358,11 +358,7 @@ public class TournamentPanel extends javax.swing.JPanel { txtName.setMaximumSize(new java.awt.Dimension(50, 22)); txtName.setOpaque(false); txtName.setRequestFocusEnabled(false); - txtName.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - txtNameActionPerformed(evt); - } - }); + txtName.addActionListener(evt -> txtNameActionPerformed(evt)); txtType.setEditable(false); txtType.setHorizontalAlignment(javax.swing.JTextField.LEFT); @@ -394,19 +390,11 @@ public class TournamentPanel extends javax.swing.JPanel { btnQuitTournament.setText("Quit Tournament"); btnQuitTournament.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); - btnQuitTournament.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnQuitTournamentActionPerformed(evt); - } - }); + btnQuitTournament.addActionListener(evt -> btnQuitTournamentActionPerformed(evt)); btnCloseWindow.setText("Close Window"); btnCloseWindow.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); - btnCloseWindow.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnCloseWindowActionPerformed(evt); - } - }); + btnCloseWindow.addActionListener(evt -> btnCloseWindowActionPerformed(evt)); lblName.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N lblName.setText("Name:"); diff --git a/Mage.Client/src/main/java/mage/client/unusedFiles/DelayedViewerThread.java b/Mage.Client/src/main/java/mage/client/unusedFiles/DelayedViewerThread.java index 7d878d75566..8d0318e4ea2 100644 --- a/Mage.Client/src/main/java/mage/client/unusedFiles/DelayedViewerThread.java +++ b/Mage.Client/src/main/java/mage/client/unusedFiles/DelayedViewerThread.java @@ -9,7 +9,7 @@ import java.util.Map; public class DelayedViewerThread extends Thread { - private static DelayedViewerThread fInstance = new DelayedViewerThread(); + private static final DelayedViewerThread fInstance = new DelayedViewerThread(); public static DelayedViewerThread getInstance() { return fInstance; diff --git a/Mage.Client/src/main/java/mage/client/unusedFiles/PlayerPanel.java b/Mage.Client/src/main/java/mage/client/unusedFiles/PlayerPanel.java index 2b46f47ea00..a0efe5eb61c 100644 --- a/Mage.Client/src/main/java/mage/client/unusedFiles/PlayerPanel.java +++ b/Mage.Client/src/main/java/mage/client/unusedFiles/PlayerPanel.java @@ -36,11 +36,10 @@ package mage.client.unusedFiles; import java.awt.Color; import java.util.UUID; -import mage.client.MageFrame; + import mage.client.SessionHandler; import mage.client.cards.BigCard; import mage.client.dialog.ShowCardsDialog; -import mage.remote.Session; import mage.view.PlayerView; /** @@ -108,11 +107,7 @@ public class PlayerPanel extends javax.swing.JPanel { btnPlayerName.setText("Player Name"); // NOI18N btnPlayerName.setName("btnPlayerName"); // NOI18N - btnPlayerName.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnPlayerNameActionPerformed(evt); - } - }); + btnPlayerName.addActionListener(evt -> btnPlayerNameActionPerformed(evt)); lblLife.setLabelFor(txtLife); lblLife.setText("Life:"); // NOI18N @@ -140,11 +135,7 @@ public class PlayerPanel extends javax.swing.JPanel { lblGrave.setName("lblGrave"); // NOI18N btnGrave.setName("btnGrave"); // NOI18N - btnGrave.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnGraveActionPerformed(evt); - } - }); + btnGrave.addActionListener(evt -> btnGraveActionPerformed(evt)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); diff --git a/Mage.Client/src/main/java/mage/client/util/DefaultActionCallback.java b/Mage.Client/src/main/java/mage/client/util/DefaultActionCallback.java index 9723a4b8c76..7a678e49be7 100644 --- a/Mage.Client/src/main/java/mage/client/util/DefaultActionCallback.java +++ b/Mage.Client/src/main/java/mage/client/util/DefaultActionCallback.java @@ -4,7 +4,6 @@ import java.awt.event.MouseEvent; import java.util.UUID; import mage.client.SessionHandler; -import mage.remote.Session; import mage.view.CardView; diff --git a/Mage.Client/src/main/java/mage/client/util/GameManager.java b/Mage.Client/src/main/java/mage/client/util/GameManager.java index 0a44fa14676..731a5c80658 100644 --- a/Mage.Client/src/main/java/mage/client/util/GameManager.java +++ b/Mage.Client/src/main/java/mage/client/util/GameManager.java @@ -8,7 +8,7 @@ import java.util.UUID; * @author nantuko */ public class GameManager { - private static GameManager fInstance = new GameManager(); + private static final GameManager fInstance = new GameManager(); public static GameManager getInstance() { return fInstance; diff --git a/Mage.Client/src/main/java/mage/client/util/ImageHelper.java b/Mage.Client/src/main/java/mage/client/util/ImageHelper.java index 17eb300b37d..64c727257fe 100644 --- a/Mage.Client/src/main/java/mage/client/util/ImageHelper.java +++ b/Mage.Client/src/main/java/mage/client/util/ImageHelper.java @@ -49,8 +49,8 @@ import org.mage.card.arcane.UI; */ public class ImageHelper { - protected static HashMap images = new HashMap<>(); - protected static HashMap backgrounds = new HashMap<>(); + protected static final HashMap images = new HashMap<>(); + protected static final HashMap backgrounds = new HashMap<>(); public static BufferedImage loadImage(String ref, int width, int height) { BufferedImage image = loadImage(ref); diff --git a/Mage.Client/src/main/java/mage/client/util/NaturalOrderComparator.java b/Mage.Client/src/main/java/mage/client/util/NaturalOrderComparator.java index 120df238c0d..6b1fb5e7123 100644 --- a/Mage.Client/src/main/java/mage/client/util/NaturalOrderComparator.java +++ b/Mage.Client/src/main/java/mage/client/util/NaturalOrderComparator.java @@ -181,7 +181,7 @@ public class NaturalOrderComparator implements Comparator System.out.println("Scrambled: " + scrambled); - Collections.sort(scrambled, new NaturalOrderComparator()); + scrambled.sort(new NaturalOrderComparator()); System.out.println("Sorted: " + scrambled); } diff --git a/Mage.Client/src/main/java/mage/client/util/SettingsManager.java b/Mage.Client/src/main/java/mage/client/util/SettingsManager.java index 1e87c5cea7b..990fa556eb6 100644 --- a/Mage.Client/src/main/java/mage/client/util/SettingsManager.java +++ b/Mage.Client/src/main/java/mage/client/util/SettingsManager.java @@ -10,7 +10,7 @@ import org.mage.card.arcane.CardPanel; * @author nantuko */ public class SettingsManager { - private static SettingsManager fInstance = new SettingsManager(); + private static final SettingsManager fInstance = new SettingsManager(); public static SettingsManager getInstance() { return fInstance; @@ -68,5 +68,5 @@ public class SettingsManager { private int screenWidth; private int screenHeight; - private Rectangle cardSize = CardPanel.CARD_SIZE_FULL; + private final Rectangle cardSize = CardPanel.CARD_SIZE_FULL; } diff --git a/Mage.Client/src/main/java/mage/client/util/TransformedImageCache.java b/Mage.Client/src/main/java/mage/client/util/TransformedImageCache.java index ef59199b983..285512c0725 100644 --- a/Mage.Client/src/main/java/mage/client/util/TransformedImageCache.java +++ b/Mage.Client/src/main/java/mage/client/util/TransformedImageCache.java @@ -68,27 +68,19 @@ public class TransformedImageCache { } } - static Map> IMAGE_CACHE; + static final Map> IMAGE_CACHE; static { // TODO: can we use a single map? - IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap(new Function>() { - @Override - public Map apply(final Key key) { - return new MapMaker().weakKeys().softValues().makeComputingMap(new Function() { - @Override - public BufferedImage apply(BufferedImage image) { - if (key.width != image.getWidth() || key.height != image.getHeight()) { - image = resizeImage(image, key.width, key.height); - } - if (key.angle != 0.0) { - image = rotateImage(image, key.angle); - } - return image; - } - }); + IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap((Function>) key -> new MapMaker().weakKeys().softValues().makeComputingMap(image -> { + if (key.width != image.getWidth() || key.height != image.getHeight()) { + image = resizeImage(image, key.width, key.height); } - })); + if (key.angle != 0.0) { + image = rotateImage(image, key.angle); + } + return image; + }))); } private static BufferedImage rotateImage(BufferedImage image, double angle) { diff --git a/Mage.Client/src/main/java/mage/client/util/audio/AudioGroup.java b/Mage.Client/src/main/java/mage/client/util/audio/AudioGroup.java index 7db982c7522..1cd97b9b23d 100644 --- a/Mage.Client/src/main/java/mage/client/util/audio/AudioGroup.java +++ b/Mage.Client/src/main/java/mage/client/util/audio/AudioGroup.java @@ -9,5 +9,5 @@ public enum AudioGroup { GameSounds, DraftSounds, SkipSounds, - OtherSounds; + OtherSounds } diff --git a/Mage.Client/src/main/java/mage/client/util/audio/LinePool.java b/Mage.Client/src/main/java/mage/client/util/audio/LinePool.java index f12a6d791eb..633b677a350 100644 --- a/Mage.Client/src/main/java/mage/client/util/audio/LinePool.java +++ b/Mage.Client/src/main/java/mage/client/util/audio/LinePool.java @@ -39,8 +39,8 @@ public class LinePool { * from the timer thread to prevent deadlocks in PulseAudio internals. */ - private Mixer mixer; - private int alwaysActive; + private final Mixer mixer; + private final int alwaysActive; public LinePool() { this(new AudioFormat(22050, 16, 1, true, false), 4, 1); diff --git a/Mage.Client/src/main/java/mage/client/util/audio/MusicPlayer.java b/Mage.Client/src/main/java/mage/client/util/audio/MusicPlayer.java index 4cae5b1bb1d..b823ad3ed0d 100644 --- a/Mage.Client/src/main/java/mage/client/util/audio/MusicPlayer.java +++ b/Mage.Client/src/main/java/mage/client/util/audio/MusicPlayer.java @@ -16,7 +16,7 @@ public class MusicPlayer { private static final Logger log = Logger.getLogger(AudioManager.class); String filepath; String filename; - List filelist = new List(); + final List filelist = new List(); static MusicPlayer player = null; //open file and add list @@ -138,11 +138,11 @@ public class MusicPlayer { breaked = false; } } - }; + } class PlayThread extends Thread { - byte tempBuffer[] = new byte[320]; + final byte[] tempBuffer = new byte[320]; public void run() { try { @@ -165,5 +165,5 @@ public class MusicPlayer { log.error("Thread error: " + e); } } - }; + } } diff --git a/Mage.Client/src/main/java/mage/client/util/gui/ArrowBuilder.java b/Mage.Client/src/main/java/mage/client/util/gui/ArrowBuilder.java index 89cb8a762ff..1f0c3d67643 100644 --- a/Mage.Client/src/main/java/mage/client/util/gui/ArrowBuilder.java +++ b/Mage.Client/src/main/java/mage/client/util/gui/ArrowBuilder.java @@ -12,7 +12,7 @@ import java.util.List; */ public class ArrowBuilder { - private static ArrowBuilder instance; + private static final ArrowBuilder instance; static { instance = new ArrowBuilder(); @@ -38,7 +38,7 @@ public class ArrowBuilder { private int currentHeight; public enum Type { - PAIRED, SOURCE, TARGET, COMBAT, ENCHANT_PLAYERS; + PAIRED, SOURCE, TARGET, COMBAT, ENCHANT_PLAYERS } /** @@ -103,16 +103,8 @@ public class ArrowBuilder { synchronized (map) { p.add(arrow); - Map> innerMap = map.get(gameId); - if (innerMap == null) { - innerMap = new HashMap>(); - map.put(gameId, innerMap); - } - java.util.List arrows = innerMap.get(type); - if (arrows == null) { - arrows = new ArrayList(); - innerMap.put(type, arrows); - } + Map> innerMap = map.computeIfAbsent(gameId, k -> new HashMap>()); + java.util.List arrows = innerMap.computeIfAbsent(type, k -> new ArrayList()); arrows.add(arrow); } diff --git a/Mage.Client/src/main/java/mage/client/util/gui/BufferedImageBuilder.java b/Mage.Client/src/main/java/mage/client/util/gui/BufferedImageBuilder.java index 0c75503dc97..cf71f462331 100644 --- a/Mage.Client/src/main/java/mage/client/util/gui/BufferedImageBuilder.java +++ b/Mage.Client/src/main/java/mage/client/util/gui/BufferedImageBuilder.java @@ -49,25 +49,19 @@ public class BufferedImageBuilder { private void waitForImage(BufferedImage bufferedImage) { final ImageLoadStatus imageLoadStatus = new ImageLoadStatus(); - bufferedImage.getHeight(new ImageObserver() { - @Override - public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { - if (infoflags == ALLBITS) { - imageLoadStatus.heightDone = true; - return true; - } - return false; + bufferedImage.getHeight((img, infoflags, x, y, width, height) -> { + if (infoflags == ImageObserver.ALLBITS) { + imageLoadStatus.heightDone = true; + return true; } + return false; }); - bufferedImage.getWidth(new ImageObserver() { - @Override - public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { - if (infoflags == ALLBITS) { - imageLoadStatus.widthDone = true; - return true; - } - return false; + bufferedImage.getWidth((img, infoflags, x, y, width, height) -> { + if (infoflags == ImageObserver.ALLBITS) { + imageLoadStatus.widthDone = true; + return true; } + return false; }); while (!imageLoadStatus.widthDone && !imageLoadStatus.heightDone) { try { diff --git a/Mage.Client/src/main/java/mage/client/util/gui/GuiDisplayUtil.java b/Mage.Client/src/main/java/mage/client/util/gui/GuiDisplayUtil.java index 8cc83f05895..081245971d7 100644 --- a/Mage.Client/src/main/java/mage/client/util/gui/GuiDisplayUtil.java +++ b/Mage.Client/src/main/java/mage/client/util/gui/GuiDisplayUtil.java @@ -156,8 +156,8 @@ public class GuiDisplayUtil { if (card.getMageObjectType().canHaveCounters()) { ArrayList counters = new ArrayList<>(); if (card instanceof PermanentView) { - if (((PermanentView) card).getCounters() != null) { - counters = new ArrayList<>(((PermanentView) card).getCounters()); + if (card.getCounters() != null) { + counters = new ArrayList<>(card.getCounters()); } } else if (card.getCounters() != null) { counters = new ArrayList<>(card.getCounters()); diff --git a/Mage.Client/src/main/java/mage/client/util/gui/MageDialogState.java b/Mage.Client/src/main/java/mage/client/util/gui/MageDialogState.java index 13a48e25b1c..1c272674e0c 100644 --- a/Mage.Client/src/main/java/mage/client/util/gui/MageDialogState.java +++ b/Mage.Client/src/main/java/mage/client/util/gui/MageDialogState.java @@ -37,9 +37,9 @@ import mage.client.dialog.MageDialog; */ public class MageDialogState { - Dimension dimension; - int xPos; - int yPos; + final Dimension dimension; + final int xPos; + final int yPos; public MageDialogState(MageDialog mageDialog) { this.dimension = mageDialog.getSize(); diff --git a/Mage.Client/src/main/java/mage/client/util/gui/TableSpinnerEditor.java b/Mage.Client/src/main/java/mage/client/util/gui/TableSpinnerEditor.java index 12f22edcd12..d7f239d770e 100644 --- a/Mage.Client/src/main/java/mage/client/util/gui/TableSpinnerEditor.java +++ b/Mage.Client/src/main/java/mage/client/util/gui/TableSpinnerEditor.java @@ -28,8 +28,6 @@ package mage.client.util.gui; import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; @@ -50,9 +48,9 @@ import mage.client.cards.CardsList; */ public class TableSpinnerEditor extends DefaultCellEditor { - JSpinner spinner; - JSpinner.DefaultEditor editor; - JTextField textField; + final JSpinner spinner; + final JSpinner.DefaultEditor editor; + final JTextField textField; boolean valueSet; private JTable table; private int lastRow = -1; @@ -60,7 +58,7 @@ public class TableSpinnerEditor extends DefaultCellEditor { private int lastOriginalHeigh; private int currentOriginalHeigh; private static final int NEEDED_HIGH = 24; - CardsList cardsList; + final CardsList cardsList; // Initializes the spinner. public TableSpinnerEditor(CardsList cardsList) { @@ -83,12 +81,9 @@ public class TableSpinnerEditor extends DefaultCellEditor { table.setRowHeight(lastRow, NEEDED_HIGH); } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (valueSet) { - textField.setCaretPosition(1); - } + SwingUtilities.invokeLater(() -> { + if (valueSet) { + textField.setCaretPosition(1); } }); } @@ -101,12 +96,7 @@ public class TableSpinnerEditor extends DefaultCellEditor { } } }); - textField.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent ae) { - stopCellEditing(); - } - }); + textField.addActionListener(ae -> stopCellEditing()); } private synchronized void resetRow() { @@ -129,12 +119,7 @@ public class TableSpinnerEditor extends DefaultCellEditor { if (!valueSet) { spinner.setValue(value); } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - textField.requestFocus(); - } - }); + SwingUtilities.invokeLater(() -> textField.requestFocus()); return spinner; } diff --git a/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryCellRenderer.java b/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryCellRenderer.java index ed4c03a41f8..e63d78f56b8 100644 --- a/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryCellRenderer.java +++ b/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryCellRenderer.java @@ -42,7 +42,7 @@ public class CountryCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (value == null || ((String) value).isEmpty()) { - value = (String) "world"; + value = "world"; } label.setToolTipText(CountryUtil.getCountryName((String) value)); label.setIcon(CountryUtil.getCountryFlagIcon((String) value)); diff --git a/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryComboBox.java b/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryComboBox.java index 5fee4088d09..b054146b7fc 100644 --- a/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryComboBox.java +++ b/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryComboBox.java @@ -40,7 +40,7 @@ public class CountryComboBox extends JComboBox { private final DefaultComboBoxModel model; - public static String[][] countryList = { + public static final String[][] countryList = { {"Afghanistan", "af"}, {"Åland Islands", "ax"}, {"Albania", "al"}, diff --git a/Mage.Client/src/main/java/mage/client/util/sets/ConstructedFormats.java b/Mage.Client/src/main/java/mage/client/util/sets/ConstructedFormats.java index c7bda50e95f..a208a8b7abd 100644 --- a/Mage.Client/src/main/java/mage/client/util/sets/ConstructedFormats.java +++ b/Mage.Client/src/main/java/mage/client/util/sets/ConstructedFormats.java @@ -1,8 +1,6 @@ package mage.client.util.sets; import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; @@ -26,9 +24,7 @@ public class ConstructedFormats { public static final String FRONTIER = "- Frontier"; public static final String MODERN = "- Modern"; public static final String VINTAGE_LEGACY = "- Vintage / Legacy"; - ; public static final String CUSTOM = "- Custom"; - ; public static final Standard STANDARD_CARDS = new Standard(); private static final Map> underlyingSetCodesPerFormat = new HashMap<>(); @@ -99,9 +95,7 @@ public class ConstructedFormats { // Create the Block formats if (set.getType().equals(SetType.EXPANSION) && set.getBlockName() != null) { String blockDisplayName = getBlockDisplayName(set.getBlockName()); - if (underlyingSetCodesPerFormat.get(blockDisplayName) == null) { - underlyingSetCodesPerFormat.put(blockDisplayName, new ArrayList<>()); - } + underlyingSetCodesPerFormat.computeIfAbsent(blockDisplayName, k -> new ArrayList<>()); underlyingSetCodesPerFormat.get(blockDisplayName).add(set.getCode()); @@ -117,9 +111,7 @@ public class ConstructedFormats { } if (set.getType().equals(SetType.SUPPLEMENTAL) && set.getBlockName() != null) { - if (expansionInfo.get(set.getBlockName()) == null) { - expansionInfo.put(set.getBlockName(), set); - } + expansionInfo.putIfAbsent(set.getBlockName(), set); if (expansionInfo.get(set.getBlockName()).getReleaseDate().before(set.getReleaseDate())) { expansionInfo.put(set.getBlockName(), set); @@ -127,89 +119,84 @@ public class ConstructedFormats { } } - Collections.sort(formats, new Comparator() { - - @Override - public int compare(String name1, String name2) { - ExpansionInfo expansionInfo1 = expansionInfo.get(name1); - ExpansionInfo expansionInfo2 = expansionInfo.get(name2); - - if (expansionInfo1.getType().compareTo(expansionInfo2.getType()) == 0) { - SetType setType = expansionInfo1.getType(); - switch (setType) { - case EXPANSION: - if (expansionInfo1.getBlockName() == null) { - if (expansionInfo2.getBlockName() == null) { - return expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()); - } - - return 1; - } + formats.sort((name1, name2) -> { + ExpansionInfo expansionInfo1 = expansionInfo.get(name1); + ExpansionInfo expansionInfo2 = expansionInfo.get(name2); + if (expansionInfo1.getType().compareTo(expansionInfo2.getType()) == 0) { + SetType setType = expansionInfo1.getType(); + switch (setType) { + case EXPANSION: + if (expansionInfo1.getBlockName() == null) { if (expansionInfo2.getBlockName() == null) { - return -1; - } - - //Block comparison - if (name1.endsWith("Block") && name2.endsWith("Block")) { return expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()); } - if (name1.endsWith("Block")) { - if (expansionInfo1.getBlockName().equals(expansionInfo2.getBlockName())) { - return -1; - } - } + return 1; + } - if (name2.endsWith("Block")) { - if (expansionInfo1.getBlockName().equals(expansionInfo2.getBlockName())) { - return 1; - } - } + if (expansionInfo2.getBlockName() == null) { + return -1; + } + //Block comparison + if (name1.endsWith("Block") && name2.endsWith("Block")) { return expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()); - case SUPPLEMENTAL: - if (expansionInfo1.getBlockName() == null) { - if (expansionInfo2.getBlockName() == null) { - return expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()); - } - - return -1; - } - - if (expansionInfo2.getBlockName() == null) { - return 1; - } + } + if (name1.endsWith("Block")) { if (expansionInfo1.getBlockName().equals(expansionInfo2.getBlockName())) { - //If release date is the same, sort alphabetically. - if (expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()) == 0) { - return name1.compareTo(name2); - } + return -1; + } + } + + if (name2.endsWith("Block")) { + if (expansionInfo1.getBlockName().equals(expansionInfo2.getBlockName())) { + return 1; + } + } + + return expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()); + case SUPPLEMENTAL: + if (expansionInfo1.getBlockName() == null) { + if (expansionInfo2.getBlockName() == null) { return expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()); } - if (expansionInfo1.getBlockName().startsWith("Duel Decks")) { - if (expansionInfo1.getBlockName().startsWith("Duel Decks: Anthology")) { - return 1; - } + return -1; + } + + if (expansionInfo2.getBlockName() == null) { + return 1; + } + + if (expansionInfo1.getBlockName().equals(expansionInfo2.getBlockName())) { + //If release date is the same, sort alphabetically. + if (expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()) == 0) { + return name1.compareTo(name2); + } + return expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()); + } + + if (expansionInfo1.getBlockName().startsWith("Duel Decks")) { + if (expansionInfo1.getBlockName().startsWith("Duel Decks: Anthology")) { return 1; } - if (expansionInfo2.getBlockName().startsWith("Duel Decks")) { - return -1; - } + return 1; + } + if (expansionInfo2.getBlockName().startsWith("Duel Decks")) { + return -1; + } - ExpansionInfo blockInfo1 = expansionInfo.get(expansionInfo1.getBlockName()); - ExpansionInfo blockInfo2 = expansionInfo.get(expansionInfo2.getBlockName()); + ExpansionInfo blockInfo1 = expansionInfo.get(expansionInfo1.getBlockName()); + ExpansionInfo blockInfo2 = expansionInfo.get(expansionInfo2.getBlockName()); - return blockInfo2.getReleaseDate().compareTo(blockInfo1.getReleaseDate()); - default: - return expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()); - } + return blockInfo2.getReleaseDate().compareTo(blockInfo1.getReleaseDate()); + default: + return expansionInfo2.getReleaseDate().compareTo(expansionInfo1.getReleaseDate()); } - return expansionInfo1.getType().compareTo(expansionInfo2.getType()); } - + return expansionInfo1.getType().compareTo(expansionInfo2.getType()); }); if (!formats.isEmpty()) { formats.add(0, CUSTOM); @@ -224,10 +211,7 @@ public class ConstructedFormats { } private static String getBlockDisplayName(String blockName) { - StringBuilder builder = new StringBuilder(); - builder.append("* ").append(blockName).append(" Block"); - - return builder.toString(); + return "* " + blockName + " Block"; } // Attention -Month is 0 Based so Feb = 1 for example. private static final Date extendedDate = new GregorianCalendar(2009, 7, 20).getTime(); diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/Animation.java b/Mage.Client/src/main/java/org/mage/card/arcane/Animation.java index ea69e5cc6e1..34a44b66e2a 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/Animation.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/Animation.java @@ -8,11 +8,11 @@ import mage.cards.MagePermanent; public abstract class Animation { - private static boolean ENABLED = true; + private static final boolean ENABLED = true; private static final long TARGET_MILLIS_PER_FRAME = 30; - private static Timer timer = new Timer("Animation", true); + private static final Timer timer = new Timer("Animation", true); private static CardPanel enlargedCardPanel; private static CardPanel enlargedAnimationPanel; @@ -28,13 +28,10 @@ public abstract class Animation { public Animation(final long duration, long delay) { if (!ENABLED) { - UI.invokeLater(new Runnable() { - @Override - public void run() { - start(); - //update(1.0f); - end(); - } + UI.invokeLater(() -> { + start(); + //update(1.0f); + end(); }); return; } @@ -82,7 +79,7 @@ public abstract class Animation { private static final int SAMPLES = 6; private static final long MAX_FRAME = 100; // Max time for one frame, to weed out spikes. - private long samples[] = new long[SAMPLES]; + private final long[] samples = new long[SAMPLES]; private int sampleIndex; public FrameTimer() { @@ -202,117 +199,105 @@ public abstract class Animation { public static void moveCardToPlay(final int startX, final int startY, final int startWidth, final int endX, final int endY, final int endWidth, final CardPanel animationPanel, final CardPanel placeholder, final JLayeredPane layeredPane, final int speed) { - UI.invokeLater(new Runnable() { - @Override - public void run() { - final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO); - final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO); - final float a = 2f; - final float sqrta = (float) Math.sqrt(1 / a); + UI.invokeLater(() -> { + final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO); + final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO); + final float a = 2f; + final float sqrta = (float) Math.sqrt(1 / a); - animationPanel.setCardBounds(startX, startY, startWidth, startHeight); - animationPanel.setAnimationPanel(true); - Container parent = animationPanel.getParent(); - if (parent != null && !parent.equals(layeredPane)) { - layeredPane.add(animationPanel); - layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER); + animationPanel.setCardBounds(startX, startY, startWidth, startHeight); + animationPanel.setAnimationPanel(true); + Container parent = animationPanel.getParent(); + if (parent != null && !parent.equals(layeredPane)) { + layeredPane.add(animationPanel); + layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER); + } + + new Animation(700) { + @Override + protected void update(float percentage) { + float percent = percentage; + if (placeholder != null && !placeholder.isShowing()) { + cancel(); + return; + } + int currentX = startX + Math.round((endX - startX + endWidth / 2f) * percent); + int currentY = startY + Math.round((endY - startY + endHeight / 2f) * percent); + int currentWidth, currentHeight; + int midWidth = Math.max(200, endWidth * 2); + int midHeight = Math.round(midWidth * CardPanel.ASPECT_RATIO); + if (percent <= 0.5f) { + percent = percent * 2; + float pp = sqrta * (1 - percent); + percent = 1 - a * pp * pp; + currentWidth = startWidth + Math.round((midWidth - startWidth) * percent); + currentHeight = startHeight + Math.round((midHeight - startHeight) * percent); + } else { + percent = (percent - 0.5f) * 2; + float pp = sqrta * percent; + percent = a * pp * pp; + currentWidth = midWidth + Math.round((endWidth - midWidth) * percent); + currentHeight = midHeight + Math.round((endHeight - midHeight) * percent); + } + currentX -= currentWidth / 2; + currentY -= currentHeight / 2; + animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight); } - new Animation(700) { - @Override - protected void update(float percentage) { - float percent = percentage; - if (placeholder != null && !placeholder.isShowing()) { - cancel(); - return; + @Override + protected void end() { + EventQueue.invokeLater(() -> { + if (placeholder != null) { + placeholder.setDisplayEnabled(true); + placeholder.transferResources(animationPanel); } - int currentX = startX + Math.round((endX - startX + endWidth / 2f) * percent); - int currentY = startY + Math.round((endY - startY + endHeight / 2f) * percent); - int currentWidth, currentHeight; - int midWidth = Math.max(200, endWidth * 2); - int midHeight = Math.round(midWidth * CardPanel.ASPECT_RATIO); - if (percent <= 0.5f) { - percent = percent * 2; - float pp = sqrta * (1 - percent); - percent = 1 - a * pp * pp; - currentWidth = startWidth + Math.round((midWidth - startWidth) * percent); - currentHeight = startHeight + Math.round((midHeight - startHeight) * percent); - } else { - percent = (percent - 0.5f) * 2; - float pp = sqrta * percent; - percent = a * pp * pp; - currentWidth = midWidth + Math.round((endWidth - midWidth) * percent); - currentHeight = midHeight + Math.round((endHeight - midHeight) * percent); - } - currentX -= currentWidth / 2; - currentY -= currentHeight / 2; - animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight); - } - - @Override - protected void end() { - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - if (placeholder != null) { - placeholder.setDisplayEnabled(true); - placeholder.transferResources(animationPanel); - } - animationPanel.setVisible(false); - animationPanel.repaint(); - layeredPane.remove(animationPanel); - } - }); - } - }; - } + animationPanel.setVisible(false); + animationPanel.repaint(); + layeredPane.remove(animationPanel); + }); + } + }; }); } public static void moveCard(final int startX, final int startY, final int startWidth, final int endX, final int endY, final int endWidth, final CardPanel animationPanel, final CardPanel placeholder, final JLayeredPane layeredPane, final int speed) { - UI.invokeLater(new Runnable() { - @Override - public void run() { - final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO); - final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO); + UI.invokeLater(() -> { + final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO); + final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO); - animationPanel.setCardBounds(startX, startY, startWidth, startHeight); - animationPanel.setAnimationPanel(true); - Container parent = animationPanel.getParent(); - if (parent != null && !parent.equals(layeredPane)) { - layeredPane.add(animationPanel); - layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER); + animationPanel.setCardBounds(startX, startY, startWidth, startHeight); + animationPanel.setAnimationPanel(true); + Container parent = animationPanel.getParent(); + if (parent != null && !parent.equals(layeredPane)) { + layeredPane.add(animationPanel); + layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER); + } + + new Animation(speed) { + @Override + protected void update(float percentage) { + int currentX = startX + Math.round((endX - startX) * percentage); + int currentY = startY + Math.round((endY - startY) * percentage); + int currentWidth = startWidth + Math.round((endWidth - startWidth) * percentage); + int currentHeight = startHeight + Math.round((endHeight - startHeight) * percentage); + animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight); } - new Animation(speed) { - @Override - protected void update(float percentage) { - int currentX = startX + Math.round((endX - startX) * percentage); - int currentY = startY + Math.round((endY - startY) * percentage); - int currentWidth = startWidth + Math.round((endWidth - startWidth) * percentage); - int currentHeight = startHeight + Math.round((endHeight - startHeight) * percentage); - animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight); - } - - @Override - protected void end() { - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - if (placeholder != null) { - placeholder.setDisplayEnabled(true); - placeholder.transferResources(animationPanel); - } - animationPanel.setVisible(false); - animationPanel.repaint(); - layeredPane.remove(animationPanel); - } - }); - } - }; - } + @Override + protected void end() { + EventQueue.invokeLater(() -> { + if (placeholder != null) { + placeholder.setDisplayEnabled(true); + placeholder.transferResources(animationPanel); + } + animationPanel.setVisible(false); + animationPanel.repaint(); + layeredPane.remove(animationPanel); + }); + } + }; }); } @@ -357,12 +342,7 @@ public abstract class Animation { protected void end() { animationPanel.setVisible(false); animationPanel.repaint(); - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - layeredPane.remove(animationPanel); - } - }); + EventQueue.invokeLater(() -> layeredPane.remove(animationPanel)); } }; } diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/CardPanel.java b/Mage.Client/src/main/java/org/mage/card/arcane/CardPanel.java index a26d25c7cac..fd329f538dc 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/CardPanel.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/CardPanel.java @@ -6,7 +6,6 @@ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; @@ -72,7 +71,7 @@ public abstract class CardPanel extends MagePermanent implements MouseListener, private final List links = new ArrayList<>(); - public JPanel buttonPanel; + public final JPanel buttonPanel; private JButton dayNightButton; private JButton showCopySourceButton; @@ -89,11 +88,11 @@ public abstract class CardPanel extends MagePermanent implements MouseListener, private ActionCallback callback; protected boolean tooltipShowing; - protected TextPopup tooltipText; + protected final TextPopup tooltipText; protected UUID gameId; private TransferData data = new TransferData(); - private boolean isPermanent; + private final boolean isPermanent; private boolean hasSickness; private String zone; @@ -139,17 +138,14 @@ public abstract class CardPanel extends MagePermanent implements MouseListener, dayNightButton.setToolTipText("This permanent is a double faced card. To see the back face card, push this button or turn mouse wheel down while hovering with the mouse pointer over the permanent."); BufferedImage day = ImageManagerImpl.getInstance().getDayImage(); dayNightButton.setIcon(new ImageIcon(day)); - dayNightButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // if card is being rotated, ignore action performed - // if card is tapped, no visual transforming is possible (implementation limitation) - // if card is permanent, it will be rotated by Mage, so manual rotate should be possible - if (animationInProgress || isTapped() || isPermanent) { - return; - } - Animation.transformCard(CardPanel.this, CardPanel.this, true); + dayNightButton.addActionListener(e -> { + // if card is being rotated, ignore action performed + // if card is tapped, no visual transforming is possible (implementation limitation) + // if card is permanent, it will be rotated by Mage, so manual rotate should be possible + if (animationInProgress || isTapped() || isPermanent) { + return; } + Animation.transformCard(CardPanel.this, CardPanel.this, true); }); // Add it @@ -164,12 +160,9 @@ public abstract class CardPanel extends MagePermanent implements MouseListener, showCopySourceButton.setToolTipText("This permanent is copying a target. To see original card, push this button or turn mouse wheel down while hovering with the mouse pointer over the permanent."); showCopySourceButton.setVisible(((PermanentView) this.gameCard).isCopy()); showCopySourceButton.setIcon(new ImageIcon(ImageManagerImpl.getInstance().getCopyInformIconImage())); - showCopySourceButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ActionCallback callback = Plugins.getInstance().getActionCallback(); - ((MageActionCallback) callback).enlargeCard(EnlargeMode.COPY); - } + showCopySourceButton.addActionListener(e -> { + ActionCallback callback1 = Plugins.getInstance().getActionCallback(); + ((MageActionCallback) callback1).enlargeCard(EnlargeMode.COPY); }); // Add it diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/CardPanelComponentImpl.java b/Mage.Client/src/main/java/org/mage/card/arcane/CardPanelComponentImpl.java index 4003eaa7a29..827ecc70a5b 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/CardPanelComponentImpl.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/CardPanelComponentImpl.java @@ -179,12 +179,7 @@ public class CardPanelComponentImpl extends CardPanel { } static { - IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap(new Function() { - @Override - public BufferedImage apply(Key key) { - return createImage(key); - } - })); + IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap((Function) key -> createImage(key))); } public CardPanelComponentImpl(CardView newGameCard, UUID gameId, final boolean loadImage, ActionCallback callback, final boolean foil, Dimension dimension) { @@ -472,7 +467,7 @@ public class CardPanelComponentImpl extends CardPanel { ptText.setVisible(showText); if (showText) { - int fontSize = (int) cardHeight / 11; + int fontSize = cardHeight / 11; titleText.setFont(getFont().deriveFont(Font.BOLD, fontSize)); int titleX = Math.round(cardWidth * (20f / 480)); @@ -533,33 +528,27 @@ public class CardPanelComponentImpl extends CardPanel { //final CardView gameCard = this.gameCard; final int stamp = ++updateArtImageStamp; - Util.threadPool.submit(new Runnable() { - @Override - public void run() { - try { - final BufferedImage srcImage; - if (gameCard.isFaceDown()) { - srcImage = getFaceDownImage(); - } else if (getCardWidth() > THUMBNAIL_SIZE_FULL.width) { - srcImage = ImageCache.getImage(gameCard, getCardWidth(), getCardHeight()); - } else { - srcImage = ImageCache.getThumbnail(gameCard); - } - UI.invokeLater(new Runnable() { - @Override - public void run() { - if (stamp == updateArtImageStamp) { - hasImage = srcImage != null; - setText(gameCard); - setImage(srcImage); - } - } - }); - } catch (Exception e) { - e.printStackTrace(); - } catch (Error err) { - err.printStackTrace(); + Util.threadPool.submit(() -> { + try { + final BufferedImage srcImage; + if (gameCard.isFaceDown()) { + srcImage = getFaceDownImage(); + } else if (getCardWidth() > THUMBNAIL_SIZE_FULL.width) { + srcImage = ImageCache.getImage(gameCard, getCardWidth(), getCardHeight()); + } else { + srcImage = ImageCache.getThumbnail(gameCard); } + UI.invokeLater(() -> { + if (stamp == updateArtImageStamp) { + hasImage = srcImage != null; + setText(gameCard); + setImage(srcImage); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } catch (Error err) { + err.printStackTrace(); } }); } diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/CardPanelRenderImpl.java b/Mage.Client/src/main/java/org/mage/card/arcane/CardPanelRenderImpl.java index 05bc713a8b4..5d7a5362eb3 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/CardPanelRenderImpl.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/CardPanelRenderImpl.java @@ -260,13 +260,9 @@ public class CardPanelRenderImpl extends CardPanel { = new ImageKey(gameCard, artImage, getCardWidth(), getCardHeight(), isChoosable(), isSelected()); - cardImage = IMAGE_CACHE.get(key); + cardImage = IMAGE_CACHE.computeIfAbsent(key, k -> renderCard()); // No cached copy exists? Render one and cache it - if (cardImage == null) { - cardImage = renderCard(); - IMAGE_CACHE.put(key, cardImage); - } } // And draw the image we now have @@ -324,39 +320,33 @@ public class CardPanelRenderImpl extends CardPanel { // Submit a task to draw with the card art when it arrives if (artImage == null) { final int stamp = ++updateArtImageStamp; - Util.threadPool.submit(new Runnable() { - @Override - public void run() { - try { - final BufferedImage srcImage; - if (gameCard.isFaceDown()) { - // Nothing to do - srcImage = null; - } else if (getCardWidth() > THUMBNAIL_SIZE_FULL.width) { - srcImage = ImageCache.getImage(gameCard, getCardWidth(), getCardHeight()); - } else { - srcImage = ImageCache.getThumbnail(gameCard); - } - - UI.invokeLater(new Runnable() { - @Override - public void run() { - if (stamp == updateArtImageStamp) { - artImage = srcImage; - cardRenderer.setArtImage(srcImage); - if (srcImage != null) { - // Invalidate and repaint - cardImage = null; - repaint(); - } - } - } - }); - } catch (Exception e) { - e.printStackTrace(); - } catch (Error err) { - err.printStackTrace(); + Util.threadPool.submit(() -> { + try { + final BufferedImage srcImage; + if (gameCard.isFaceDown()) { + // Nothing to do + srcImage = null; + } else if (getCardWidth() > THUMBNAIL_SIZE_FULL.width) { + srcImage = ImageCache.getImage(gameCard, getCardWidth(), getCardHeight()); + } else { + srcImage = ImageCache.getThumbnail(gameCard); } + + UI.invokeLater(() -> { + if (stamp == updateArtImageStamp) { + artImage = srcImage; + cardRenderer.setArtImage(srcImage); + if (srcImage != null) { + // Invalidate and repaint + cardImage = null; + repaint(); + } + } + }); + } catch (Exception e) { + e.printStackTrace(); + } catch (Error err) { + err.printStackTrace(); } }); } diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/CardRenderer.java b/Mage.Client/src/main/java/org/mage/card/arcane/CardRenderer.java index 3e29d6f30ce..64b23245c84 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/CardRenderer.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/CardRenderer.java @@ -15,7 +15,6 @@ import java.awt.Polygon; import java.awt.image.BufferedImage; import java.util.ArrayList; -import mage.abilities.Ability; import mage.client.dialog.PreferencesDialog; import mage.constants.AbilityType; import mage.constants.CardType; @@ -96,7 +95,7 @@ public abstract class CardRenderer { }, 4); // Paint for a card back - public static Paint BG_TEXTURE_CARDBACK = new Color(153, 102, 51); + public static final Paint BG_TEXTURE_CARDBACK = new Color(153, 102, 51); // The size of the card protected int cardWidth; @@ -107,18 +106,18 @@ public abstract class CardRenderer { protected boolean isSelected; // Radius of the corners of the cards - protected static float CORNER_RADIUS_FRAC = 0.1f; //x cardWidth - protected static int CORNER_RADIUS_MIN = 3; + protected static final float CORNER_RADIUS_FRAC = 0.1f; //x cardWidth + protected static final int CORNER_RADIUS_MIN = 3; protected int cornerRadius; // The inset of the actual card from the black / white border around it - protected static float BORDER_WIDTH_FRAC = 0.03f; //x cardWidth - protected static float BORDER_WIDTH_MIN = 2; + protected static final float BORDER_WIDTH_FRAC = 0.03f; //x cardWidth + protected static final float BORDER_WIDTH_MIN = 2; protected int borderWidth; // The parsed text of the card - protected ArrayList textboxRules = new ArrayList<>(); - protected ArrayList textboxKeywords = new ArrayList<>(); + protected final ArrayList textboxRules = new ArrayList<>(); + protected final ArrayList textboxKeywords = new ArrayList<>(); // The Construtor // The constructor should prepare all of the things that it can @@ -271,14 +270,19 @@ public abstract class CardRenderer { // Don't render loyalty, we do that in the bottom corner if (!v.getName().equals("loyalty")) { Polygon p; - if (v.getName().equals("+1/+1")) { - p = PLUS_COUNTER_POLY; - } else if (v.getName().equals("-1/-1")) { - p = MINUS_COUNTER_POLY; - } else if (v.getName().equals("time")) { - p = TIME_COUNTER_POLY; - } else { - p = OTHER_COUNTER_POLY; + switch (v.getName()) { + case "+1/+1": + p = PLUS_COUNTER_POLY; + break; + case "-1/-1": + p = MINUS_COUNTER_POLY; + break; + case "time": + p = TIME_COUNTER_POLY; + break; + default: + p = OTHER_COUNTER_POLY; + break; } double scale = (0.1 * 0.25 * cardWidth); Graphics2D g2 = (Graphics2D) g.create(); diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/CardRendererUtils.java b/Mage.Client/src/main/java/org/mage/card/arcane/CardRendererUtils.java index bede760f806..628ecd66c0e 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/CardRendererUtils.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/CardRendererUtils.java @@ -85,9 +85,9 @@ public class CardRendererUtils { // Abbreviate a piece of rules text, making substitutions to decrease its // length. Also abbreviate reminder text. - private static Pattern abbreviationPattern; - private static Map abbreviations = new HashMap(); - private static Pattern killReminderTextPattern; + private static final Pattern abbreviationPattern; + private static final Map abbreviations = new HashMap(); + private static final Pattern killReminderTextPattern; static { // Available abbreviations abbreviations.put("enters the battlefield", "ETB"); diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/GlowText.java b/Mage.Client/src/main/java/org/mage/card/arcane/GlowText.java index 77122b0d9cf..bc7ac1617d0 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/GlowText.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/GlowText.java @@ -125,12 +125,7 @@ public class GlowText extends JLabel { } static { - IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap(new Function() { - @Override - public BufferedImage apply(Key key) { - return createImage(key); - } - })); + IMAGE_CACHE = ImageCaches.register(new MapMaker().softValues().makeComputingMap((Function) GlowText::createImage)); } public void setGlow(Color glowColor, int size, float intensity) { diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/ManaSymbols.java b/Mage.Client/src/main/java/org/mage/card/arcane/ManaSymbols.java index 7052fdb277b..d1e37c6034f 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/ManaSymbols.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/ManaSymbols.java @@ -228,7 +228,7 @@ public class ManaSymbols { manaCost = UI.getDisplayManaCost(manaCost); StringTokenizer tok = new StringTokenizer(manaCost, " "); while (tok.hasMoreTokens()) { - String symbol = tok.nextToken().substring(0); + String symbol = tok.nextToken(); // Check and load symbol in the width Image image = sizedSymbols.get(symbol); if (image == null) { diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/ModernCardRenderer.java b/Mage.Client/src/main/java/org/mage/card/arcane/ModernCardRenderer.java index 8a04b6148e9..6cad41a0940 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/ModernCardRenderer.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/ModernCardRenderer.java @@ -87,65 +87,65 @@ public class ModernCardRenderer extends CardRenderer { } return new Font("Arial", Font.PLAIN, 1); } - public static Font BASE_BELEREN_FONT = loadFont("beleren-bold"); + public static final Font BASE_BELEREN_FONT = loadFont("beleren-bold"); - public static Paint BG_TEXTURE_WHITE = loadBackgroundTexture("white"); - public static Paint BG_TEXTURE_BLUE = loadBackgroundTexture("blue"); - public static Paint BG_TEXTURE_BLACK = loadBackgroundTexture("black"); - public static Paint BG_TEXTURE_RED = loadBackgroundTexture("red"); - public static Paint BG_TEXTURE_GREEN = loadBackgroundTexture("green"); - public static Paint BG_TEXTURE_GOLD = loadBackgroundTexture("gold"); - public static Paint BG_TEXTURE_ARTIFACT = loadBackgroundTexture("artifact"); - public static Paint BG_TEXTURE_LAND = loadBackgroundTexture("land"); - public static Paint BG_TEXTURE_VEHICLE = loadBackgroundTexture("vehicle"); + public static final Paint BG_TEXTURE_WHITE = loadBackgroundTexture("white"); + public static final Paint BG_TEXTURE_BLUE = loadBackgroundTexture("blue"); + public static final Paint BG_TEXTURE_BLACK = loadBackgroundTexture("black"); + public static final Paint BG_TEXTURE_RED = loadBackgroundTexture("red"); + public static final Paint BG_TEXTURE_GREEN = loadBackgroundTexture("green"); + public static final Paint BG_TEXTURE_GOLD = loadBackgroundTexture("gold"); + public static final Paint BG_TEXTURE_ARTIFACT = loadBackgroundTexture("artifact"); + public static final Paint BG_TEXTURE_LAND = loadBackgroundTexture("land"); + public static final Paint BG_TEXTURE_VEHICLE = loadBackgroundTexture("vehicle"); - public static BufferedImage FRAME_INVENTION = loadFramePart("invention_frame"); + public static final BufferedImage FRAME_INVENTION = loadFramePart("invention_frame"); - public static Color BORDER_WHITE = new Color(216, 203, 188); - public static Color BORDER_BLUE = new Color(20, 121, 175); - public static Color BORDER_BLACK = new Color(45, 45, 35); - public static Color BORDER_RED = new Color(201, 71, 58); - public static Color BORDER_GREEN = new Color(4, 136, 69); - public static Color BORDER_GOLD = new Color(255, 228, 124); - public static Color BORDER_COLORLESS = new Color(238, 242, 242); - public static Color BORDER_LAND = new Color(190, 173, 115); + public static final Color BORDER_WHITE = new Color(216, 203, 188); + public static final Color BORDER_BLUE = new Color(20, 121, 175); + public static final Color BORDER_BLACK = new Color(45, 45, 35); + public static final Color BORDER_RED = new Color(201, 71, 58); + public static final Color BORDER_GREEN = new Color(4, 136, 69); + public static final Color BORDER_GOLD = new Color(255, 228, 124); + public static final Color BORDER_COLORLESS = new Color(238, 242, 242); + public static final Color BORDER_LAND = new Color(190, 173, 115); - public static Color BOX_WHITE = new Color(244, 245, 239); - public static Color BOX_BLUE = new Color(201, 223, 237); - public static Color BOX_BLACK = new Color(204, 194, 192); - public static Color BOX_RED = new Color(246, 208, 185); - public static Color BOX_GREEN = new Color(205, 221, 213); - public static Color BOX_GOLD = new Color(223, 195, 136); - public static Color BOX_COLORLESS = new Color(220, 228, 232); - public static Color BOX_LAND = new Color(220, 215, 213); - public static Color BOX_INVENTION = new Color(209, 97, 33); - public static Color BOX_VEHICLE = new Color(155, 105, 60); + public static final Color BOX_WHITE = new Color(244, 245, 239); + public static final Color BOX_BLUE = new Color(201, 223, 237); + public static final Color BOX_BLACK = new Color(204, 194, 192); + public static final Color BOX_RED = new Color(246, 208, 185); + public static final Color BOX_GREEN = new Color(205, 221, 213); + public static final Color BOX_GOLD = new Color(223, 195, 136); + public static final Color BOX_COLORLESS = new Color(220, 228, 232); + public static final Color BOX_LAND = new Color(220, 215, 213); + public static final Color BOX_INVENTION = new Color(209, 97, 33); + public static final Color BOX_VEHICLE = new Color(155, 105, 60); - public static Color BOX_WHITE_NIGHT = new Color(169, 160, 145); - public static Color BOX_BLUE_NIGHT = new Color(46, 133, 176); - public static Color BOX_BLACK_NIGHT = new Color(95, 90, 89); - public static Color BOX_RED_NIGHT = new Color(188, 87, 57); - public static Color BOX_GREEN_NIGHT = new Color(31, 100, 44); - public static Color BOX_GOLD_NIGHT = new Color(171, 134, 70); - public static Color BOX_COLORLESS_NIGHT = new Color(118, 147, 158); + public static final Color BOX_WHITE_NIGHT = new Color(169, 160, 145); + public static final Color BOX_BLUE_NIGHT = new Color(46, 133, 176); + public static final Color BOX_BLACK_NIGHT = new Color(95, 90, 89); + public static final Color BOX_RED_NIGHT = new Color(188, 87, 57); + public static final Color BOX_GREEN_NIGHT = new Color(31, 100, 44); + public static final Color BOX_GOLD_NIGHT = new Color(171, 134, 70); + public static final Color BOX_COLORLESS_NIGHT = new Color(118, 147, 158); - public static Color LAND_TEXTBOX_WHITE = new Color(248, 232, 188, 244); - public static Color LAND_TEXTBOX_BLUE = new Color(189, 212, 236, 244); - public static Color LAND_TEXTBOX_BLACK = new Color(174, 164, 162, 244); - public static Color LAND_TEXTBOX_RED = new Color(242, 168, 133, 244); - public static Color LAND_TEXTBOX_GREEN = new Color(198, 220, 198, 244); - public static Color LAND_TEXTBOX_GOLD = new Color(236, 229, 207, 244); + public static final Color LAND_TEXTBOX_WHITE = new Color(248, 232, 188, 244); + public static final Color LAND_TEXTBOX_BLUE = new Color(189, 212, 236, 244); + public static final Color LAND_TEXTBOX_BLACK = new Color(174, 164, 162, 244); + public static final Color LAND_TEXTBOX_RED = new Color(242, 168, 133, 244); + public static final Color LAND_TEXTBOX_GREEN = new Color(198, 220, 198, 244); + public static final Color LAND_TEXTBOX_GOLD = new Color(236, 229, 207, 244); - public static Color TEXTBOX_WHITE = new Color(252, 249, 244, 244); - public static Color TEXTBOX_BLUE = new Color(229, 238, 247, 244); - public static Color TEXTBOX_BLACK = new Color(241, 241, 240, 244); - public static Color TEXTBOX_RED = new Color(243, 224, 217, 244); - public static Color TEXTBOX_GREEN = new Color(217, 232, 223, 244); - public static Color TEXTBOX_GOLD = new Color(240, 234, 209, 244); - public static Color TEXTBOX_COLORLESS = new Color(219, 229, 233, 244); - public static Color TEXTBOX_LAND = new Color(218, 214, 212, 244); + public static final Color TEXTBOX_WHITE = new Color(252, 249, 244, 244); + public static final Color TEXTBOX_BLUE = new Color(229, 238, 247, 244); + public static final Color TEXTBOX_BLACK = new Color(241, 241, 240, 244); + public static final Color TEXTBOX_RED = new Color(243, 224, 217, 244); + public static final Color TEXTBOX_GREEN = new Color(217, 232, 223, 244); + public static final Color TEXTBOX_GOLD = new Color(240, 234, 209, 244); + public static final Color TEXTBOX_COLORLESS = new Color(219, 229, 233, 244); + public static final Color TEXTBOX_LAND = new Color(218, 214, 212, 244); - public static Color ERROR_COLOR = new Color(255, 0, 255); + public static final Color ERROR_COLOR = new Color(255, 0, 255); /////////////////////////////////////////////////////////////////////////// // Layout metrics for modern border cards @@ -163,18 +163,18 @@ public class ModernCardRenderer extends CardRenderer { protected int contentWidth; // How tall the name / type lines and P/T box are - protected static float BOX_HEIGHT_FRAC = 0.065f; // x cardHeight - protected static int BOX_HEIGHT_MIN = 16; + protected static final float BOX_HEIGHT_FRAC = 0.065f; // x cardHeight + protected static final int BOX_HEIGHT_MIN = 16; protected int boxHeight; // How far down the card is the type line placed? - protected static float TYPE_LINE_Y_FRAC = 0.57f; // x cardHeight - protected static float TYPE_LINE_Y_FRAC_TOKEN = 0.70f; - protected static float TYPE_LINE_Y_FRAC_FULL_ART = 0.74f; + protected static final float TYPE_LINE_Y_FRAC = 0.57f; // x cardHeight + protected static final float TYPE_LINE_Y_FRAC_TOKEN = 0.70f; + protected static final float TYPE_LINE_Y_FRAC_FULL_ART = 0.74f; protected int typeLineY; // Possible sizes of rules text font - protected static int[] RULES_TEXT_FONT_SIZES = {24, 18, 15, 12, 9}; + protected static final int[] RULES_TEXT_FONT_SIZES = {24, 18, 15, 12, 9}; // How large is the box text, and how far is it down the boxes protected int boxTextHeight; @@ -188,7 +188,7 @@ public class ModernCardRenderer extends CardRenderer { protected Font ptTextFont; // Processed mana cost string - protected String manaCostString; + protected final String manaCostString; public ModernCardRenderer(CardView card, boolean isTransformed) { // Pass off to parent diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/TextboxBasicManaRule.java b/Mage.Client/src/main/java/org/mage/card/arcane/TextboxBasicManaRule.java index 8b68848566f..020f177f439 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/TextboxBasicManaRule.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/TextboxBasicManaRule.java @@ -6,7 +6,7 @@ import java.util.ArrayList; * Created by stravant@gmail.com on 2016-09-14. */ public class TextboxBasicManaRule extends TextboxRule { - private String basicManaSymbol; + private final String basicManaSymbol; public TextboxBasicManaRule(String rule, ArrayList regions, String basicManaSymbol) { super(rule, regions, TextboxRuleType.BASIC_MANA); diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/TextboxLevelRule.java b/Mage.Client/src/main/java/org/mage/card/arcane/TextboxLevelRule.java index 207e2dee908..61e295b426e 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/TextboxLevelRule.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/TextboxLevelRule.java @@ -15,10 +15,10 @@ import java.util.List; public class TextboxLevelRule extends TextboxRule { // The levels that this rule applies to - public int levelFrom; - public int levelTo; + public final int levelFrom; + public final int levelTo; - public static int AND_HIGHER = 100; + public static final int AND_HIGHER = 100; public TextboxLevelRule(String text, List regions, int levelFrom, int levelTo) { super(text, regions, TextboxRuleType.LEVEL); diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/TextboxLoyaltyRule.java b/Mage.Client/src/main/java/org/mage/card/arcane/TextboxLoyaltyRule.java index 50d1ae633aa..d7b599e2b41 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/TextboxLoyaltyRule.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/TextboxLoyaltyRule.java @@ -12,9 +12,9 @@ import java.util.List; */ public class TextboxLoyaltyRule extends TextboxRule { - public int loyaltyChange; + public final int loyaltyChange; - public static int MINUS_X = 100; + public static final int MINUS_X = 100; public String getChangeString() { if (loyaltyChange == MINUS_X) { diff --git a/Mage.Client/src/main/java/org/mage/card/arcane/TextboxRule.java b/Mage.Client/src/main/java/org/mage/card/arcane/TextboxRule.java index 063685782c4..807e03d6547 100644 --- a/Mage.Client/src/main/java/org/mage/card/arcane/TextboxRule.java +++ b/Mage.Client/src/main/java/org/mage/card/arcane/TextboxRule.java @@ -25,7 +25,7 @@ public class TextboxRule { // attributed string. public interface AttributeRegion { - public void applyToAttributedString(AttributedString str, Font normal, Font italic); + void applyToAttributedString(AttributedString str, Font normal, Font italic); } // A region of italics, or bold text in a @@ -67,10 +67,10 @@ public class TextboxRule { } } - public String text; - public TextboxRuleType type; + public final String text; + public final TextboxRuleType type; - private List regions; + private final List regions; protected TextboxRule(String text, List regions, TextboxRuleType type) { this.text = text; diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/CardPluginImpl.java b/Mage.Client/src/main/java/org/mage/plugins/card/CardPluginImpl.java index 3c53fa20f7d..29195aa2f0b 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/CardPluginImpl.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/CardPluginImpl.java @@ -68,12 +68,12 @@ public class CardPluginImpl implements CardPlugin { private static final float STACK_SPACING_Y = 0.10f; private static final float ATTACHMENT_SPACING_Y = 0.13f; - private int landStackMax = 5; + private final int landStackMax = 5; // private int cardWidthMin = 50, cardWidthMax = Constants.CARD_SIZE_FULL.width; private int cardWidthMin = (int) GUISizeHelper.battlefieldCardMinDimension.getWidth(); private int cardWidthMax = (int) GUISizeHelper.battlefieldCardMaxDimension.getWidth(); - private boolean stackVertical = false; + private final boolean stackVertical = false; private int playAreaWidth, playAreaHeight; private int cardWidth, cardHeight; @@ -422,7 +422,7 @@ public class CardPluginImpl implements CardPlugin { return height - cardSpacingY + GUTTER_Y * 2; } - private static enum RowType { + private enum RowType { land, creature, other, attached; public boolean isType(MagePermanent card) { @@ -581,7 +581,7 @@ public class CardPluginImpl implements CardPlugin { @Override public void onAddCard(MagePermanent card, int count) { if (card != null) { - Animation.showCard((CardPanel) card, count > 0 ? count : 1); + Animation.showCard(card, count > 0 ? count : 1); try { while ((card).getAlpha() + 0.05f < 1) { Thread.sleep(30); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/DownloadGui.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/DownloadGui.java index c115b4deb94..b847d94127b 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/DownloadGui.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/DownloadGui.java @@ -9,8 +9,6 @@ package org.mage.plugins.card.dl; import java.awt.BorderLayout; import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.beans.IndexedPropertyChangeEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; @@ -55,12 +53,7 @@ public class DownloadGui extends JPanel { p.setBorder(BorderFactory.createTitledBorder("Progress:")); p.add(progress); JButton b = new JButton("X"); - b.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - getDownloader().dispose(); - } - }); + b.addActionListener(e -> getDownloader().dispose()); p.add(b, BorderLayout.EAST); add(p, BorderLayout.NORTH); @@ -160,14 +153,11 @@ public class DownloadGui extends JPanel { setBorder(BorderFactory.createTitledBorder(job.getName())); add(bar = new JProgressBar(job.getProgress())); JButton b = new JButton("X"); - b.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - switch(getJob().getState()) { - case NEW: - case WORKING: - getJob().setState(State.ABORTED); - } + b.addActionListener(e -> { + switch(getJob().getState()) { + case NEW: + case WORKING: + getJob().setState(State.ABORTED); } }); add(b, BorderLayout.EAST); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/DownloadJob.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/DownloadJob.java index 32462dfa601..049a9f8403b 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/DownloadJob.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/DownloadJob.java @@ -27,9 +27,9 @@ import org.mage.plugins.card.utils.CardImageUtils; */ public class DownloadJob extends AbstractLaternaBean { - public static enum State { + public enum State { - NEW, WORKING, FINISHED, ABORTED; + NEW, WORKING, FINISHED, ABORTED } private final String name; diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/AbstractBoundBean.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/AbstractBoundBean.java index fb411fe5350..0aa044940a6 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/AbstractBoundBean.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/AbstractBoundBean.java @@ -17,7 +17,7 @@ import java.beans.PropertyChangeListener; * @author Clemens Koza */ public abstract class AbstractBoundBean implements BoundBean { - protected PropertyChangeSupport s = new PropertyChangeSupport(this); + protected final PropertyChangeSupport s = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener listener) { s.addPropertyChangeListener(listener); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/EventListenerList.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/EventListenerList.java index aaf87ff37f6..18dc8d852a6 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/EventListenerList.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/EventListenerList.java @@ -41,11 +41,7 @@ public class EventListenerList extends javax.swing.event.EventListenerList { final Iterable it = Iterables.concat(new ArrayList>(l)); //transform to singleton iterators - return new Iterable() { - public Iterator iterator() { - return new SingletonIterator(it.iterator()); - } - }; + return () -> new SingletonIterator(it.iterator()); } /** @@ -71,7 +67,7 @@ public class EventListenerList extends javax.swing.event.EventListenerList { private class ListenerIterator extends AbstractIterator { private final Class listenerClass; - private Object[] listeners = listenerList; + private final Object[] listeners = listenerList; private int index = listeners.length; private ListenerIterator(Class listenerClass) { @@ -96,12 +92,7 @@ public class EventListenerList extends javax.swing.event.EventListenerList { private class ClassToIterableFunction implements Function, Iterable> { public Iterable apply(final Class from) { - return new Iterable() { - - public Iterator iterator() { - return new ListenerIterator(from); - } - }; + return () -> new ListenerIterator(from); } } @@ -111,8 +102,8 @@ public class EventListenerList extends javax.swing.event.EventListenerList { */ private static class SingletonIterator extends AbstractIterator { - private Iterator it; - private HashSet previous = new HashSet(); + private final Iterator it; + private final HashSet previous = new HashSet(); public SingletonIterator(Iterator it) { this.it = it; diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/PropertyChangeSupport.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/PropertyChangeSupport.java index a1ad565abc5..26574a23033 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/PropertyChangeSupport.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/PropertyChangeSupport.java @@ -18,7 +18,7 @@ package org.mage.plugins.card.dl.beans; public class PropertyChangeSupport extends java.beans.PropertyChangeSupport { private static final long serialVersionUID = -4241465377828790076L; - private Object sourceBean; + private final Object sourceBean; public PropertyChangeSupport(Object sourceBean) { super(sourceBean); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/collections/ListenableCollections.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/collections/ListenableCollections.java index b5f04d9cabd..a4a9bb0c4bd 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/collections/ListenableCollections.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/collections/ListenableCollections.java @@ -68,8 +68,8 @@ public final class ListenableCollections { private static class ListenableList extends AbstractList implements RandomAccess, Serializable { private static final long serialVersionUID = 8622608480525537692L; - private List delegate; - private ListListener listener; + private final List delegate; + private final ListListener listener; public ListenableList(List delegate, ListListener listener) { this.delegate = delegate; @@ -110,8 +110,8 @@ public final class ListenableCollections { private static class ListenableSequentialList extends AbstractSequentialList implements Serializable { private static final long serialVersionUID = 3630474556578001885L; - private List delegate; - private ListListener listener; + private final List delegate; + private final ListListener listener; public ListenableSequentialList(List delegate, ListListener listener) { this.delegate = delegate; @@ -185,23 +185,23 @@ public final class ListenableCollections { } } - public static interface SetListener extends Serializable { + public interface SetListener extends Serializable { /** * Notified after a value was added to the set. */ - public void add(E newValue); + void add(E newValue); /** * Notified after a value was removed from the set. */ - public void remove(E oldValue); + void remove(E oldValue); } private static class ListenableSet extends AbstractSet implements Serializable { private static final long serialVersionUID = 7728087988927063221L; - private Set delegate; - private SetListener listener; + private final Set delegate; + private final SetListener listener; public ListenableSet(Set set, SetListener listener) { delegate = set; @@ -220,7 +220,7 @@ public final class ListenableCollections { listener.add(o); } return b; - }; + } @SuppressWarnings("unchecked") @Override @@ -268,29 +268,29 @@ public final class ListenableCollections { } } - public static interface MapListener extends Serializable { + public interface MapListener extends Serializable { /** * Notified after a value was put into the map. */ - public void put(K key, V newValue); + void put(K key, V newValue); /** * Notified after a value in the map was changed. */ - public void set(K key, V oldValue, V newValue); + void set(K key, V oldValue, V newValue); /** * Notified after a value was removed from the map. */ - public void remove(K key, V oldValue); + void remove(K key, V oldValue); } private static class ListenableMap extends AbstractMap implements Serializable { private static final long serialVersionUID = 4032087477448965103L; - private Map delegate; - private MapListener listener; - private Set> entrySet; + private final Map delegate; + private final MapListener listener; + private final Set> entrySet; public ListenableMap(Map map, MapListener listener) { this.listener = listener; diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/CompoundProperties.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/CompoundProperties.java index 50d54cbd5b9..5a6f021913a 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/CompoundProperties.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/CompoundProperties.java @@ -23,7 +23,7 @@ import java.util.Set; * @author Clemens Koza */ public class CompoundProperties extends AbstractProperties { - private List delegates; + private final List delegates; public CompoundProperties(Properties... delegates) { this.delegates = asList(delegates); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeListListener.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeListListener.java index 740fb7d2672..260f38ca438 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeListListener.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeListListener.java @@ -21,8 +21,8 @@ import org.mage.plugins.card.dl.beans.collections.ListenableCollections.ListList public class PropertyChangeListListener implements ListListener { private static final long serialVersionUID = 625853864429729560L; - private PropertyChangeSupport s; - private String propertyName; + private final PropertyChangeSupport s; + private final String propertyName; public PropertyChangeListListener(PropertyChangeSupport s, String propertyName) { this.s = s; diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeMapListener.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeMapListener.java index 5eba920eac2..e0c9bedfe4f 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeMapListener.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeMapListener.java @@ -24,9 +24,9 @@ import org.mage.plugins.card.dl.beans.collections.ListenableCollections.MapListe public class PropertyChangeMapListener implements MapListener { private static final long serialVersionUID = 625853864429729560L; - private PropertyChangeSupport s; - private Map map; - private String propertyName; + private final PropertyChangeSupport s; + private final Map map; + private final String propertyName; public PropertyChangeMapListener(PropertyChangeSupport s, Map map, String propertyName) { this.s = s; @@ -49,8 +49,8 @@ public class PropertyChangeMapListener implements MapListener { public static abstract class MapEvent extends PropertyChangeEvent { private static final long serialVersionUID = -651568020675693544L; - private Map map; - private K key; + private final Map map; + private final K key; public MapEvent(Object source, String propertyName, Map map, K key) { super(source, propertyName, null, null); @@ -77,7 +77,7 @@ public class PropertyChangeMapListener implements MapListener { public static class MapPutEvent extends MapEvent { private static final long serialVersionUID = 6006291474676939650L; - private V newElement; + private final V newElement; public MapPutEvent(Object source, String propertyName, Map map, K key, V newElement) { super(source, propertyName, map, key); @@ -92,7 +92,8 @@ public class PropertyChangeMapListener implements MapListener { public static class MapSetEvent extends MapEvent { private static final long serialVersionUID = -2419438379909500079L; - private V oldElement, newElement; + private final V oldElement; + private final V newElement; public MapSetEvent(Object source, String propertyName, Map map, K key, V oldElement, V newElement) { super(source, propertyName, map, key); @@ -112,7 +113,7 @@ public class PropertyChangeMapListener implements MapListener { public static class MapRemoveEvent extends MapEvent { private static final long serialVersionUID = -2644879706878221895L; - private V oldElement; + private final V oldElement; public MapRemoveEvent(Object source, String propertyName, Map map, K key, V oldElement) { super(source, propertyName, map, key); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeSetListener.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeSetListener.java index f6b0effff5f..6d23fd4361d 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeSetListener.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/bound/PropertyChangeSetListener.java @@ -24,9 +24,9 @@ import org.mage.plugins.card.dl.beans.collections.ListenableCollections.SetListe public class PropertyChangeSetListener implements SetListener { private static final long serialVersionUID = 625853864429729560L; - private PropertyChangeSupport s; - private Set set; - private String propertyName; + private final PropertyChangeSupport s; + private final Set set; + private final String propertyName; public PropertyChangeSetListener(PropertyChangeSupport s, Set set, String propertyName) { this.s = s; @@ -45,7 +45,7 @@ public class PropertyChangeSetListener implements SetListener { public static abstract class SetEvent extends PropertyChangeEvent { private static final long serialVersionUID = -651568020675693544L; - private Set set; + private final Set set; public SetEvent(Object source, String propertyName, Set set) { super(source, propertyName, null, null); @@ -67,7 +67,7 @@ public class PropertyChangeSetListener implements SetListener { public static class SetAddEvent extends SetEvent { private static final long serialVersionUID = 9041766866796759871L; - private E newElement; + private final E newElement; public SetAddEvent(Object source, String propertyName, Set set, E newElement) { super(source, propertyName, set); @@ -82,7 +82,7 @@ public class PropertyChangeSetListener implements SetListener { public static class SetRemoveEvent extends SetEvent { private static final long serialVersionUID = -1315342339926392385L; - private E oldElement; + private final E oldElement; public SetRemoveEvent(Object source, String propertyName, Set set, E oldElement) { super(source, propertyName, set); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/lm/AbstractLaternaBean.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/lm/AbstractLaternaBean.java index 946560902bb..be462e18296 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/lm/AbstractLaternaBean.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/lm/AbstractLaternaBean.java @@ -22,6 +22,6 @@ import org.mage.plugins.card.dl.beans.properties.bound.BoundProperties; */ public class AbstractLaternaBean extends AbstractBoundBean { protected static final Logger log = Logger.getLogger(AbstractLaternaBean.class); - protected Properties properties = new BoundProperties(s); + protected final Properties properties = new BoundProperties(s); protected EventListenerList listeners = new EventListenerList(); } diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/AltMtgOnlTokensImageSource.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/AltMtgOnlTokensImageSource.java index af143a800d7..a52cc67102b 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/AltMtgOnlTokensImageSource.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/AltMtgOnlTokensImageSource.java @@ -28,11 +28,9 @@ package org.mage.plugins.card.dl.sources; import java.io.IOException; -import java.net.URL; import java.util.HashMap; import org.apache.log4j.Logger; import org.mage.plugins.card.images.CardDownloadData; -import org.mage.plugins.card.images.DownloadPictures; /** * diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/GrabbagImageSource.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/GrabbagImageSource.java index ee7e6afd3c3..e123be2ece8 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/GrabbagImageSource.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/GrabbagImageSource.java @@ -27,7 +27,6 @@ */ package org.mage.plugins.card.dl.sources; -import java.io.File; import java.io.IOException; import java.util.HashMap; import org.apache.log4j.Logger; diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/MtgOnlTokensImageSource.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/MtgOnlTokensImageSource.java index 630e0001671..e6493b3d2cc 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/MtgOnlTokensImageSource.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/MtgOnlTokensImageSource.java @@ -28,11 +28,9 @@ package org.mage.plugins.card.dl.sources; import java.io.IOException; -import java.net.URL; import java.util.HashMap; import org.apache.log4j.Logger; import org.mage.plugins.card.images.CardDownloadData; -import org.mage.plugins.card.images.DownloadPictures; /** * diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/MythicspoilerComSource.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/MythicspoilerComSource.java index 3611c81a633..23d3275ab45 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/MythicspoilerComSource.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/MythicspoilerComSource.java @@ -177,7 +177,6 @@ public class MythicspoilerComSource implements CardImageSource { cardName = cardLink.substring(6, cardLink.length() - 4); } else if (aliasesStart.contains(cardLink)) { cardName = cardLink.substring(0, cardLink.length() - 4); - ; } if (cardName != null && !cardName.isEmpty()) { if (cardNameAliases.containsKey(cardSet + "-" + cardName)) { @@ -209,11 +208,7 @@ public class MythicspoilerComSource implements CardImageSource { if (card.isFlippedSide()) { //doesn't support rotated images return null; } - Map setLinks = sets.get(cardSet); - if (setLinks == null) { - setLinks = getSetLinks(cardSet); - sets.put(cardSet, setLinks); - } + Map setLinks = sets.computeIfAbsent(cardSet, k -> getSetLinks(cardSet)); String searchName = card.getDownloadName().toLowerCase() .replaceAll(" ", "") .replaceAll("-", "") diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/WizardCardsImageSource.java b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/WizardCardsImageSource.java index 69b6386ff6e..e0b2b7c9fed 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/WizardCardsImageSource.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/dl/sources/WizardCardsImageSource.java @@ -440,11 +440,7 @@ public class WizardCardsImageSource implements CardImageSource { } String setNames = setsAliases.get(cardSet); if (setNames != null) { - Map setLinks = sets.get(cardSet); - if (setLinks == null) { - setLinks = getSetLinks(cardSet); - sets.put(cardSet, setLinks); - } + Map setLinks = sets.computeIfAbsent(cardSet, k -> getSetLinks(cardSet)); String link = setLinks.get(card.getDownloadName().toLowerCase()); if (link == null) { int length = collectorId.length(); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/images/CardDownloadData.java b/Mage.Client/src/main/java/org/mage/plugins/card/images/CardDownloadData.java index 4130addaf59..f63e2e0bfa2 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/images/CardDownloadData.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/images/CardDownloadData.java @@ -14,15 +14,15 @@ public class CardDownloadData { private String set; private String tokenSetCode; private String tokenDescriptor; - private String collectorId; - private Integer type; + private final String collectorId; + private final Integer type; private boolean token; - private boolean twoFacedCard; - private boolean secondSide; + private final boolean twoFacedCard; + private final boolean secondSide; private boolean flipCard; private boolean flippedSide; private boolean splitCard; - private boolean usesVariousArt; + private final boolean usesVariousArt; private boolean isType2; public CardDownloadData(String name, String set, String collectorId, boolean usesVariousArt, Integer type, String tokenSetCode, String tokenDescriptor) { diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/images/DownloadPictures.java b/Mage.Client/src/main/java/org/mage/plugins/card/images/DownloadPictures.java index 07ae2dd24f0..0405a759c86 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/images/DownloadPictures.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/images/DownloadPictures.java @@ -3,8 +3,6 @@ package org.mage.plugins.card.images; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics2D; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -69,11 +67,11 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab private static final Logger logger = Logger.getLogger(DownloadPictures.class); - private JProgressBar bar; + private final JProgressBar bar; private final JOptionPane dlg; private boolean cancel; private final JButton closeButton; - private JButton startDownloadButton; + private final JButton startDownloadButton; private int cardIndex; private List cards; private List type2cards; @@ -111,12 +109,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab String title = "Downloading"; final JDialog dialog = this.dlg.createDialog(frame, title); - closeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - dialog.setVisible(false); - } - }); + closeButton.addActionListener(e -> dialog.setVisible(false)); return dialog; } @@ -159,51 +152,45 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab jComboBox1.setModel(jComboBox1Model); jComboBox1.setAlignmentX(Component.LEFT_ALIGNMENT); - jComboBox1.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JComboBox cb = (JComboBox) e.getSource(); - switch (cb.getSelectedIndex()) { - case 0: - cardImageSource = MagicCardsImageSource.getInstance(); - break; - case 1: - cardImageSource = WizardCardsImageSource.getInstance(); - break; - case 2: - cardImageSource = MythicspoilerComSource.getInstance(); - break; - case 3: - cardImageSource = TokensMtgImageSource.getInstance(); - break; - case 4: - cardImageSource = MtgOnlTokensImageSource.getInstance(); - break; - case 5: - cardImageSource = AltMtgOnlTokensImageSource.getInstance(); - break; - case 6: - cardImageSource = GrabbagImageSource.getInstance(); - break; - case 7: - cardImageSource = MagidexImageSource.getInstance(); - break; - } - updateCardsToDownload(); + jComboBox1.addActionListener(e -> { + JComboBox cb = (JComboBox) e.getSource(); + switch (cb.getSelectedIndex()) { + case 0: + cardImageSource = MagicCardsImageSource.getInstance(); + break; + case 1: + cardImageSource = WizardCardsImageSource.getInstance(); + break; + case 2: + cardImageSource = MythicspoilerComSource.getInstance(); + break; + case 3: + cardImageSource = TokensMtgImageSource.getInstance(); + break; + case 4: + cardImageSource = MtgOnlTokensImageSource.getInstance(); + break; + case 5: + cardImageSource = AltMtgOnlTokensImageSource.getInstance(); + break; + case 6: + cardImageSource = GrabbagImageSource.getInstance(); + break; + case 7: + cardImageSource = MagidexImageSource.getInstance(); + break; } + updateCardsToDownload(); }); p0.add(jComboBox1); p0.add(Box.createVerticalStrut(5)); // Start startDownloadButton = new JButton("Start download"); - startDownloadButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - new Thread(DownloadPictures.this).start(); - startDownloadButton.setEnabled(false); - checkBox.setEnabled(false); - } + startDownloadButton.addActionListener(e -> { + new Thread(DownloadPictures.this).start(); + startDownloadButton.setEnabled(false); + checkBox.setEnabled(false); }); p0.add(Box.createVerticalStrut(5)); @@ -223,12 +210,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab p0.add(checkBox); p0.add(Box.createVerticalStrut(5)); - checkBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateCardsToDownload(); - } - }); + checkBox.addActionListener(e -> updateCardsToDownload()); // JOptionPane Object[] options = {startDownloadButton, closeButton = new JButton("Cancel")}; @@ -669,7 +651,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab if (responseCode == 200 || useTempFile) { if (!useTempFile) { - try (BufferedInputStream in = new BufferedInputStream(((HttpURLConnection) httpConn).getInputStream())) { + try (BufferedInputStream in = new BufferedInputStream(httpConn.getInputStream())) { //try (BufferedInputStream in = new BufferedInputStream(url.openConnection(p).getInputStream())) { out = new BufferedOutputStream(new TFileOutputStream(temporaryFile)); byte[] buf = new byte[1024]; diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/info/CardInfoPaneImpl.java b/Mage.Client/src/main/java/org/mage/plugins/card/info/CardInfoPaneImpl.java index 00ee89e34b5..869dc31bdcf 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/info/CardInfoPaneImpl.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/info/CardInfoPaneImpl.java @@ -63,18 +63,15 @@ public class CardInfoPaneImpl extends JEditorPane implements CardInfoPane { return; } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!card.equals(currentCard)) { - return; - } - TextLines textLines = GuiDisplayUtil.getTextLinesfromCardView(card); - StringBuilder buffer = GuiDisplayUtil.getRulefromCardView(card, textLines); - resizeTooltipIfNeeded(container, textLines.basicTextLength, textLines.lines.size()); - setText(buffer.toString()); - setCaretPosition(0); + SwingUtilities.invokeLater(() -> { + if (!card.equals(currentCard)) { + return; } + TextLines textLines = GuiDisplayUtil.getTextLinesfromCardView(card); + StringBuilder buffer = GuiDisplayUtil.getRulefromCardView(card, textLines); + resizeTooltipIfNeeded(container, textLines.basicTextLength, textLines.lines.size()); + setText(buffer.toString()); + setCaretPosition(0); }); } catch (Exception e) { diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/utils/CardImageUtils.java b/Mage.Client/src/main/java/org/mage/plugins/card/utils/CardImageUtils.java index 759787d6186..74db210fe9e 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/utils/CardImageUtils.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/utils/CardImageUtils.java @@ -3,6 +3,7 @@ package org.mage.plugins.card.utils; import java.net.InetSocketAddress; import java.net.Proxy; import java.util.HashMap; +import java.util.Objects; import java.util.prefs.Preferences; import mage.client.MageFrame; import mage.client.constants.Constants; @@ -120,8 +121,9 @@ public class CardImageUtils { public static String getImageBasePath() { String useDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_USE_DEFAULT, "true"); - String imagesPath = useDefault.equals("true") ? Constants.IO.imageBaseDir : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null); - if (!imagesPath.endsWith(TFile.separator)) { + String imagesPath = Objects.equals(useDefault, "true") ? Constants.IO.imageBaseDir : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null); + + if (imagesPath != null && !imagesPath.endsWith(TFile.separator)) { imagesPath += TFile.separator; } return imagesPath; @@ -161,7 +163,7 @@ public class CardImageUtils { public static String generateImagePath(CardDownloadData card) { String useDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_USE_DEFAULT, "true"); - String imagesPath = useDefault.equals("true") ? null : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null); + String imagesPath = Objects.equals(useDefault, "true") ? null : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null); String imageDir = getImageDir(card, imagesPath); String imageName; @@ -189,7 +191,7 @@ public class CardImageUtils { public static String generateTokenDescriptorImagePath(CardDownloadData card) { String useDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_USE_DEFAULT, "true"); - String imagesPath = useDefault.equals("true") ? null : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null); + String imagesPath = Objects.equals(useDefault, "true") ? null : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null); String straightImageFile = getTokenDescriptorImagePath(card); TFile file = new TFile(straightImageFile); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/utils/Transparency.java b/Mage.Client/src/main/java/org/mage/plugins/card/utils/Transparency.java index e5f449d5d5e..4a62f270256 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/utils/Transparency.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/utils/Transparency.java @@ -15,7 +15,7 @@ public class Transparency { public static Image makeColorTransparent(Image im, final Color color) { ImageFilter filter = new RGBImageFilter() { // the color we are looking for... Alpha bits are set to opaque - public int markerRGB = color.getRGB() | 0xFF000000; + public final int markerRGB = color.getRGB() | 0xFF000000; @Override public final int filterRGB(int x, int y, int rgb) { diff --git a/Mage.Client/src/main/java/org/mage/plugins/theme/ThemePluginImpl.java b/Mage.Client/src/main/java/org/mage/plugins/theme/ThemePluginImpl.java index aec6180610b..f6587272d9a 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/theme/ThemePluginImpl.java +++ b/Mage.Client/src/main/java/org/mage/plugins/theme/ThemePluginImpl.java @@ -22,8 +22,8 @@ public class ThemePluginImpl implements ThemePlugin { private static final Logger log = Logger.getLogger(ThemePluginImpl.class); private static BufferedImage background; - private List flist = new List(); - private String BackgroundDir = "backgrounds" + File.separator; + private final List flist = new List(); + private final String BackgroundDir = "backgrounds" + File.separator; @Init public void init() { diff --git a/Mage.Common/pom.xml b/Mage.Common/pom.xml index e82a698d932..feb4b9b013a 100644 --- a/Mage.Common/pom.xml +++ b/Mage.Common/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 mage-common diff --git a/Mage.Common/src/mage/interfaces/MageServer.java b/Mage.Common/src/mage/interfaces/MageServer.java index d9702a12548..817ccf84a98 100644 --- a/Mage.Common/src/mage/interfaces/MageServer.java +++ b/Mage.Common/src/mage/interfaces/MageServer.java @@ -210,6 +210,8 @@ public interface MageServer { void lockUser(String sessionId, String userName, long durationMinutes) throws MageException; + void setActivation(String sessionId, String userName, boolean active) throws MageException; + void toggleActivation(String sessionId, String userName) throws MageException; void removeTable(String sessionId, UUID tableId) throws MageException; diff --git a/Mage.Common/src/mage/remote/SessionImpl.java b/Mage.Common/src/mage/remote/SessionImpl.java index 9acb85673df..594bf094305 100644 --- a/Mage.Common/src/mage/remote/SessionImpl.java +++ b/Mage.Common/src/mage/remote/SessionImpl.java @@ -1466,11 +1466,37 @@ public class SessionImpl implements Session { } return false; } + + @Override + public boolean setActivation(String userName, boolean active) { + try { + if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to set active to " + active + " for user: " + userName + "?", "WARNING", + JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { + if (isConnected()) { + server.setActivation(sessionId, userName, active); + return true; + } + } + } catch (MageException ex) { + handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); + } + return false; + } @Override public boolean toggleActivation(String userName) { try { - if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to activate/deactivate user: " + userName + " for?", "WARNING", + if (JOptionPane.showConfirmDialog(null, "Did you want to set user: " + userName + " to active?", "WARNING", + JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { + return setActivation(userName, true); + } + if (JOptionPane.showConfirmDialog(null, "Did you want to set user: " + userName + " to INactive?", "WARNING", + JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { + return setActivation(userName, false); + } + if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to toggle activation for user: " + userName + "?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if (isConnected()) { server.toggleActivation(sessionId, userName); diff --git a/Mage.Common/src/mage/remote/interfaces/Connect.java b/Mage.Common/src/mage/remote/interfaces/Connect.java index 5f8a4a0667c..5cb8750e596 100644 --- a/Mage.Common/src/mage/remote/interfaces/Connect.java +++ b/Mage.Common/src/mage/remote/interfaces/Connect.java @@ -58,6 +58,8 @@ public interface Connect { boolean muteUserChat(String userName, long durationMinute); + boolean setActivation(String userName, boolean active); + boolean toggleActivation(String userName); boolean lockUser(String userName, long durationMinute); diff --git a/Mage.Common/src/mage/utils/DeckBuilder.java b/Mage.Common/src/mage/utils/DeckBuilder.java index 525049b4fdd..0d4b4482adc 100644 --- a/Mage.Common/src/mage/utils/DeckBuilder.java +++ b/Mage.Common/src/mage/utils/DeckBuilder.java @@ -7,7 +7,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Random; + import mage.Mana; import mage.cards.Card; import mage.cards.decks.Deck; diff --git a/Mage.Common/src/mage/utils/MageVersion.java b/Mage.Common/src/mage/utils/MageVersion.java index c90c6912cbe..33185a3fd3e 100644 --- a/Mage.Common/src/mage/utils/MageVersion.java +++ b/Mage.Common/src/mage/utils/MageVersion.java @@ -40,7 +40,7 @@ public class MageVersion implements Serializable, Comparable { */ public final static int MAGE_VERSION_MAJOR = 1; public final static int MAGE_VERSION_MINOR = 4; - public final static int MAGE_VERSION_PATCH = 20; + public final static int MAGE_VERSION_PATCH = 21; public final static String MAGE_VERSION_MINOR_PATCH = "V0"; public final static String MAGE_VERSION_INFO = ""; diff --git a/Mage.Common/src/mage/view/CardView.java b/Mage.Common/src/mage/view/CardView.java index 5413d844ac5..3d03b865f21 100644 --- a/Mage.Common/src/mage/view/CardView.java +++ b/Mage.Common/src/mage/view/CardView.java @@ -244,7 +244,7 @@ public class CardView extends SimpleCardView { Zone cardZone = game.getState().getZone(card.getId()); if (card.isFaceDown(game)) { showFaceUp = false; - if (!Zone.BATTLEFIELD.equals(cardZone)) { + if (Zone.BATTLEFIELD != cardZone) { if (showFaceDownCard) { showFaceUp = true; } @@ -379,8 +379,9 @@ public class CardView extends SimpleCardView { this.isToken = false; } - if (card.getSecondCardFace() != null) { - this.secondCardFace = new CardView(card.getSecondCardFace()); + Card secondSideCard = card.getSecondCardFace(); + if (secondSideCard != null) { + this.secondCardFace = new CardView(secondSideCard); this.alternateName = secondCardFace.getName(); this.originalName = card.getName(); } @@ -458,7 +459,7 @@ public class CardView extends SimpleCardView { this.rarity = Rarity.NA; this.rules = new ArrayList<>(); this.rules.add(stackAbility.getRule()); - if (stackAbility.getZone().equals(Zone.COMMAND)) { + if (stackAbility.getZone() == Zone.COMMAND) { this.expansionSetCode = stackAbility.getExpansionSetCode(); } } diff --git a/Mage.Common/src/mage/view/ChatMessage.java b/Mage.Common/src/mage/view/ChatMessage.java index a0dbd1e1d83..487e2fbf1c4 100644 --- a/Mage.Common/src/mage/view/ChatMessage.java +++ b/Mage.Common/src/mage/view/ChatMessage.java @@ -82,11 +82,11 @@ public class ChatMessage implements Serializable { } public boolean isUserMessage() { - return color != null && (color.equals(MessageColor.BLUE) || color.equals(MessageColor.YELLOW)); + return color != null && (color==MessageColor.BLUE || color==MessageColor.YELLOW); } public boolean isStatusMessage() { - return color != null && color.equals(MessageColor.ORANGE); + return color != null && color== MessageColor.ORANGE; } public String getUsername() { diff --git a/Mage.Common/src/mage/view/TableView.java b/Mage.Common/src/mage/view/TableView.java index 4d4f7373dde..52051be04c2 100644 --- a/Mage.Common/src/mage/view/TableView.java +++ b/Mage.Common/src/mage/view/TableView.java @@ -33,6 +33,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; + import mage.constants.SkillLevel; import mage.constants.TableState; import mage.game.Game; @@ -43,7 +44,6 @@ import mage.game.match.MatchPlayer; import mage.game.tournament.TournamentPlayer; /** - * * @author BetaSteward_at_googlemail.com */ public class TableView implements Serializable { @@ -67,19 +67,19 @@ public class TableView implements Serializable { private final boolean rated; private final boolean passworded; - public TableView(Table table) { + public TableView(Table table) { this.tableId = table.getId(); this.gameType = table.getGameType(); this.tableName = table.getName(); String tableNameInfo = null; if (tableName != null && !tableName.isEmpty()) { - tableNameInfo = " [" + table.getName() + "]"; + tableNameInfo = " [" + table.getName() + "]"; } this.controllerName = table.getControllerName(); this.tableState = table.getState(); - if (table.getState().equals(TableState.WAITING) || - table.getState().equals(TableState.READY_TO_START) || - table.getState().equals(TableState.STARTING) ) { + if (table.getState() == TableState.WAITING || + table.getState() == TableState.READY_TO_START || + table.getState() == TableState.STARTING) { this.createTime = table.getCreateTime(); } else { if (table.isTournament()) { @@ -89,22 +89,22 @@ public class TableView implements Serializable { } } this.isTournament = table.isTournament(); - for (Seat seat: table.getSeats()) { + for (Seat seat : table.getSeats()) { seats.add(new SeatView(seat)); } if (!table.isTournament()) { - // MATCH - if (table.getState().equals(TableState.WAITING) || table.getState().equals(TableState.READY_TO_START)) { - tableStateText = table.getState().toString() + " (" + table.getMatch().getPlayers().size() + "/"+ table.getSeats().length + ")"; + // MATCH + if (table.getState()==TableState.WAITING || table.getState()==TableState.READY_TO_START) { + tableStateText = table.getState().toString() + " (" + table.getMatch().getPlayers().size() + "/" + table.getSeats().length + ")"; } else { tableStateText = table.getState().toString(); } - for (Game game: table.getMatch().getGames()) { + for (Game game : table.getMatch().getGames()) { games.add(game.getId()); } StringBuilder sb = new StringBuilder(); StringBuilder sbScore = new StringBuilder(); - for(MatchPlayer matchPlayer: table.getMatch().getPlayers()) { + for (MatchPlayer matchPlayer : table.getMatch().getPlayers()) { if (matchPlayer.getPlayer() == null) { sb.append(", ").append("[unknown]"); sbScore.append("-").append(matchPlayer.getWins()); @@ -112,7 +112,7 @@ public class TableView implements Serializable { sb.append(", ").append(matchPlayer.getName()); sbScore.append("-").append(matchPlayer.getWins()); } else { - sbScore.insert(0,matchPlayer.getWins()).insert(0," Score: "); + sbScore.insert(0, matchPlayer.getWins()).insert(0, " Score: "); } } if (table.getMatch().getDraws() > 0) { @@ -138,12 +138,12 @@ public class TableView implements Serializable { this.rated = table.getMatch().getOptions().isRated(); this.passworded = !table.getMatch().getOptions().getPassword().isEmpty(); } else { - // TOURNAMENT + // TOURNAMENT if (table.getTournament().getOptions().getNumberRounds() > 0) { this.gameType = new StringBuilder(this.gameType).append(" ").append(table.getTournament().getOptions().getNumberRounds()).append(" Rounds").toString(); } StringBuilder sb1 = new StringBuilder(); - for (TournamentPlayer tp: table.getTournament().getPlayers()) { + for (TournamentPlayer tp : table.getTournament().getPlayers()) { if (!tp.getPlayer().getName().equals(table.getControllerName())) { sb1.append(", ").append(tp.getPlayer().getName()); } @@ -163,7 +163,7 @@ public class TableView implements Serializable { infoText.append(" Fr.Mul: ").append(table.getTournament().getOptions().getMatchOptions().getFreeMulligans()); } if (table.getTournament().getTournamentType().isLimited()) { - infoText.append(" Constr.: ").append(table.getTournament().getOptions().getLimitedOptions().getConstructionTime()/60).append(" Min."); + infoText.append(" Constr.: ").append(table.getTournament().getOptions().getLimitedOptions().getConstructionTime() / 60).append(" Min."); } break; case DUELING: @@ -172,13 +172,13 @@ public class TableView implements Serializable { case DRAFTING: Draft draft = table.getTournament().getDraft(); if (draft != null) { - stateText.append(" ").append(draft.getBoosterNum()).append("/").append(draft.getCardNum() -1); + stateText.append(" ").append(draft.getBoosterNum()).append("/").append(draft.getCardNum() - 1); } default: } this.additionalInfo = infoText.toString(); this.tableStateText = stateText.toString(); - this.deckType = table.getDeckType() + " " + table.getTournament().getBoosterInfo() + (tableNameInfo != null ? tableNameInfo : ""); + this.deckType = table.getDeckType() + " " + table.getTournament().getBoosterInfo() + (tableNameInfo != null ? tableNameInfo : ""); this.skillLevel = table.getTournament().getOptions().getMatchOptions().getSkillLevel(); this.quitRatio = Integer.toString(table.getTournament().getOptions().getQuitRatio()); this.limited = table.getTournament().getOptions().getMatchOptions().isLimited(); @@ -226,6 +226,7 @@ public class TableView implements Serializable { public boolean isTournament() { return this.isTournament; } + public String getAdditionalInfo() { return this.additionalInfo; } @@ -249,7 +250,7 @@ public class TableView implements Serializable { public boolean isRated() { return rated; } - + public boolean isPassworded() { return passworded; } diff --git a/Mage.Common/src/mage/view/UserView.java b/Mage.Common/src/mage/view/UserView.java index e1118d32a0c..d8d5e6a1de0 100644 --- a/Mage.Common/src/mage/view/UserView.java +++ b/Mage.Common/src/mage/view/UserView.java @@ -45,8 +45,9 @@ public class UserView implements Serializable { private final String userState; private final Date muteChatUntil; private final String clientVersion; + private final String email; - public UserView(String userName, String host, String sessionId, Date timeConnected, String gameInfo, String userState, Date muteChatUntil, String clientVersion) { + public UserView(String userName, String host, String sessionId, Date timeConnected, String gameInfo, String userState, Date muteChatUntil, String clientVersion, String email) { this.userName = userName; this.host = host; this.sessionId = sessionId; @@ -55,6 +56,7 @@ public class UserView implements Serializable { this.userState = userState; this.muteChatUntil = muteChatUntil; this.clientVersion = clientVersion; + this.email = email; } public String getUserName() { @@ -88,5 +90,9 @@ public class UserView implements Serializable { public Date getTimeConnected() { return timeConnected; } + + public String getEmail() { + return email; + } } diff --git a/Mage.Plugins/Mage.Counter.Plugin/pom.xml b/Mage.Plugins/Mage.Counter.Plugin/pom.xml index 14c592301c1..3ac80e4339e 100644 --- a/Mage.Plugins/Mage.Counter.Plugin/pom.xml +++ b/Mage.Plugins/Mage.Counter.Plugin/pom.xml @@ -7,7 +7,7 @@ org.mage mage-plugins - 1.4.20 + 1.4.21 mage-counter-plugin diff --git a/Mage.Plugins/pom.xml b/Mage.Plugins/pom.xml index d3103062fbc..e78d03456d1 100644 --- a/Mage.Plugins/pom.xml +++ b/Mage.Plugins/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 mage-plugins diff --git a/Mage.Server.Console/pom.xml b/Mage.Server.Console/pom.xml index 0beffafde59..fed6ebec66e 100644 --- a/Mage.Server.Console/pom.xml +++ b/Mage.Server.Console/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 org.mage diff --git a/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml b/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml index f0bf68970d3..1a12447c96e 100644 --- a/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml +++ b/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-deck-constructed diff --git a/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/AusHighlander.java b/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/AusHighlander.java index 7aa707894ce..d4f46323959 100644 --- a/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/AusHighlander.java +++ b/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/AusHighlander.java @@ -32,14 +32,12 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import mage.cards.Card; + import mage.cards.ExpansionSet; import mage.cards.Sets; import mage.cards.decks.Constructed; import mage.cards.decks.Deck; -import mage.constants.CardType; import mage.constants.SetType; -import mage.util.CardUtil; /** * diff --git a/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/Modern.java b/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/Modern.java index 270863f5f33..2d653699097 100644 --- a/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/Modern.java +++ b/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/Modern.java @@ -62,7 +62,9 @@ public class Modern extends Constructed { banned.add("Dig Through Time"); banned.add("Dread Return"); banned.add("Eye of Ugin"); + banned.add("Gitaxian Probe"); banned.add("Glimpse of Nature"); + banned.add("Golgari Grave-Troll"); banned.add("Great Furnace"); banned.add("Green Sun's Zenith"); banned.add("Hypergenesis"); diff --git a/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/Standard.java b/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/Standard.java index 054c8505d12..1e7377fa5e1 100644 --- a/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/Standard.java +++ b/Mage.Server.Plugins/Mage.Deck.Constructed/src/mage/deck/Standard.java @@ -67,5 +67,8 @@ public class Standard extends Constructed { } } } + banned.add("Emrakul, the Promised End"); + banned.add("Reflector Mage"); + banned.add("Smuggler's Copter"); } } diff --git a/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml b/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml index 0af678370fc..ceb0213d67b 100644 --- a/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml +++ b/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-deck-limited diff --git a/Mage.Server.Plugins/Mage.Game.CommanderDuel/pom.xml b/Mage.Server.Plugins/Mage.Game.CommanderDuel/pom.xml index 4f11eea8c43..0ee36bf21e3 100644 --- a/Mage.Server.Plugins/Mage.Game.CommanderDuel/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.CommanderDuel/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-game-commanderduel diff --git a/Mage.Server.Plugins/Mage.Game.CommanderDuel/src/mage/game/CommanderDuelMatch.java b/Mage.Server.Plugins/Mage.Game.CommanderDuel/src/mage/game/CommanderDuelMatch.java index 1090c4bd645..65a1edefa93 100644 --- a/Mage.Server.Plugins/Mage.Game.CommanderDuel/src/mage/game/CommanderDuelMatch.java +++ b/Mage.Server.Plugins/Mage.Game.CommanderDuel/src/mage/game/CommanderDuelMatch.java @@ -25,7 +25,6 @@ * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. */ - package mage.game; import mage.game.match.MatchImpl; @@ -46,11 +45,14 @@ public class CommanderDuelMatch extends MatchImpl { int startLife = 40; boolean alsoHand = true; // Don't like it to compare but seems like it's complicated to do it in another way + boolean checkCommanderDamage = true; if (options.getDeckType().equals("Variant Magic - Duel Commander")) { startLife = 20; // Starting with the Commander 2016 update (on November 11th, 2016), Duel Commander will be played with 20 life points instead of 30. alsoHand = true; // commander going to hand allowed to go to command zone effective July 17, 2015 + checkCommanderDamage = false; // since nov 16 duel commander uses no longer commander damage rule } CommanderDuel game = new CommanderDuel(options.getAttackOption(), options.getRange(), options.getFreeMulligans(), startLife); + game.setCheckCommanderDamage(checkCommanderDamage); game.setStartMessage(this.createGameStartMessage()); game.setAlsoHand(alsoHand); game.setAlsoLibrary(true); diff --git a/Mage.Server.Plugins/Mage.Game.CommanderFreeForAll/pom.xml b/Mage.Server.Plugins/Mage.Game.CommanderFreeForAll/pom.xml index 3e20eb3e960..dee41279516 100644 --- a/Mage.Server.Plugins/Mage.Game.CommanderFreeForAll/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.CommanderFreeForAll/pom.xml @@ -6,7 +6,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-game-commanderfreeforall diff --git a/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml b/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml index 3a8f95b6961..d44ee03a052 100644 --- a/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-game-freeforall diff --git a/Mage.Server.Plugins/Mage.Game.MomirDuel/pom.xml b/Mage.Server.Plugins/Mage.Game.MomirDuel/pom.xml index b7c46693585..65abbf56745 100644 --- a/Mage.Server.Plugins/Mage.Game.MomirDuel/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.MomirDuel/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-game-momirduel diff --git a/Mage.Server.Plugins/Mage.Game.TinyLeadersDuel/pom.xml b/Mage.Server.Plugins/Mage.Game.TinyLeadersDuel/pom.xml index 48a4f3ac524..e088bb47b88 100644 --- a/Mage.Server.Plugins/Mage.Game.TinyLeadersDuel/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.TinyLeadersDuel/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-game-tinyleadersduel diff --git a/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml b/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml index bb729f5ee93..df364bcfec5 100644 --- a/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-game-twoplayerduel diff --git a/Mage.Server.Plugins/Mage.Player.AI.DraftBot/pom.xml b/Mage.Server.Plugins/Mage.Player.AI.DraftBot/pom.xml index f55a49adc42..fa651388a71 100644 --- a/Mage.Server.Plugins/Mage.Player.AI.DraftBot/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AI.DraftBot/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-player-ai-draftbot diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml b/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml index 791a6036cf0..32cab1a21de 100644 --- a/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-player-ai-ma diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer6.java b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer6.java index fff24fdf6bd..908ae33f087 100644 --- a/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer6.java +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/src/mage/player/ai/ComputerPlayer6.java @@ -36,7 +36,6 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; -import java.util.Random; import java.util.Scanner; import java.util.Set; import java.util.UUID; diff --git a/Mage.Server.Plugins/Mage.Player.AI/pom.xml b/Mage.Server.Plugins/Mage.Player.AI/pom.xml index 53c235c45f5..e7cc0f5e5de 100644 --- a/Mage.Server.Plugins/Mage.Player.AI/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AI/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-player-ai diff --git a/Mage.Server.Plugins/Mage.Player.AI/src/main/java/mage/player/ai/ComputerPlayer.java b/Mage.Server.Plugins/Mage.Player.AI/src/main/java/mage/player/ai/ComputerPlayer.java index fa5e8f6cb2a..75e70c3c8da 100644 --- a/Mage.Server.Plugins/Mage.Player.AI/src/main/java/mage/player/ai/ComputerPlayer.java +++ b/Mage.Server.Plugins/Mage.Player.AI/src/main/java/mage/player/ai/ComputerPlayer.java @@ -593,6 +593,54 @@ public class ComputerPlayer extends PlayerImpl implements Player { //if (!target.isRequired()) return false; } + if (target.getOriginalTarget() instanceof TargetPermanentOrPlayer) { + List targets; + TargetPermanentOrPlayer t = ((TargetPermanentOrPlayer) target); + if (outcome.isGood()) { + targets = threats(abilityControllerId, source.getSourceId(), ((FilterPermanentOrPlayer) t.getFilter()).getPermanentFilter(), game, target.getTargets()); + } else { + targets = threats(randomOpponentId, source.getSourceId(), ((FilterPermanentOrPlayer) t.getFilter()).getPermanentFilter(), game, target.getTargets()); + } + + if (targets.isEmpty()) { + if (outcome.isGood()) { + if (target.canTarget(getId(), abilityControllerId, source, game)) { + target.addTarget(abilityControllerId, source, game); + return true; + } + } else if (target.canTarget(getId(), randomOpponentId, source, game)) { + target.addTarget(randomOpponentId, source, game); + return true; + } + } + + if (targets.isEmpty() && target.isRequired(source)) { + targets = game.getBattlefield().getActivePermanents(((FilterPermanentOrPlayer) t.getFilter()).getPermanentFilter(), playerId, game); + } + for (Permanent permanent : targets) { + List alreadyTargetted = target.getTargets(); + if (t.canTarget(abilityControllerId, permanent.getId(), source, game)) { + if (alreadyTargetted != null && !alreadyTargetted.contains(permanent.getId())) { + target.addTarget(permanent.getId(), source, game); + return true; + } + } + } + + if (outcome.isGood()) { + if (target.canTarget(getId(), abilityControllerId, source, game)) { + target.addTarget(abilityControllerId, source, game); + return true; + } + } else if (target.canTarget(getId(), randomOpponentId, source, game)) { + target.addTarget(randomOpponentId, source, game); + return true; + } + + //if (!target.isRequired()) + return false; + } + if (target.getOriginalTarget() instanceof TargetCardInGraveyard) { List cards = new ArrayList<>(); for (Player player : game.getPlayers().values()) { diff --git a/Mage.Server.Plugins/Mage.Player.AIMCTS/pom.xml b/Mage.Server.Plugins/Mage.Player.AIMCTS/pom.xml index 2ff383a06bd..05077c65e2e 100644 --- a/Mage.Server.Plugins/Mage.Player.AIMCTS/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AIMCTS/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-player-ai-mcts diff --git a/Mage.Server.Plugins/Mage.Player.AIMCTS/src/mage/player/ai/SimulatedPlayerMCTS.java b/Mage.Server.Plugins/Mage.Player.AIMCTS/src/mage/player/ai/SimulatedPlayerMCTS.java index 8a315878f18..2c015d350c7 100644 --- a/Mage.Server.Plugins/Mage.Player.AIMCTS/src/mage/player/ai/SimulatedPlayerMCTS.java +++ b/Mage.Server.Plugins/Mage.Player.AIMCTS/src/mage/player/ai/SimulatedPlayerMCTS.java @@ -31,7 +31,6 @@ import java.io.Serializable; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Random; import java.util.Set; import java.util.UUID; import mage.abilities.Ability; diff --git a/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml b/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml index ea6281b6747..a707d24b995 100644 --- a/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-player-aiminimax diff --git a/Mage.Server.Plugins/Mage.Player.Human/pom.xml b/Mage.Server.Plugins/Mage.Player.Human/pom.xml index 9973b7c2d83..c3161f80753 100644 --- a/Mage.Server.Plugins/Mage.Player.Human/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.Human/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-player-human diff --git a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml index 9f1bf92794c..59d38af82d7 100644 --- a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml +++ b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-tournament-boosterdraft diff --git a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/CubeFromDeck.java b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/CubeFromDeck.java index b4212eb3693..ef34d70b6e8 100644 --- a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/CubeFromDeck.java +++ b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/CubeFromDeck.java @@ -30,7 +30,6 @@ package mage.tournament.cubes; import mage.cards.decks.Deck; import mage.cards.decks.DeckCardInfo; import mage.cards.decks.DeckCardLists; -import mage.cards.decks.importer.DeckImporterUtil; import mage.game.draft.DraftCube.CardIdentity; import mage.game.draft.DraftCube; diff --git a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/LegacyCubeJanuary2017.java b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/LegacyCubeJanuary2017.java new file mode 100644 index 00000000000..cdaaa46ea42 --- /dev/null +++ b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/LegacyCubeJanuary2017.java @@ -0,0 +1,641 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.tournament.cubes; + +import mage.game.draft.DraftCube; + +/** + * + * @author fireshoes + */ + +public class LegacyCubeJanuary2017 extends DraftCube { + + public LegacyCubeJanuary2017() { + super("MTGO Legacy Cube January 2017 (600 cards)"); + cubeCards.add(new DraftCube.CardIdentity("Abbot of Keral Keep","")); + cubeCards.add(new DraftCube.CardIdentity("Abrupt Decay","")); + cubeCards.add(new DraftCube.CardIdentity("Abyssal Persecutor","")); + cubeCards.add(new DraftCube.CardIdentity("Accorder Paladin","")); + cubeCards.add(new DraftCube.CardIdentity("Acidic Slime","")); + cubeCards.add(new DraftCube.CardIdentity("Act of Aggression","")); + cubeCards.add(new DraftCube.CardIdentity("Ajani Goldmane","")); + cubeCards.add(new DraftCube.CardIdentity("Ajani Vengeant","")); + cubeCards.add(new DraftCube.CardIdentity("Ajani, Caller of the Pride","")); + cubeCards.add(new DraftCube.CardIdentity("Anafenza, Kin-Tree Spirit","")); + cubeCards.add(new DraftCube.CardIdentity("Ancestral Vision","")); + cubeCards.add(new DraftCube.CardIdentity("Ancient Tomb","")); + cubeCards.add(new DraftCube.CardIdentity("Angel of Invention","")); + cubeCards.add(new DraftCube.CardIdentity("Angel of Serenity","")); + cubeCards.add(new DraftCube.CardIdentity("Anger of the Gods","")); + cubeCards.add(new DraftCube.CardIdentity("Anguished Unmaking","")); + cubeCards.add(new DraftCube.CardIdentity("Animate Dead","")); + cubeCards.add(new DraftCube.CardIdentity("Arbor Elf","")); + cubeCards.add(new DraftCube.CardIdentity("Arc Trail","")); + cubeCards.add(new DraftCube.CardIdentity("Archangel Avacyn","")); + cubeCards.add(new DraftCube.CardIdentity("Arid Mesa","")); + cubeCards.add(new DraftCube.CardIdentity("Armageddon","")); + cubeCards.add(new DraftCube.CardIdentity("Ashenmoor Gouger","")); + cubeCards.add(new DraftCube.CardIdentity("Ashiok, Nightmare Weaver","")); + cubeCards.add(new DraftCube.CardIdentity("Assemble the Legion","")); + cubeCards.add(new DraftCube.CardIdentity("Asylum Visitor","")); + cubeCards.add(new DraftCube.CardIdentity("Attrition","")); + cubeCards.add(new DraftCube.CardIdentity("Augur of Bolas","")); + cubeCards.add(new DraftCube.CardIdentity("Avacyn's Pilgrim","")); + cubeCards.add(new DraftCube.CardIdentity("Avalanche Riders","")); + cubeCards.add(new DraftCube.CardIdentity("Avenger of Zendikar","")); + cubeCards.add(new DraftCube.CardIdentity("Badlands","")); + cubeCards.add(new DraftCube.CardIdentity("Baleful Strix","")); + cubeCards.add(new DraftCube.CardIdentity("Banefire","")); + cubeCards.add(new DraftCube.CardIdentity("Baneslayer Angel","")); + cubeCards.add(new DraftCube.CardIdentity("Banisher Priest","")); + cubeCards.add(new DraftCube.CardIdentity("Banishing Light","")); + cubeCards.add(new DraftCube.CardIdentity("Batterskull","")); + cubeCards.add(new DraftCube.CardIdentity("Bayou","")); + cubeCards.add(new DraftCube.CardIdentity("Beast Within","")); + cubeCards.add(new DraftCube.CardIdentity("Bedlam Reveler","")); + cubeCards.add(new DraftCube.CardIdentity("Beetleback Chief","")); + cubeCards.add(new DraftCube.CardIdentity("Birds of Paradise","")); + cubeCards.add(new DraftCube.CardIdentity("Birthing Pod","")); + cubeCards.add(new DraftCube.CardIdentity("Bitterblossom","")); + cubeCards.add(new DraftCube.CardIdentity("Blade Splicer","")); + cubeCards.add(new DraftCube.CardIdentity("Blood Artist","")); + cubeCards.add(new DraftCube.CardIdentity("Blood Crypt","")); + cubeCards.add(new DraftCube.CardIdentity("Bloodbraid Elf","")); + cubeCards.add(new DraftCube.CardIdentity("Bloodghast","")); + cubeCards.add(new DraftCube.CardIdentity("Bloodstained Mire","")); + cubeCards.add(new DraftCube.CardIdentity("Bloom Tender","")); + cubeCards.add(new DraftCube.CardIdentity("Blossoming Defense","")); + cubeCards.add(new DraftCube.CardIdentity("Bogardan Hellkite","")); + cubeCards.add(new DraftCube.CardIdentity("Bone Shredder","")); + cubeCards.add(new DraftCube.CardIdentity("Bonesplitter","")); + cubeCards.add(new DraftCube.CardIdentity("Bonfire of the Damned","")); + cubeCards.add(new DraftCube.CardIdentity("Boros Charm","")); + cubeCards.add(new DraftCube.CardIdentity("Boros Reckoner","")); + cubeCards.add(new DraftCube.CardIdentity("Brainstorm","")); + cubeCards.add(new DraftCube.CardIdentity("Breeding Pool","")); + cubeCards.add(new DraftCube.CardIdentity("Brimaz, King of Oreskos","")); + cubeCards.add(new DraftCube.CardIdentity("Brimstone Volley","")); + cubeCards.add(new DraftCube.CardIdentity("Bruna, the Fading Light","")); + cubeCards.add(new DraftCube.CardIdentity("Buried Alive","")); + cubeCards.add(new DraftCube.CardIdentity("Burst Lightning","")); + cubeCards.add(new DraftCube.CardIdentity("Careful Consideration","")); + cubeCards.add(new DraftCube.CardIdentity("Careful Study","")); + cubeCards.add(new DraftCube.CardIdentity("Catacomb Sifter","")); + cubeCards.add(new DraftCube.CardIdentity("Cathartic Reunion","")); + cubeCards.add(new DraftCube.CardIdentity("Celestial Colonnade","")); + cubeCards.add(new DraftCube.CardIdentity("Chain Lightning","")); + cubeCards.add(new DraftCube.CardIdentity("Chainer's Edict","")); + cubeCards.add(new DraftCube.CardIdentity("Chameleon Colossus","")); + cubeCards.add(new DraftCube.CardIdentity("Champion of the Parish","")); + cubeCards.add(new DraftCube.CardIdentity("Chandra, Fire of Kaladesh","")); + cubeCards.add(new DraftCube.CardIdentity("Chandra, Flamecaller","")); + cubeCards.add(new DraftCube.CardIdentity("Chandra, Pyromaster","")); + cubeCards.add(new DraftCube.CardIdentity("Chandra, Torch of Defiance","")); + cubeCards.add(new DraftCube.CardIdentity("Chandra's Phoenix","")); + cubeCards.add(new DraftCube.CardIdentity("Char","")); + cubeCards.add(new DraftCube.CardIdentity("Chord of Calling","")); + cubeCards.add(new DraftCube.CardIdentity("Chromatic Lantern","")); + cubeCards.add(new DraftCube.CardIdentity("City of Brass","")); + cubeCards.add(new DraftCube.CardIdentity("Clifftop Retreat","")); + cubeCards.add(new DraftCube.CardIdentity("Cloudgoat Ranger","")); + cubeCards.add(new DraftCube.CardIdentity("Collective Brutality","")); + cubeCards.add(new DraftCube.CardIdentity("Collective Defiance","")); + cubeCards.add(new DraftCube.CardIdentity("Collective Effort","")); + cubeCards.add(new DraftCube.CardIdentity("Compulsive Research","")); + cubeCards.add(new DraftCube.CardIdentity("Condemn","")); + cubeCards.add(new DraftCube.CardIdentity("Consecrated Sphinx","")); + cubeCards.add(new DraftCube.CardIdentity("Control Magic","")); + cubeCards.add(new DraftCube.CardIdentity("Coralhelm Commander","")); + cubeCards.add(new DraftCube.CardIdentity("Council's Judgment","")); + cubeCards.add(new DraftCube.CardIdentity("Counterspell","")); + cubeCards.add(new DraftCube.CardIdentity("Courser of Kruphix","")); + cubeCards.add(new DraftCube.CardIdentity("Crater's Claws","")); + cubeCards.add(new DraftCube.CardIdentity("Craterhoof Behemoth","")); + cubeCards.add(new DraftCube.CardIdentity("Creeping Tar Pit","")); + cubeCards.add(new DraftCube.CardIdentity("Crux of Fate","")); + cubeCards.add(new DraftCube.CardIdentity("Cryptic Command","")); + cubeCards.add(new DraftCube.CardIdentity("Cultivate","")); + cubeCards.add(new DraftCube.CardIdentity("Cunning Sparkmage","")); + cubeCards.add(new DraftCube.CardIdentity("Cyclonic Rift","")); + cubeCards.add(new DraftCube.CardIdentity("Damnation","")); + cubeCards.add(new DraftCube.CardIdentity("Dark Confidant","")); + cubeCards.add(new DraftCube.CardIdentity("Dark Petition","")); + cubeCards.add(new DraftCube.CardIdentity("Dark Ritual","")); + cubeCards.add(new DraftCube.CardIdentity("Day of Judgment","")); + cubeCards.add(new DraftCube.CardIdentity("Daze","")); + cubeCards.add(new DraftCube.CardIdentity("Deathrite Shaman","")); + cubeCards.add(new DraftCube.CardIdentity("Deceiver Exarch","")); + cubeCards.add(new DraftCube.CardIdentity("Declaration in Stone","")); + cubeCards.add(new DraftCube.CardIdentity("Deep Analysis","")); + cubeCards.add(new DraftCube.CardIdentity("Delver of Secrets","")); + cubeCards.add(new DraftCube.CardIdentity("Den Protector","")); + cubeCards.add(new DraftCube.CardIdentity("Deranged Hermit","")); + cubeCards.add(new DraftCube.CardIdentity("Desecration Demon","")); + cubeCards.add(new DraftCube.CardIdentity("Devil's Play","")); + cubeCards.add(new DraftCube.CardIdentity("Devoted Druid","")); + cubeCards.add(new DraftCube.CardIdentity("Disfigure","")); + cubeCards.add(new DraftCube.CardIdentity("Dismember","")); + cubeCards.add(new DraftCube.CardIdentity("Dismiss","")); + cubeCards.add(new DraftCube.CardIdentity("Dissipate","")); + cubeCards.add(new DraftCube.CardIdentity("Dissolve","")); + cubeCards.add(new DraftCube.CardIdentity("Distended Mindbender","")); + cubeCards.add(new DraftCube.CardIdentity("Domri Rade","")); + cubeCards.add(new DraftCube.CardIdentity("Doom Blade","")); + cubeCards.add(new DraftCube.CardIdentity("Dragon Fodder","")); + cubeCards.add(new DraftCube.CardIdentity("Dragonlord Atarka","")); + cubeCards.add(new DraftCube.CardIdentity("Dragonlord Dromoka","")); + cubeCards.add(new DraftCube.CardIdentity("Dragonlord Ojutai","")); + cubeCards.add(new DraftCube.CardIdentity("Dragonlord Silumgar","")); + cubeCards.add(new DraftCube.CardIdentity("Dragonskull Summit","")); + cubeCards.add(new DraftCube.CardIdentity("Drana, Liberator of Malakir","")); + cubeCards.add(new DraftCube.CardIdentity("Dread Return","")); + cubeCards.add(new DraftCube.CardIdentity("Dreadbore","")); + cubeCards.add(new DraftCube.CardIdentity("Dromoka's Command","")); + cubeCards.add(new DraftCube.CardIdentity("Drowned Catacomb","")); + cubeCards.add(new DraftCube.CardIdentity("Dualcaster Mage","")); + cubeCards.add(new DraftCube.CardIdentity("Dungeon Geists","")); + cubeCards.add(new DraftCube.CardIdentity("Duplicant","")); + cubeCards.add(new DraftCube.CardIdentity("Duress","")); + cubeCards.add(new DraftCube.CardIdentity("Duskwatch Recruiter","")); + cubeCards.add(new DraftCube.CardIdentity("Edric, Spymaster of Trest","")); + cubeCards.add(new DraftCube.CardIdentity("Elder Deep-Fiend","")); + cubeCards.add(new DraftCube.CardIdentity("Eldrazi Monument","")); + cubeCards.add(new DraftCube.CardIdentity("Eldritch Evolution","")); + cubeCards.add(new DraftCube.CardIdentity("Electrolyze","")); + cubeCards.add(new DraftCube.CardIdentity("Elesh Norn, Grand Cenobite","")); + cubeCards.add(new DraftCube.CardIdentity("Elspeth Tirel","")); + cubeCards.add(new DraftCube.CardIdentity("Elspeth, Knight-Errant","")); + cubeCards.add(new DraftCube.CardIdentity("Elspeth, Sun's Champion","")); + cubeCards.add(new DraftCube.CardIdentity("Elves of Deep Shadow","")); + cubeCards.add(new DraftCube.CardIdentity("Elvish Mystic","")); + cubeCards.add(new DraftCube.CardIdentity("Emeria Angel","")); + cubeCards.add(new DraftCube.CardIdentity("Emrakul, the Promised End","")); + cubeCards.add(new DraftCube.CardIdentity("Entomb","")); + cubeCards.add(new DraftCube.CardIdentity("Entreat the Angels","")); + cubeCards.add(new DraftCube.CardIdentity("Erebos, God of the Dead","")); + cubeCards.add(new DraftCube.CardIdentity("Eternal Witness","")); + cubeCards.add(new DraftCube.CardIdentity("Ever After","")); + cubeCards.add(new DraftCube.CardIdentity("Exhume","")); + cubeCards.add(new DraftCube.CardIdentity("Explore","")); + cubeCards.add(new DraftCube.CardIdentity("Exquisite Firecraft","")); + cubeCards.add(new DraftCube.CardIdentity("Fact or Fiction","")); + cubeCards.add(new DraftCube.CardIdentity("Faith's Fetters","")); + cubeCards.add(new DraftCube.CardIdentity("Falkenrath Gorger","")); + cubeCards.add(new DraftCube.CardIdentity("Far // Away","")); + cubeCards.add(new DraftCube.CardIdentity("Farseek","")); + cubeCards.add(new DraftCube.CardIdentity("Fauna Shaman","")); + cubeCards.add(new DraftCube.CardIdentity("Fertile Ground","")); + cubeCards.add(new DraftCube.CardIdentity("Fiend Hunter","")); + cubeCards.add(new DraftCube.CardIdentity("Fiery Confluence","")); + cubeCards.add(new DraftCube.CardIdentity("Fire // Ice","")); + cubeCards.add(new DraftCube.CardIdentity("Firebolt","")); + cubeCards.add(new DraftCube.CardIdentity("Firefist Striker","")); + cubeCards.add(new DraftCube.CardIdentity("Flame Slash","")); + cubeCards.add(new DraftCube.CardIdentity("Flametongue Kavu","")); + cubeCards.add(new DraftCube.CardIdentity("Flamewake Phoenix","")); + cubeCards.add(new DraftCube.CardIdentity("Fleetwheel Cruiser","")); + cubeCards.add(new DraftCube.CardIdentity("Flickerwisp","")); + cubeCards.add(new DraftCube.CardIdentity("Flooded Strand","")); + cubeCards.add(new DraftCube.CardIdentity("Forbid","")); + cubeCards.add(new DraftCube.CardIdentity("Force of Will","")); + cubeCards.add(new DraftCube.CardIdentity("Force Spike","")); + cubeCards.add(new DraftCube.CardIdentity("Forked Bolt","")); + cubeCards.add(new DraftCube.CardIdentity("Frost Titan","")); + cubeCards.add(new DraftCube.CardIdentity("Future Sight","")); + cubeCards.add(new DraftCube.CardIdentity("Fyndhorn Elves","")); + cubeCards.add(new DraftCube.CardIdentity("Gaddock Teeg","")); + cubeCards.add(new DraftCube.CardIdentity("Gaea's Cradle","")); + cubeCards.add(new DraftCube.CardIdentity("Gamble","")); + cubeCards.add(new DraftCube.CardIdentity("Garruk Relentless","")); + cubeCards.add(new DraftCube.CardIdentity("Garruk Wildspeaker","")); + cubeCards.add(new DraftCube.CardIdentity("Garruk, Apex Predator","")); + cubeCards.add(new DraftCube.CardIdentity("Garruk, Caller of Beasts","")); + cubeCards.add(new DraftCube.CardIdentity("Garruk, Primal Hunter","")); + cubeCards.add(new DraftCube.CardIdentity("Gatekeeper of Malakir","")); + cubeCards.add(new DraftCube.CardIdentity("Gather the Townsfolk","")); + cubeCards.add(new DraftCube.CardIdentity("Geist of Saint Traft","")); + cubeCards.add(new DraftCube.CardIdentity("Genesis Wave","")); + cubeCards.add(new DraftCube.CardIdentity("Geralf's Messenger","")); + cubeCards.add(new DraftCube.CardIdentity("Gideon, Ally of Zendikar","")); + cubeCards.add(new DraftCube.CardIdentity("Gideon Jura","")); + cubeCards.add(new DraftCube.CardIdentity("Gifts Ungiven","")); + cubeCards.add(new DraftCube.CardIdentity("Gilded Lotus","")); + cubeCards.add(new DraftCube.CardIdentity("Gilt-Leaf Winnower","")); + cubeCards.add(new DraftCube.CardIdentity("Gisela, the Broken Blade","")); + cubeCards.add(new DraftCube.CardIdentity("Gitaxian Probe","")); + cubeCards.add(new DraftCube.CardIdentity("Glacial Fortress","")); + cubeCards.add(new DraftCube.CardIdentity("Glen Elendra Archmage","")); + cubeCards.add(new DraftCube.CardIdentity("Glorious Anthem","")); + cubeCards.add(new DraftCube.CardIdentity("Go for the Throat","")); + cubeCards.add(new DraftCube.CardIdentity("Goblin Bombardment","")); + cubeCards.add(new DraftCube.CardIdentity("Goblin Bushwhacker","")); + cubeCards.add(new DraftCube.CardIdentity("Goblin Dark-Dwellers","")); + cubeCards.add(new DraftCube.CardIdentity("Goblin Guide","")); + cubeCards.add(new DraftCube.CardIdentity("Goblin Rabblemaster","")); + cubeCards.add(new DraftCube.CardIdentity("Godless Shrine","")); + cubeCards.add(new DraftCube.CardIdentity("Gonti, Lord of Luxury","")); + cubeCards.add(new DraftCube.CardIdentity("Gore-House Chainwalker","")); + cubeCards.add(new DraftCube.CardIdentity("Grave Titan","")); + cubeCards.add(new DraftCube.CardIdentity("Gray Merchant of Asphodel","")); + cubeCards.add(new DraftCube.CardIdentity("Greater Gargadon","")); + cubeCards.add(new DraftCube.CardIdentity("Green Sun's Zenith","")); + cubeCards.add(new DraftCube.CardIdentity("Greenwarden of Murasa","")); + cubeCards.add(new DraftCube.CardIdentity("Grim Lavamancer","")); + cubeCards.add(new DraftCube.CardIdentity("Griselbrand","")); + cubeCards.add(new DraftCube.CardIdentity("Hallowed Fountain","")); + cubeCards.add(new DraftCube.CardIdentity("Hallowed Spiritkeeper","")); + cubeCards.add(new DraftCube.CardIdentity("Hangarback Walker","")); + cubeCards.add(new DraftCube.CardIdentity("Harbinger of the Tides","")); + cubeCards.add(new DraftCube.CardIdentity("Harmonize","")); + cubeCards.add(new DraftCube.CardIdentity("Hellrider","")); + cubeCards.add(new DraftCube.CardIdentity("Hero of Bladehold","")); + cubeCards.add(new DraftCube.CardIdentity("Hero's Downfall","")); + cubeCards.add(new DraftCube.CardIdentity("Hidden Dragonslayer","")); + cubeCards.add(new DraftCube.CardIdentity("Hinterland Harbor","")); + cubeCards.add(new DraftCube.CardIdentity("Hissing Quagmire","")); + cubeCards.add(new DraftCube.CardIdentity("Honor of the Pure","")); + cubeCards.add(new DraftCube.CardIdentity("Hordeling Outburst","")); + cubeCards.add(new DraftCube.CardIdentity("Hornet Queen","")); + cubeCards.add(new DraftCube.CardIdentity("Huntmaster of the Fells","")); + cubeCards.add(new DraftCube.CardIdentity("Hymn to Tourach","")); + cubeCards.add(new DraftCube.CardIdentity("Hypnotic Specter","")); + cubeCards.add(new DraftCube.CardIdentity("Imperial Recruiter","")); + cubeCards.add(new DraftCube.CardIdentity("Impulse","")); + cubeCards.add(new DraftCube.CardIdentity("Incendiary Flow","")); + cubeCards.add(new DraftCube.CardIdentity("Incinerate","")); + cubeCards.add(new DraftCube.CardIdentity("Inferno Titan","")); + cubeCards.add(new DraftCube.CardIdentity("Inquisition of Kozilek","")); + cubeCards.add(new DraftCube.CardIdentity("Into the Roil","")); + cubeCards.add(new DraftCube.CardIdentity("Ire Shaman","")); + cubeCards.add(new DraftCube.CardIdentity("Isamaru, Hound of Konda","")); + cubeCards.add(new DraftCube.CardIdentity("Isochron Scepter","")); + cubeCards.add(new DraftCube.CardIdentity("Isolated Chapel","")); + cubeCards.add(new DraftCube.CardIdentity("Izzet Charm","")); + cubeCards.add(new DraftCube.CardIdentity("Jace Beleren","")); + cubeCards.add(new DraftCube.CardIdentity("Jace, Architect of Thought","")); + cubeCards.add(new DraftCube.CardIdentity("Jace, the Mind Sculptor","")); + cubeCards.add(new DraftCube.CardIdentity("Jace, Vryn's Prodigy","")); + cubeCards.add(new DraftCube.CardIdentity("Jackal Pup","")); + cubeCards.add(new DraftCube.CardIdentity("Joraga Treespeaker","")); + cubeCards.add(new DraftCube.CardIdentity("Journey to Nowhere","")); + cubeCards.add(new DraftCube.CardIdentity("Kalitas, Traitor of Ghet","")); + cubeCards.add(new DraftCube.CardIdentity("Kami of Ancient Law","")); + cubeCards.add(new DraftCube.CardIdentity("Karmic Guide","")); + cubeCards.add(new DraftCube.CardIdentity("Karn Liberated","")); + cubeCards.add(new DraftCube.CardIdentity("Keiga, the Tide Star","")); + cubeCards.add(new DraftCube.CardIdentity("Keranos, God of Storms","")); + cubeCards.add(new DraftCube.CardIdentity("Kiki-Jiki, Mirror Breaker","")); + cubeCards.add(new DraftCube.CardIdentity("Kiln Fiend","")); + cubeCards.add(new DraftCube.CardIdentity("Kiora, the Crashing Wave","")); + cubeCards.add(new DraftCube.CardIdentity("Kiora's Follower","")); + cubeCards.add(new DraftCube.CardIdentity("Kira, Great Glass-Spinner","")); + cubeCards.add(new DraftCube.CardIdentity("Kitchen Finks","")); + cubeCards.add(new DraftCube.CardIdentity("Kodama's Reach","")); + cubeCards.add(new DraftCube.CardIdentity("Kokusho, the Evening Star","")); + cubeCards.add(new DraftCube.CardIdentity("Kolaghan's Command","")); + cubeCards.add(new DraftCube.CardIdentity("Koth of the Hammer","")); + cubeCards.add(new DraftCube.CardIdentity("Krenko's Command","")); + cubeCards.add(new DraftCube.CardIdentity("Kytheon, Hero of Akros","")); + cubeCards.add(new DraftCube.CardIdentity("Land Tax","")); + cubeCards.add(new DraftCube.CardIdentity("Languish","")); + cubeCards.add(new DraftCube.CardIdentity("Lavaclaw Reaches","")); + cubeCards.add(new DraftCube.CardIdentity("Legacy's Allure","")); + cubeCards.add(new DraftCube.CardIdentity("Leonin Relic-Warder","")); + cubeCards.add(new DraftCube.CardIdentity("Lightning Bolt","")); + cubeCards.add(new DraftCube.CardIdentity("Lightning Greaves","")); + cubeCards.add(new DraftCube.CardIdentity("Lightning Helix","")); + cubeCards.add(new DraftCube.CardIdentity("Lightning Mauler","")); + cubeCards.add(new DraftCube.CardIdentity("Lightning Strike","")); + cubeCards.add(new DraftCube.CardIdentity("Liliana of the Veil","")); + cubeCards.add(new DraftCube.CardIdentity("Liliana Vess","")); + cubeCards.add(new DraftCube.CardIdentity("Liliana, Heretical Healer","")); + cubeCards.add(new DraftCube.CardIdentity("Liliana, the Last Hope","")); + cubeCards.add(new DraftCube.CardIdentity("Lingering Souls","")); + cubeCards.add(new DraftCube.CardIdentity("Linvala, Keeper of Silence","")); + cubeCards.add(new DraftCube.CardIdentity("Linvala, the Preserver","")); + cubeCards.add(new DraftCube.CardIdentity("Living Death","")); + cubeCards.add(new DraftCube.CardIdentity("Llanowar Elves","")); + cubeCards.add(new DraftCube.CardIdentity("Looter il-Kor","")); + cubeCards.add(new DraftCube.CardIdentity("Lotus Cobra","")); + cubeCards.add(new DraftCube.CardIdentity("Loxodon Warhammer","")); + cubeCards.add(new DraftCube.CardIdentity("Lumbering Falls","")); + cubeCards.add(new DraftCube.CardIdentity("Maelstrom Pulse","")); + cubeCards.add(new DraftCube.CardIdentity("Magma Jet","")); + cubeCards.add(new DraftCube.CardIdentity("Magus of the Will","")); + cubeCards.add(new DraftCube.CardIdentity("Makeshift Mannequin","")); + cubeCards.add(new DraftCube.CardIdentity("Malicious Affliction","")); + cubeCards.add(new DraftCube.CardIdentity("Man-o'-War","")); + cubeCards.add(new DraftCube.CardIdentity("Mana Confluence","")); + cubeCards.add(new DraftCube.CardIdentity("Mana Tithe","")); + cubeCards.add(new DraftCube.CardIdentity("Managorger Hydra","")); + cubeCards.add(new DraftCube.CardIdentity("Manic Vandal","")); + cubeCards.add(new DraftCube.CardIdentity("Marsh Flats","")); + cubeCards.add(new DraftCube.CardIdentity("Martial Coup","")); + cubeCards.add(new DraftCube.CardIdentity("Massacre Wurm","")); + cubeCards.add(new DraftCube.CardIdentity("Master of the Wild Hunt","")); + cubeCards.add(new DraftCube.CardIdentity("Master of Waves","")); + cubeCards.add(new DraftCube.CardIdentity("Meloku the Clouded Mirror","")); + cubeCards.add(new DraftCube.CardIdentity("Mentor of the Meek","")); + cubeCards.add(new DraftCube.CardIdentity("Merfolk Looter","")); + cubeCards.add(new DraftCube.CardIdentity("Mimic Vat","")); + cubeCards.add(new DraftCube.CardIdentity("Mindslaver","")); + cubeCards.add(new DraftCube.CardIdentity("Mirari's Wake","")); + cubeCards.add(new DraftCube.CardIdentity("Mirran Crusader","")); + cubeCards.add(new DraftCube.CardIdentity("Mirror Entity","")); + cubeCards.add(new DraftCube.CardIdentity("Miscalculation","")); + cubeCards.add(new DraftCube.CardIdentity("Mishra's Factory","")); + cubeCards.add(new DraftCube.CardIdentity("Misty Rainforest","")); + cubeCards.add(new DraftCube.CardIdentity("Mizzium Mortars","")); + cubeCards.add(new DraftCube.CardIdentity("Mogg War Marshal","")); + cubeCards.add(new DraftCube.CardIdentity("Monastery Mentor","")); + cubeCards.add(new DraftCube.CardIdentity("Monastery Swiftspear","")); + cubeCards.add(new DraftCube.CardIdentity("Mother of Runes","")); + cubeCards.add(new DraftCube.CardIdentity("Mulldrifter","")); + cubeCards.add(new DraftCube.CardIdentity("Murderous Cut","")); + cubeCards.add(new DraftCube.CardIdentity("Mutavault","")); + cubeCards.add(new DraftCube.CardIdentity("Myr Battlesphere","")); + cubeCards.add(new DraftCube.CardIdentity("Mystic Snake","")); + cubeCards.add(new DraftCube.CardIdentity("Nahiri, the Harbinger","")); + cubeCards.add(new DraftCube.CardIdentity("Nature's Lore","")); + cubeCards.add(new DraftCube.CardIdentity("Necromancy","")); + cubeCards.add(new DraftCube.CardIdentity("Needle Spires","")); + cubeCards.add(new DraftCube.CardIdentity("Negate","")); + cubeCards.add(new DraftCube.CardIdentity("Nekrataal","")); + cubeCards.add(new DraftCube.CardIdentity("Nevinyrral's Disk","")); + cubeCards.add(new DraftCube.CardIdentity("Nicol Bolas, Planeswalker","")); + cubeCards.add(new DraftCube.CardIdentity("Nightveil Specter","")); + cubeCards.add(new DraftCube.CardIdentity("Nissa, Vastwood Seer","")); + cubeCards.add(new DraftCube.CardIdentity("Nissa, Voice of Zendikar","")); + cubeCards.add(new DraftCube.CardIdentity("Nissa, Worldwaker","")); + cubeCards.add(new DraftCube.CardIdentity("Noble Hierarch","")); + cubeCards.add(new DraftCube.CardIdentity("Noxious Gearhulk","")); + cubeCards.add(new DraftCube.CardIdentity("Nykthos, Shrine to Nyx","")); + cubeCards.add(new DraftCube.CardIdentity("Oath of Nissa","")); + cubeCards.add(new DraftCube.CardIdentity("Ob Nixilis Reignited","")); + cubeCards.add(new DraftCube.CardIdentity("Oblivion Ring","")); + cubeCards.add(new DraftCube.CardIdentity("Oblivion Stone","")); + cubeCards.add(new DraftCube.CardIdentity("Obstinate Baloth","")); + cubeCards.add(new DraftCube.CardIdentity("Old Man of the Sea","")); + cubeCards.add(new DraftCube.CardIdentity("Olivia Voldaren","")); + cubeCards.add(new DraftCube.CardIdentity("Omnath, Locus of Rage","")); + cubeCards.add(new DraftCube.CardIdentity("Oona's Prowler","")); + cubeCards.add(new DraftCube.CardIdentity("Ophiomancer","")); + cubeCards.add(new DraftCube.CardIdentity("Opposition","")); + cubeCards.add(new DraftCube.CardIdentity("Oracle of Mul Daya","")); + cubeCards.add(new DraftCube.CardIdentity("Oust","")); + cubeCards.add(new DraftCube.CardIdentity("Outpost Siege","")); + cubeCards.add(new DraftCube.CardIdentity("Overgrown Battlement","")); + cubeCards.add(new DraftCube.CardIdentity("Overgrown Tomb","")); + cubeCards.add(new DraftCube.CardIdentity("Pack Rat","")); + cubeCards.add(new DraftCube.CardIdentity("Pact of Negation","")); + cubeCards.add(new DraftCube.CardIdentity("Panharmonicon","")); + cubeCards.add(new DraftCube.CardIdentity("Parallax Wave","")); + cubeCards.add(new DraftCube.CardIdentity("Part the Waterveil","")); + cubeCards.add(new DraftCube.CardIdentity("Path to Exile","")); + cubeCards.add(new DraftCube.CardIdentity("Pestermite","")); + cubeCards.add(new DraftCube.CardIdentity("Phantasmal Image","")); + cubeCards.add(new DraftCube.CardIdentity("Phyrexian Arena","")); + cubeCards.add(new DraftCube.CardIdentity("Phyrexian Metamorph","")); + cubeCards.add(new DraftCube.CardIdentity("Phyrexian Obliterator","")); + cubeCards.add(new DraftCube.CardIdentity("Phyrexian Rager","")); + cubeCards.add(new DraftCube.CardIdentity("Phyrexian Revoker","")); + cubeCards.add(new DraftCube.CardIdentity("Pia and Kiran Nalaar","")); + cubeCards.add(new DraftCube.CardIdentity("Pillar of Flame","")); + cubeCards.add(new DraftCube.CardIdentity("Plateau","")); + cubeCards.add(new DraftCube.CardIdentity("Polluted Delta","")); + cubeCards.add(new DraftCube.CardIdentity("Polukranos, World Eater","")); + cubeCards.add(new DraftCube.CardIdentity("Ponder","")); + cubeCards.add(new DraftCube.CardIdentity("Porcelain Legionnaire","")); + cubeCards.add(new DraftCube.CardIdentity("Precinct Captain","")); + cubeCards.add(new DraftCube.CardIdentity("Precursor Golem","")); + cubeCards.add(new DraftCube.CardIdentity("Preordain","")); + cubeCards.add(new DraftCube.CardIdentity("Primal Command","")); + cubeCards.add(new DraftCube.CardIdentity("Primeval Titan","")); + cubeCards.add(new DraftCube.CardIdentity("Profane Command","")); + cubeCards.add(new DraftCube.CardIdentity("Purphoros, God of the Forge","")); + cubeCards.add(new DraftCube.CardIdentity("Pyroclasm","")); + cubeCards.add(new DraftCube.CardIdentity("Qasali Pridemage","")); + cubeCards.add(new DraftCube.CardIdentity("Quarantine Field","")); + cubeCards.add(new DraftCube.CardIdentity("Raging Ravine","")); + cubeCards.add(new DraftCube.CardIdentity("Raise the Alarm","")); + cubeCards.add(new DraftCube.CardIdentity("Rakdos's Return","")); + cubeCards.add(new DraftCube.CardIdentity("Ral Zarek","")); + cubeCards.add(new DraftCube.CardIdentity("Rampaging Baloths","")); + cubeCards.add(new DraftCube.CardIdentity("Rampant Growth","")); + cubeCards.add(new DraftCube.CardIdentity("Ranger of Eos","")); + cubeCards.add(new DraftCube.CardIdentity("Ratchet Bomb","")); + cubeCards.add(new DraftCube.CardIdentity("Ravages of War","")); + cubeCards.add(new DraftCube.CardIdentity("Read the Bones","")); + cubeCards.add(new DraftCube.CardIdentity("Reanimate","")); + cubeCards.add(new DraftCube.CardIdentity("Reckless Bushwhacker","")); + cubeCards.add(new DraftCube.CardIdentity("Reclamation Sage","")); + cubeCards.add(new DraftCube.CardIdentity("Recruiter of the Guard","")); + cubeCards.add(new DraftCube.CardIdentity("Recurring Nightmare","")); + cubeCards.add(new DraftCube.CardIdentity("Reflecting Pool","")); + cubeCards.add(new DraftCube.CardIdentity("Reflector Mage","")); + cubeCards.add(new DraftCube.CardIdentity("Regrowth","")); + cubeCards.add(new DraftCube.CardIdentity("Relentless Dead","")); + cubeCards.add(new DraftCube.CardIdentity("Relic of Progenitus","")); + cubeCards.add(new DraftCube.CardIdentity("Remand","")); + cubeCards.add(new DraftCube.CardIdentity("Remove Soul","")); + cubeCards.add(new DraftCube.CardIdentity("Repeal","")); + cubeCards.add(new DraftCube.CardIdentity("Restoration Angel","")); + cubeCards.add(new DraftCube.CardIdentity("Reveillark","")); + cubeCards.add(new DraftCube.CardIdentity("Rift Bolt","")); + cubeCards.add(new DraftCube.CardIdentity("Riftwing Cloudskate","")); + cubeCards.add(new DraftCube.CardIdentity("Rishadan Port","")); + cubeCards.add(new DraftCube.CardIdentity("Roast","")); + cubeCards.add(new DraftCube.CardIdentity("Rofellos, Llanowar Emissary","")); + cubeCards.add(new DraftCube.CardIdentity("Rootbound Crag","")); + cubeCards.add(new DraftCube.CardIdentity("Rune-Scarred Demon","")); + cubeCards.add(new DraftCube.CardIdentity("Sacred Foundry","")); + cubeCards.add(new DraftCube.CardIdentity("Sakura-Tribe Elder","")); + cubeCards.add(new DraftCube.CardIdentity("Sarkhan, the Dragonspeaker","")); + cubeCards.add(new DraftCube.CardIdentity("Savannah","")); + cubeCards.add(new DraftCube.CardIdentity("Scalding Tarn","")); + cubeCards.add(new DraftCube.CardIdentity("Scavenging Ooze","")); + cubeCards.add(new DraftCube.CardIdentity("Scrapheap Scrounger","")); + cubeCards.add(new DraftCube.CardIdentity("Scroll Rack","")); + cubeCards.add(new DraftCube.CardIdentity("Scrubland","")); + cubeCards.add(new DraftCube.CardIdentity("Sea Gate Oracle","")); + cubeCards.add(new DraftCube.CardIdentity("Seal of Fire","")); + cubeCards.add(new DraftCube.CardIdentity("Search for Tomorrow","")); + cubeCards.add(new DraftCube.CardIdentity("Searing Spear","")); + cubeCards.add(new DraftCube.CardIdentity("Secure the Wastes","")); + cubeCards.add(new DraftCube.CardIdentity("See the Unwritten","")); + cubeCards.add(new DraftCube.CardIdentity("Seeker of the Way","")); + cubeCards.add(new DraftCube.CardIdentity("Selfless Spirit","")); + cubeCards.add(new DraftCube.CardIdentity("Selvala, Heart of the Wilds","")); + cubeCards.add(new DraftCube.CardIdentity("Sensei's Divining Top","")); + cubeCards.add(new DraftCube.CardIdentity("Serendib Efreet","")); + cubeCards.add(new DraftCube.CardIdentity("Serum Visions","")); + cubeCards.add(new DraftCube.CardIdentity("Shadowmage Infiltrator","")); + cubeCards.add(new DraftCube.CardIdentity("Shaman of Forgotten Ways","")); + cubeCards.add(new DraftCube.CardIdentity("Shambling Vent","")); + cubeCards.add(new DraftCube.CardIdentity("Shardless Agent","")); + cubeCards.add(new DraftCube.CardIdentity("Shelldock Isle","")); + cubeCards.add(new DraftCube.CardIdentity("Sheoldred, Whispering One","")); + cubeCards.add(new DraftCube.CardIdentity("Shriekmaw","")); + cubeCards.add(new DraftCube.CardIdentity("Sidisi, Undead Vizier","")); + cubeCards.add(new DraftCube.CardIdentity("Siege-Gang Commander","")); + cubeCards.add(new DraftCube.CardIdentity("Silverblade Paladin","")); + cubeCards.add(new DraftCube.CardIdentity("Skinrender","")); + cubeCards.add(new DraftCube.CardIdentity("Slagstorm","")); + cubeCards.add(new DraftCube.CardIdentity("Slaughter Pact","")); + cubeCards.add(new DraftCube.CardIdentity("Smuggler's Copter","")); + cubeCards.add(new DraftCube.CardIdentity("Snapcaster Mage","")); + cubeCards.add(new DraftCube.CardIdentity("Soldier of the Pantheon","")); + cubeCards.add(new DraftCube.CardIdentity("Solemn Simulacrum","")); + cubeCards.add(new DraftCube.CardIdentity("Song of the Dryads","")); + cubeCards.add(new DraftCube.CardIdentity("Sorin Markov","")); + cubeCards.add(new DraftCube.CardIdentity("Sorin, Solemn Visitor","")); + cubeCards.add(new DraftCube.CardIdentity("Soulfire Grand Master","")); + cubeCards.add(new DraftCube.CardIdentity("Sower of Temptation","")); + cubeCards.add(new DraftCube.CardIdentity("Spear of Heliod","")); + cubeCards.add(new DraftCube.CardIdentity("Spectral Procession","")); + cubeCards.add(new DraftCube.CardIdentity("Spell Pierce","")); + cubeCards.add(new DraftCube.CardIdentity("Spell Queller","")); + cubeCards.add(new DraftCube.CardIdentity("Spellskite","")); + cubeCards.add(new DraftCube.CardIdentity("Sphinx's Revelation","")); + cubeCards.add(new DraftCube.CardIdentity("Splinter Twin","")); + cubeCards.add(new DraftCube.CardIdentity("Staggershock","")); + cubeCards.add(new DraftCube.CardIdentity("Steam Vents","")); + cubeCards.add(new DraftCube.CardIdentity("Stirring Wildwood","")); + cubeCards.add(new DraftCube.CardIdentity("Stoke the Flames","")); + cubeCards.add(new DraftCube.CardIdentity("Stomping Ground","")); + cubeCards.add(new DraftCube.CardIdentity("Stormbreath Dragon","")); + cubeCards.add(new DraftCube.CardIdentity("Stormchaser Mage","")); + cubeCards.add(new DraftCube.CardIdentity("Stratus Dancer","")); + cubeCards.add(new DraftCube.CardIdentity("Stroke of Genius","")); + cubeCards.add(new DraftCube.CardIdentity("Stromkirk Noble","")); + cubeCards.add(new DraftCube.CardIdentity("Student of Warfare","")); + cubeCards.add(new DraftCube.CardIdentity("Sublime Archangel","")); + cubeCards.add(new DraftCube.CardIdentity("Sulfur Falls","")); + cubeCards.add(new DraftCube.CardIdentity("Summoning Trap","")); + cubeCards.add(new DraftCube.CardIdentity("Sun Titan","")); + cubeCards.add(new DraftCube.CardIdentity("Sundering Titan","")); + cubeCards.add(new DraftCube.CardIdentity("Sunpetal Grove","")); + cubeCards.add(new DraftCube.CardIdentity("Supreme Verdict","")); + cubeCards.add(new DraftCube.CardIdentity("Surrak, the Hunt Caller","")); + cubeCards.add(new DraftCube.CardIdentity("Swords to Plowshares","")); + cubeCards.add(new DraftCube.CardIdentity("Sylvan Advocate","")); + cubeCards.add(new DraftCube.CardIdentity("Sylvan Caryatid","")); + cubeCards.add(new DraftCube.CardIdentity("Sylvan Library","")); + cubeCards.add(new DraftCube.CardIdentity("Taiga","")); + cubeCards.add(new DraftCube.CardIdentity("Talrand, Sky Summoner","")); + cubeCards.add(new DraftCube.CardIdentity("Tamiyo, the Moon Sage","")); + cubeCards.add(new DraftCube.CardIdentity("Tangle Wire","")); + cubeCards.add(new DraftCube.CardIdentity("Tarmogoyf","")); + cubeCards.add(new DraftCube.CardIdentity("Tasigur, the Golden Fang","")); + cubeCards.add(new DraftCube.CardIdentity("Tectonic Edge","")); + cubeCards.add(new DraftCube.CardIdentity("Teferi, Mage of Zhalfir","")); + cubeCards.add(new DraftCube.CardIdentity("Temple Garden","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Abandon","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Deceit","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Enlightenment","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Epiphany","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Malady","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Malice","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Mystery","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Plenty","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Silence","")); + cubeCards.add(new DraftCube.CardIdentity("Temple of Triumph","")); + cubeCards.add(new DraftCube.CardIdentity("Terastodon","")); + cubeCards.add(new DraftCube.CardIdentity("Terminate","")); + cubeCards.add(new DraftCube.CardIdentity("Terminus","")); + cubeCards.add(new DraftCube.CardIdentity("Thalia, Guardian of Thraben","")); + cubeCards.add(new DraftCube.CardIdentity("Thalia, Heretic Cathar","")); + cubeCards.add(new DraftCube.CardIdentity("Thassa, God of the Sea","")); + cubeCards.add(new DraftCube.CardIdentity("Thing in the Ice","")); + cubeCards.add(new DraftCube.CardIdentity("Thirst for Knowledge","")); + cubeCards.add(new DraftCube.CardIdentity("Thoughtseize","")); + cubeCards.add(new DraftCube.CardIdentity("Thragtusk","")); + cubeCards.add(new DraftCube.CardIdentity("Threads of Disloyalty","")); + cubeCards.add(new DraftCube.CardIdentity("Thrun, the Last Troll","")); + cubeCards.add(new DraftCube.CardIdentity("Thunderbreak Regent","")); + cubeCards.add(new DraftCube.CardIdentity("Thundermaw Hellkite","")); + cubeCards.add(new DraftCube.CardIdentity("Tidehollow Sculler","")); + cubeCards.add(new DraftCube.CardIdentity("Time Warp","")); + cubeCards.add(new DraftCube.CardIdentity("Tireless Tracker","")); + cubeCards.add(new DraftCube.CardIdentity("Tooth and Nail","")); + cubeCards.add(new DraftCube.CardIdentity("Toxic Deluge","")); + cubeCards.add(new DraftCube.CardIdentity("Treachery","")); + cubeCards.add(new DraftCube.CardIdentity("Tropical Island","")); + cubeCards.add(new DraftCube.CardIdentity("Trygon Predator","")); + cubeCards.add(new DraftCube.CardIdentity("Tundra","")); + cubeCards.add(new DraftCube.CardIdentity("Ugin, the Spirit Dragon","")); + cubeCards.add(new DraftCube.CardIdentity("Ulamog, the Ceaseless Hunger","")); + cubeCards.add(new DraftCube.CardIdentity("Ultimate Price","")); + cubeCards.add(new DraftCube.CardIdentity("Unburial Rites","")); + cubeCards.add(new DraftCube.CardIdentity("Underground Sea","")); + cubeCards.add(new DraftCube.CardIdentity("Underworld Connections","")); + cubeCards.add(new DraftCube.CardIdentity("Unexpectedly Absent","")); + cubeCards.add(new DraftCube.CardIdentity("Upheaval","")); + cubeCards.add(new DraftCube.CardIdentity("Utopia Sprawl","")); + cubeCards.add(new DraftCube.CardIdentity("Vampire Hexmage","")); + cubeCards.add(new DraftCube.CardIdentity("Vampire Nighthawk","")); + cubeCards.add(new DraftCube.CardIdentity("Vapor Snag","")); + cubeCards.add(new DraftCube.CardIdentity("Vendilion Clique","")); + cubeCards.add(new DraftCube.CardIdentity("Venser, Shaper Savant","")); + cubeCards.add(new DraftCube.CardIdentity("Verdant Catacombs","")); + cubeCards.add(new DraftCube.CardIdentity("Verdurous Gearhulk","")); + cubeCards.add(new DraftCube.CardIdentity("Victimize","")); + cubeCards.add(new DraftCube.CardIdentity("Vindicate","")); + cubeCards.add(new DraftCube.CardIdentity("Volcanic Island","")); + cubeCards.add(new DraftCube.CardIdentity("Volrath's Stronghold","")); + cubeCards.add(new DraftCube.CardIdentity("Vorinclex, Voice of Hunger","")); + cubeCards.add(new DraftCube.CardIdentity("Vraska the Unseen","")); + cubeCards.add(new DraftCube.CardIdentity("Wake Thrasher","")); + cubeCards.add(new DraftCube.CardIdentity("Wall of Blossoms","")); + cubeCards.add(new DraftCube.CardIdentity("Wall of Omens","")); + cubeCards.add(new DraftCube.CardIdentity("Wandering Fumarole","")); + cubeCards.add(new DraftCube.CardIdentity("Wasteland","")); + cubeCards.add(new DraftCube.CardIdentity("Watery Grave","")); + cubeCards.add(new DraftCube.CardIdentity("Westvale Abbey","")); + cubeCards.add(new DraftCube.CardIdentity("Wharf Infiltrator","")); + cubeCards.add(new DraftCube.CardIdentity("Whip of Erebos","")); + cubeCards.add(new DraftCube.CardIdentity("Whirler Rogue","")); + cubeCards.add(new DraftCube.CardIdentity("Whisperwood Elemental","")); + cubeCards.add(new DraftCube.CardIdentity("Windbrisk Heights","")); + cubeCards.add(new DraftCube.CardIdentity("Windswept Heath","")); + cubeCards.add(new DraftCube.CardIdentity("Wolfir Silverheart","")); + cubeCards.add(new DraftCube.CardIdentity("Wood Elves","")); + cubeCards.add(new DraftCube.CardIdentity("Wooded Foothills","")); + cubeCards.add(new DraftCube.CardIdentity("Woodfall Primus","")); + cubeCards.add(new DraftCube.CardIdentity("Woodland Cemetery","")); + cubeCards.add(new DraftCube.CardIdentity("Wrath of God","")); + cubeCards.add(new DraftCube.CardIdentity("Wretched Confluence","")); + cubeCards.add(new DraftCube.CardIdentity("Wurmcoil Engine","")); + cubeCards.add(new DraftCube.CardIdentity("Xenagos, the Reveler","")); + cubeCards.add(new DraftCube.CardIdentity("Yavimaya Elder","")); + cubeCards.add(new DraftCube.CardIdentity("Yosei, the Morning Star","")); + cubeCards.add(new DraftCube.CardIdentity("Young Pyromancer","")); + cubeCards.add(new DraftCube.CardIdentity("Zealous Conscripts","")); + } +} diff --git a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/LegacyCubeSeptember2016.java b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/LegacyCubeSeptember2016.java index de627d557cd..172133aa831 100644 --- a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/LegacyCubeSeptember2016.java +++ b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/LegacyCubeSeptember2016.java @@ -89,6 +89,7 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Bloodbraid Elf","")); cubeCards.add(new DraftCube.CardIdentity("Bloodghast","")); cubeCards.add(new DraftCube.CardIdentity("Bloodstained Mire","")); + cubeCards.add(new DraftCube.CardIdentity("Bloom Tender","")); cubeCards.add(new DraftCube.CardIdentity("Bogardan Hellkite","")); cubeCards.add(new DraftCube.CardIdentity("Bone Shredder","")); cubeCards.add(new DraftCube.CardIdentity("Bonesplitter","")); @@ -102,6 +103,7 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Bruna, the Fading Light","")); cubeCards.add(new DraftCube.CardIdentity("Buried Alive","")); cubeCards.add(new DraftCube.CardIdentity("Burst Lightning","")); + cubeCards.add(new DraftCube.CardIdentity("Careful Consideration","")); cubeCards.add(new DraftCube.CardIdentity("Careful Study","")); cubeCards.add(new DraftCube.CardIdentity("Catacomb Sifter","")); cubeCards.add(new DraftCube.CardIdentity("Celestial Colonnade","")); @@ -141,7 +143,6 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Cursed Scroll","")); cubeCards.add(new DraftCube.CardIdentity("Cyclonic Rift","")); cubeCards.add(new DraftCube.CardIdentity("Damnation","")); - cubeCards.add(new DraftCube.CardIdentity("Dance of the Dead","")); cubeCards.add(new DraftCube.CardIdentity("Dark Confidant","")); cubeCards.add(new DraftCube.CardIdentity("Dark Petition","")); cubeCards.add(new DraftCube.CardIdentity("Dark Ritual","")); @@ -157,7 +158,6 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Desecration Demon","")); cubeCards.add(new DraftCube.CardIdentity("Devil's Play","")); cubeCards.add(new DraftCube.CardIdentity("Devoted Druid","")); - cubeCards.add(new DraftCube.CardIdentity("Diabolic Servitude","")); cubeCards.add(new DraftCube.CardIdentity("Dictate of Heliod","")); cubeCards.add(new DraftCube.CardIdentity("Disciple of Bolas","")); cubeCards.add(new DraftCube.CardIdentity("Disfigure","")); @@ -184,13 +184,12 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Duplicant","")); cubeCards.add(new DraftCube.CardIdentity("Duress","")); cubeCards.add(new DraftCube.CardIdentity("Duskwatch Recruiter","")); + cubeCards.add(new DraftCube.CardIdentity("Edric, Spymaster of Trest","")); cubeCards.add(new DraftCube.CardIdentity("Elder Deep-Fiend","")); cubeCards.add(new DraftCube.CardIdentity("Eldrazi Monument","")); - cubeCards.add(new DraftCube.CardIdentity("Edric, Spymaster of Trest","")); cubeCards.add(new DraftCube.CardIdentity("Eldritch Evolution","")); cubeCards.add(new DraftCube.CardIdentity("Electrolyze","")); cubeCards.add(new DraftCube.CardIdentity("Elesh Norn, Grand Cenobite","")); - cubeCards.add(new DraftCube.CardIdentity("Elite Vanguard","")); cubeCards.add(new DraftCube.CardIdentity("Elixir of Immortality","")); cubeCards.add(new DraftCube.CardIdentity("Elspeth Tirel","")); cubeCards.add(new DraftCube.CardIdentity("Elspeth, Knight-Errant","")); @@ -244,7 +243,6 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Gatekeeper of Malakir","")); cubeCards.add(new DraftCube.CardIdentity("Gather the Townsfolk","")); cubeCards.add(new DraftCube.CardIdentity("Geist of Saint Traft","")); - cubeCards.add(new DraftCube.CardIdentity("Genesis Hydra","")); cubeCards.add(new DraftCube.CardIdentity("Genesis Wave","")); cubeCards.add(new DraftCube.CardIdentity("Geralf's Messenger","")); cubeCards.add(new DraftCube.CardIdentity("Gideon, Ally of Zendikar","")); @@ -293,6 +291,7 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Huntmaster of the Fells","")); cubeCards.add(new DraftCube.CardIdentity("Hymn to Tourach","")); cubeCards.add(new DraftCube.CardIdentity("Hypnotic Specter","")); + cubeCards.add(new DraftCube.CardIdentity("Icefall Regent","")); cubeCards.add(new DraftCube.CardIdentity("Imperial Recruiter","")); cubeCards.add(new DraftCube.CardIdentity("Impulse","")); cubeCards.add(new DraftCube.CardIdentity("Incendiary Flow","")); @@ -332,6 +331,7 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Krenko's Command","")); cubeCards.add(new DraftCube.CardIdentity("Kytheon, Hero of Akros","")); cubeCards.add(new DraftCube.CardIdentity("Land Tax","")); + cubeCards.add(new DraftCube.CardIdentity("Languish","")); cubeCards.add(new DraftCube.CardIdentity("Lavaclaw Reaches","")); cubeCards.add(new DraftCube.CardIdentity("Legacy's Allure","")); cubeCards.add(new DraftCube.CardIdentity("Leonin Relic-Warder","")); @@ -445,7 +445,6 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Primal Command","")); cubeCards.add(new DraftCube.CardIdentity("Primeval Titan","")); cubeCards.add(new DraftCube.CardIdentity("Profane Command","")); - cubeCards.add(new DraftCube.CardIdentity("Puppeteer Clique","")); cubeCards.add(new DraftCube.CardIdentity("Purphoros, God of the Forge","")); cubeCards.add(new DraftCube.CardIdentity("Pyroclasm","")); cubeCards.add(new DraftCube.CardIdentity("Qasali Pridemage","")); @@ -461,8 +460,8 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Ravages of War","")); cubeCards.add(new DraftCube.CardIdentity("Read the Bones","")); cubeCards.add(new DraftCube.CardIdentity("Reanimate","")); - cubeCards.add(new DraftCube.CardIdentity("Reclamation Sage","")); cubeCards.add(new DraftCube.CardIdentity("Reckless Bushwhacker","")); + cubeCards.add(new DraftCube.CardIdentity("Reclamation Sage","")); cubeCards.add(new DraftCube.CardIdentity("Recurring Nightmare","")); cubeCards.add(new DraftCube.CardIdentity("Reflecting Pool","")); cubeCards.add(new DraftCube.CardIdentity("Reflector Mage","")); @@ -523,9 +522,9 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Sower of Temptation","")); cubeCards.add(new DraftCube.CardIdentity("Spear of Heliod","")); cubeCards.add(new DraftCube.CardIdentity("Spectral Procession","")); - cubeCards.add(new DraftCube.CardIdentity("Spellskite","")); cubeCards.add(new DraftCube.CardIdentity("Spell Pierce","")); cubeCards.add(new DraftCube.CardIdentity("Spell Queller","")); + cubeCards.add(new DraftCube.CardIdentity("Spellskite","")); cubeCards.add(new DraftCube.CardIdentity("Sphinx's Revelation","")); cubeCards.add(new DraftCube.CardIdentity("Splinter Twin","")); cubeCards.add(new DraftCube.CardIdentity("Staggershock","")); @@ -606,6 +605,7 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Vendilion Clique","")); cubeCards.add(new DraftCube.CardIdentity("Venser, Shaper Savant","")); cubeCards.add(new DraftCube.CardIdentity("Verdant Catacombs","")); + cubeCards.add(new DraftCube.CardIdentity("Victimize","")); cubeCards.add(new DraftCube.CardIdentity("Vindicate","")); cubeCards.add(new DraftCube.CardIdentity("Volcanic Island","")); cubeCards.add(new DraftCube.CardIdentity("Volrath's Stronghold","")); @@ -614,7 +614,6 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Wake Thrasher","")); cubeCards.add(new DraftCube.CardIdentity("Wall of Blossoms","")); cubeCards.add(new DraftCube.CardIdentity("Wall of Omens","")); - cubeCards.add(new DraftCube.CardIdentity("Wall of Roots","")); cubeCards.add(new DraftCube.CardIdentity("Wandering Fumarole","")); cubeCards.add(new DraftCube.CardIdentity("Wasteland","")); cubeCards.add(new DraftCube.CardIdentity("Watery Grave","")); @@ -634,6 +633,7 @@ public class LegacyCubeSeptember2016 extends DraftCube { cubeCards.add(new DraftCube.CardIdentity("Wretched Confluence","")); cubeCards.add(new DraftCube.CardIdentity("Wurmcoil Engine","")); cubeCards.add(new DraftCube.CardIdentity("Xenagos, the Reveler","")); + cubeCards.add(new DraftCube.CardIdentity("Xiahou Dun, the One-Eyed","")); cubeCards.add(new DraftCube.CardIdentity("Yavimaya Elder","")); cubeCards.add(new DraftCube.CardIdentity("Yosei, the Morning Star","")); cubeCards.add(new DraftCube.CardIdentity("Young Pyromancer","")); diff --git a/Mage.Server.Plugins/Mage.Tournament.Constructed/pom.xml b/Mage.Server.Plugins/Mage.Tournament.Constructed/pom.xml index 0f0513588a6..a4dbfc5f2d5 100644 --- a/Mage.Server.Plugins/Mage.Tournament.Constructed/pom.xml +++ b/Mage.Server.Plugins/Mage.Tournament.Constructed/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-tournament-constructed diff --git a/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml b/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml index db716440c0f..4acdc3f9b1e 100644 --- a/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml +++ b/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml @@ -7,7 +7,7 @@ org.mage mage-server-plugins - 1.4.20 + 1.4.21 mage-tournament-sealed diff --git a/Mage.Server.Plugins/pom.xml b/Mage.Server.Plugins/pom.xml index a56b5b66803..fa315738557 100644 --- a/Mage.Server.Plugins/pom.xml +++ b/Mage.Server.Plugins/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 mage-server-plugins diff --git a/Mage.Server/pom.xml b/Mage.Server/pom.xml index fbd5e364628..8815a14850e 100644 --- a/Mage.Server/pom.xml +++ b/Mage.Server/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 mage-server @@ -229,8 +229,8 @@ org.apache.maven.plugins maven-compiler-plugin - 1.7 - 1.7 + 1.8 + 1.8 diff --git a/Mage.Server/src/main/java/mage/server/AuthorizedUserRepository.java b/Mage.Server/src/main/java/mage/server/AuthorizedUserRepository.java index 4829a2fbdfc..a0817049441 100644 --- a/Mage.Server/src/main/java/mage/server/AuthorizedUserRepository.java +++ b/Mage.Server/src/main/java/mage/server/AuthorizedUserRepository.java @@ -33,7 +33,7 @@ public enum AuthorizedUserRepository { private Dao dao; - private AuthorizedUserRepository() { + AuthorizedUserRepository() { File file = new File("db"); if (!file.exists()) { file.mkdirs(); diff --git a/Mage.Server/src/main/java/mage/server/ChatManager.java b/Mage.Server/src/main/java/mage/server/ChatManager.java index 6ee8435d10e..fe8305bdc8d 100644 --- a/Mage.Server/src/main/java/mage/server/ChatManager.java +++ b/Mage.Server/src/main/java/mage/server/ChatManager.java @@ -35,6 +35,7 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; + import mage.cards.repository.CardInfo; import mage.cards.repository.CardRepository; import mage.server.util.SystemUtil; @@ -44,13 +45,12 @@ import mage.view.ChatMessage.SoundToPlay; import org.apache.log4j.Logger; /** - * * @author BetaSteward_at_googlemail.com */ public class ChatManager { private static final Logger logger = Logger.getLogger(ChatManager.class); - private static HashMap userMessages = new HashMap<>(); + private static final HashMap userMessages = new HashMap<>(); private static final ChatManager INSTANCE = new ChatManager(); @@ -116,9 +116,9 @@ public class ChatManager { } return false; } - - Pattern cardNamePattern = Pattern.compile("\\[(.*?)\\]"); - + + final Pattern cardNamePattern = Pattern.compile("\\[(.*?)\\]"); + public void broadcast(UUID chatId, String userName, String message, MessageColor color, boolean withTime, MessageType messageType, SoundToPlay soundToPlay) { ChatSession chatSession = chatSessions.get(chatId); if (chatSession != null) { @@ -132,7 +132,7 @@ public class ChatManager { } } - if (!messageType.equals(MessageType.GAME)) { + if (messageType != MessageType.GAME) { User user = UserManager.getInstance().getUserByName(userName); if (message != null && userName != null && !userName.equals("")) { @@ -177,7 +177,7 @@ public class ChatManager { } } - if (messageType.equals(MessageType.TALK)) { + if (messageType == MessageType.TALK) { if (user != null) { if (user.getChatLockedUntil() != null) { if (user.getChatLockedUntil().compareTo(Calendar.getInstance().getTime()) > 0) { @@ -249,7 +249,6 @@ public class ChatManager { } /** - * * use mainly for announcing that a user connection was lost or that a user * has reconnected * diff --git a/Mage.Server/src/main/java/mage/server/ChatSession.java b/Mage.Server/src/main/java/mage/server/ChatSession.java index 4db5716b4b6..9c2a6e88667 100644 --- a/Mage.Server/src/main/java/mage/server/ChatSession.java +++ b/Mage.Server/src/main/java/mage/server/ChatSession.java @@ -27,12 +27,6 @@ */ package mage.server; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashSet; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; import mage.interfaces.callback.ClientCallback; import mage.view.ChatMessage; import mage.view.ChatMessage.MessageColor; @@ -40,8 +34,14 @@ import mage.view.ChatMessage.MessageType; import mage.view.ChatMessage.SoundToPlay; import org.apache.log4j.Logger; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashSet; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + /** - * * @author BetaSteward_at_googlemail.com */ public class ChatSession { @@ -79,7 +79,7 @@ public class ChatSession { } if (userId != null && clients.containsKey(userId)) { String userName = clients.get(userId); - if (!reason.equals(DisconnectReason.LostConnection)) { // for lost connection the user will be reconnected or session expire so no remove of chat yet + if (reason != DisconnectReason.LostConnection) { // for lost connection the user will be reconnected or session expire so no remove of chat yet clients.remove(userId); logger.debug(userName + "(" + reason.toString() + ")" + " removed from chatId " + chatId); } diff --git a/Mage.Server/src/main/java/mage/server/DisconnectReason.java b/Mage.Server/src/main/java/mage/server/DisconnectReason.java index 8f1bf126f21..c751814f7bb 100644 --- a/Mage.Server/src/main/java/mage/server/DisconnectReason.java +++ b/Mage.Server/src/main/java/mage/server/DisconnectReason.java @@ -6,5 +6,5 @@ package mage.server; */ public enum DisconnectReason { - LostConnection, Disconnected, CleaningUp, ConnectingOtherInstance, AdminDisconnect, SessionExpired, Undefined; + LostConnection, Disconnected, CleaningUp, ConnectingOtherInstance, AdminDisconnect, SessionExpired, Undefined } diff --git a/Mage.Server/src/main/java/mage/server/ExtensionPackage.java b/Mage.Server/src/main/java/mage/server/ExtensionPackage.java index 1d49c39c5b6..1a9d0c4c5ca 100644 --- a/Mage.Server/src/main/java/mage/server/ExtensionPackage.java +++ b/Mage.Server/src/main/java/mage/server/ExtensionPackage.java @@ -40,9 +40,9 @@ import java.util.Map; * @author Lymia */ public abstract class ExtensionPackage { - protected List expansions = new ArrayList<>(); - protected Map deckTypes = new HashMap<>(); - protected Map draftCubes = new HashMap<>(); + protected final List expansions = new ArrayList<>(); + protected final Map deckTypes = new HashMap<>(); + protected final Map draftCubes = new HashMap<>(); /** * @return A list of expansions included in this custom set package. diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java index 7b77141f304..70b94c0b4be 100644 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -157,7 +157,7 @@ public class MageServerImpl implements MageServer { } return true; } - + @Override public boolean resetPassword(String sessionId, String email, String authToken, String password) throws MageException { if (!ConfigSettings.getInstance().isAuthenticationActivated()) { @@ -314,12 +314,9 @@ public class MageServerImpl implements MageServer { @Override public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - execute("removeTable", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().removeTable(userId, tableId); - } + execute("removeTable", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().removeTable(userId, tableId); }); } @@ -377,13 +374,10 @@ public class MageServerImpl implements MageServer { @Override public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException { - execute("updateDeck", sessionId, new Action() { - @Override - public void execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().updateDeck(userId, tableId, deckList); - logger.trace("Session " + sessionId + " updated deck"); - } + execute("updateDeck", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().updateDeck(userId, tableId, deckList); + logger.trace("Session " + sessionId + " updated deck"); }); } @@ -470,12 +464,9 @@ public class MageServerImpl implements MageServer { if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) { return false; } - execute("startMatch", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().startMatch(userId, roomId, tableId); - } + execute("startMatch", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().startMatch(userId, roomId, tableId); }); return true; } @@ -495,12 +486,9 @@ public class MageServerImpl implements MageServer { if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) { return false; } - execute("startTournament", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().startTournament(userId, roomId, tableId); - } + execute("startTournament", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().startTournament(userId, roomId, tableId); }); return true; } @@ -521,12 +509,7 @@ public class MageServerImpl implements MageServer { public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException { try { callExecutor.execute( - new Runnable() { - @Override - public void run() { - ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE, true, ChatMessage.MessageType.TALK, null); - } - } + () -> ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE, true, ChatMessage.MessageType.TALK, null) ); } catch (Exception ex) { handleException(ex); @@ -535,26 +518,20 @@ public class MageServerImpl implements MageServer { @Override public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException { - execute("joinChat", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ChatManager.getInstance().joinChat(chatId, userId); - } + execute("joinChat", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ChatManager.getInstance().joinChat(chatId, userId); }); } @Override public void leaveChat(final UUID chatId, final String sessionId) throws MageException { - execute("leaveChat", sessionId, new Action() { - @Override - public void execute() { - if (chatId != null) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ChatManager.getInstance().leaveChat(chatId, userId); - } else { - logger.warn("The chatId is null. sessionId = " + sessionId); - } + execute("leaveChat", sessionId, () -> { + if (chatId != null) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ChatManager.getInstance().leaveChat(chatId, userId); + } else { + logger.warn("The chatId is null. sessionId = " + sessionId); } }); } @@ -594,28 +571,22 @@ public class MageServerImpl implements MageServer { @Override public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws MageException { - execute("swapSeats", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); - } + execute("swapSeats", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); }); } @Override public boolean leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { TableState tableState = TableManager.getInstance().getController(tableId).getTableState(); - if (!tableState.equals(TableState.WAITING) && !tableState.equals(TableState.READY_TO_START)) { + if (tableState!=TableState.WAITING && tableState!=TableState.READY_TO_START) { // table was already started, so player can't leave anymore now return false; } - execute("leaveTable", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); - } + execute("leaveTable", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); }); return true; } @@ -633,34 +604,25 @@ public class MageServerImpl implements MageServer { @Override public void joinGame(final UUID gameId, final String sessionId) throws MageException { - execute("joinGame", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().joinGame(gameId, userId); - } + execute("joinGame", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().joinGame(gameId, userId); }); } @Override public void joinDraft(final UUID draftId, final String sessionId) throws MageException { - execute("joinDraft", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - DraftManager.getInstance().joinDraft(draftId, userId); - } + execute("joinDraft", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + DraftManager.getInstance().joinDraft(draftId, userId); }); } @Override public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException { - execute("joinTournament", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TournamentManager.getInstance().joinTournament(tournamentId, userId); - } + execute("joinTournament", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TournamentManager.getInstance().joinTournament(tournamentId, userId); }); } @@ -688,76 +650,61 @@ public class MageServerImpl implements MageServer { @Override public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException { - execute("sendPlayerUUID", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { + execute("sendPlayerUUID", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { // logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); - user.sendPlayerUUID(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + user.sendPlayerUUID(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @Override public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException { - execute("sendPlayerString", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerString(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + execute("sendPlayerString", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerString(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @Override public void sendPlayerManaType(final UUID gameId, final UUID playerId, final String sessionId, final ManaType data) throws MageException { - execute("sendPlayerManaType", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerManaType(gameId, playerId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + execute("sendPlayerManaType", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerManaType(gameId, playerId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @Override public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException { - execute("sendPlayerBoolean", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerBoolean(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + execute("sendPlayerBoolean", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerBoolean(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @Override public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException { - execute("sendPlayerInteger", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerInteger(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + execute("sendPlayerInteger", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerInteger(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @@ -780,81 +727,66 @@ public class MageServerImpl implements MageServer { @Override public void sendCardMark(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException { - execute("sendCardMark", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); - } else { - logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); - } + execute("sendCardMark", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); + } else { + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); } }); } @Override public void quitMatch(final UUID gameId, final String sessionId) throws MageException { - execute("quitMatch", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - GameManager.getInstance().quitMatch(gameId, session.getUserId()); - } else { - logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); - } + execute("quitMatch", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + GameManager.getInstance().quitMatch(gameId, session.getUserId()); + } else { + logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); } }); } @Override public void quitTournament(final UUID tournamentId, final String sessionId) throws MageException { - execute("quitTournament", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - TournamentManager.getInstance().quit(tournamentId, session.getUserId()); - } else { - logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId); - } + execute("quitTournament", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + TournamentManager.getInstance().quit(tournamentId, session.getUserId()); + } else { + logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId); } }); } @Override public void quitDraft(final UUID draftId, final String sessionId) throws MageException { - execute("quitDraft", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); - return; - } - UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); - Table table = TableManager.getInstance().getTable(tableId); - if (table.isTournament()) { - UUID tournamentId = table.getTournament().getId(); - TournamentManager.getInstance().quit(tournamentId, session.getUserId()); - } + execute("quitDraft", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session == null) { + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); + return; + } + UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); + Table table = TableManager.getInstance().getTable(tableId); + if (table.isTournament()) { + UUID tournamentId = table.getTournament().getId(); + TournamentManager.getInstance().quit(tournamentId, session.getUserId()); } }); } @Override public void sendPlayerAction(final PlayerAction playerAction, final UUID gameId, final String sessionId, final Object data) throws MageException { - execute("sendPlayerAction", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); - return; - } - GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); + execute("sendPlayerAction", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session == null) { + logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); + return; } + GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); }); } @@ -882,94 +814,70 @@ public class MageServerImpl implements MageServer { @Override public void watchGame(final UUID gameId, final String sessionId) throws MageException { - execute("watchGame", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().watchGame(gameId, userId); - } + execute("watchGame", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().watchGame(gameId, userId); }); } @Override public void stopWatching(final UUID gameId, final String sessionId) throws MageException { - execute("stopWatching", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - GameManager.getInstance().stopWatching(gameId, userId); - user.removeGameWatchInfo(gameId); - } - + execute("stopWatching", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + GameManager.getInstance().stopWatching(gameId, userId); + user.removeGameWatchInfo(gameId); } + }); } @Override public void replayGame(final UUID gameId, final String sessionId) throws MageException { - execute("replayGame", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().replayGame(gameId, userId); - } + execute("replayGame", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().replayGame(gameId, userId); }); } @Override public void startReplay(final UUID gameId, final String sessionId) throws MageException { - execute("startReplay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().startReplay(gameId, userId); - } + execute("startReplay", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().startReplay(gameId, userId); }); } @Override public void stopReplay(final UUID gameId, final String sessionId) throws MageException { - execute("stopReplay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().stopReplay(gameId, userId); - } + execute("stopReplay", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().stopReplay(gameId, userId); }); } @Override public void nextPlay(final UUID gameId, final String sessionId) throws MageException { - execute("nextPlay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().nextPlay(gameId, userId); - } + execute("nextPlay", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().nextPlay(gameId, userId); }); } @Override public void previousPlay(final UUID gameId, final String sessionId) throws MageException { - execute("previousPlay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().previousPlay(gameId, userId); - } + execute("previousPlay", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().previousPlay(gameId, userId); }); } @Override public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException { - execute("skipForward", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().skipForward(gameId, userId, moves); - } + execute("skipForward", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().skipForward(gameId, userId, moves); }); } @@ -996,13 +904,10 @@ public class MageServerImpl implements MageServer { @Override public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException { - execute("cheat", sessionId, new Action() { - @Override - public void execute() { - if (testMode) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().cheat(gameId, userId, playerId, deckList); - } + execute("cheat", sessionId, () -> { + if (testMode) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().cheat(gameId, userId, playerId, deckList); } }); } @@ -1061,7 +966,8 @@ public class MageServerImpl implements MageServer { user.getGameInfo(), user.getUserState().toString(), user.getChatLockedUntil(), - user.getClientVersion() + user.getClientVersion(), + user.getEmail() )); } return users; @@ -1071,74 +977,73 @@ public class MageServerImpl implements MageServer { @Override public void disconnectUser(final String sessionId, final String userSessionId) throws MageException { - execute("disconnectUser", sessionId, new Action() { - @Override - public void execute() { - SessionManager.getInstance().disconnectUser(sessionId, userSessionId); - } - }); + execute("disconnectUser", sessionId, () -> SessionManager.getInstance().disconnectUser(sessionId, userSessionId)); } @Override public void muteUser(final String sessionId, final String userName, final long durationMinutes) throws MageException { - execute("muteUser", sessionId, new Action() { - @Override - public void execute() { - User user = UserManager.getInstance().getUserByName(userName); - if (user != null) { - Date muteUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); - user.showUserMessage("Admin info", "You were muted for chat messages until " + SystemUtil.dateFormat.format(muteUntil) + "."); - user.setChatLockedUntil(muteUntil); - } - + execute("muteUser", sessionId, () -> { + User user = UserManager.getInstance().getUserByName(userName); + if (user != null) { + Date muteUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); + user.showUserMessage("Admin info", "You were muted for chat messages until " + SystemUtil.dateFormat.format(muteUntil) + "."); + user.setChatLockedUntil(muteUntil); } + }); } @Override public void lockUser(final String sessionId, final String userName, final long durationMinutes) throws MageException { - execute("lockUser", sessionId, new Action() { - @Override - public void execute() { - User user = UserManager.getInstance().getUserByName(userName); - if (user != null) { - Date lockUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); - user.showUserMessage("Admin info", "Your user profile was locked until " + SystemUtil.dateFormat.format(lockUntil) + "."); - user.setLockedUntil(lockUntil); - if (user.isConnected()) { - SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); - } + execute("lockUser", sessionId, () -> { + User user = UserManager.getInstance().getUserByName(userName); + if (user != null) { + Date lockUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); + user.showUserMessage("Admin info", "Your user profile was locked until " + SystemUtil.dateFormat.format(lockUntil) + "."); + user.setLockedUntil(lockUntil); + if (user.isConnected()) { + SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); } - } + + }); + } + + @Override + public void setActivation(final String sessionId, final String userName, boolean active) throws MageException { + execute("setActivation", sessionId, () -> { + AuthorizedUser authorizedUser = AuthorizedUserRepository.instance.getByName(userName); + User user = UserManager.getInstance().getUserByName(userName); + if (user != null) { + user.setActive(active); + if (!user.isActive() && user.isConnected()) { + SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); + } + } else if (authorizedUser != null) { + User theUser = new User(userName, "localhost", authorizedUser); + theUser.setActive(active); + } + }); } @Override public void toggleActivation(final String sessionId, final String userName) throws MageException { - execute("toggleActivation", sessionId, new Action() { - @Override - public void execute() { - User user = UserManager.getInstance().getUserByName(userName); - if (user != null) { - user.setActive(!user.isActive()); - if (!user.isActive() && user.isConnected()) { - SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); - } + execute("toggleActivation", sessionId, () -> { + User user = UserManager.getInstance().getUserByName(userName); + if (user != null) { + user.setActive(!user.isActive()); + if (!user.isActive() && user.isConnected()) { + SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); } - } + }); } @Override public void endUserSession(final String sessionId, final String userSessionId) throws MageException { - execute("endUserSession", sessionId, new Action() { - @Override - public void execute() { - SessionManager.getInstance().endUserSession(sessionId, userSessionId); - } - }); + execute("endUserSession", sessionId, () -> SessionManager.getInstance().endUserSession(sessionId, userSessionId)); } /** @@ -1150,12 +1055,9 @@ public class MageServerImpl implements MageServer { */ @Override public void removeTable(final String sessionId, final UUID tableId) throws MageException { - execute("removeTable", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().removeTable(userId, tableId); - } + execute("removeTable", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().removeTable(userId, tableId); }); } @@ -1172,12 +1074,9 @@ public class MageServerImpl implements MageServer { @Override public void sendFeedbackMessage(final String sessionId, final String username, final String title, final String type, final String message, final String email) throws MageException { if (title != null && message != null) { - execute("sendFeedbackMessage", sessionId, new Action() { - @Override - public void execute() { - String host = SessionManager.getInstance().getSession(sessionId).getHost(); - FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); - } + execute("sendFeedbackMessage", sessionId, () -> { + String host = SessionManager.getInstance().getSession(sessionId).getHost(); + FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); }); } } @@ -1185,15 +1084,12 @@ public class MageServerImpl implements MageServer { @Override public void sendBroadcastMessage(final String sessionId, final String message) throws MageException { if (message != null) { - execute("sendBroadcastMessage", sessionId, new Action() { - @Override - public void execute() { - for (User user : UserManager.getInstance().getUsers()) { - if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { - user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED))); - } else { - user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE))); - } + execute("sendBroadcastMessage", sessionId, () -> { + for (User user : UserManager.getInstance().getUsers()) { + if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { + user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED))); + } else { + user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE))); } } }, true); @@ -1201,12 +1097,7 @@ public class MageServerImpl implements MageServer { } private void sendErrorMessageToClient(final String sessionId, final String message) throws MageException { - execute("sendErrorMessageToClient", sessionId, new Action() { - @Override - public void execute() { - SessionManager.getInstance().sendErrorMessageToClient(sessionId, message); - } - }); + execute("sendErrorMessageToClient", sessionId, () -> SessionManager.getInstance().sendErrorMessageToClient(sessionId, message)); } protected void execute(final String actionName, final String sessionId, final Action action, boolean checkAdminRights) throws MageException { @@ -1222,18 +1113,15 @@ public class MageServerImpl implements MageServer { if (SessionManager.getInstance().isValidSession(sessionId)) { try { callExecutor.execute( - new Runnable() { - @Override - public void run() { - if (SessionManager.getInstance().isValidSession(sessionId)) { - try { - action.execute(); - } catch (MageException me) { - throw new RuntimeException(me); + () -> { + if (SessionManager.getInstance().isValidSession(sessionId)) { + try { + action.execute(); + } catch (MageException me) { + throw new RuntimeException(me); + } } } - } - } ); } catch (Exception ex) { handleException(ex); diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 0da06d742ab..9c13dfb7aa3 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -92,7 +92,7 @@ public class Main { private static final File pluginFolder = new File("plugins"); private static final File extensionFolder = new File("extensions"); - public static PluginClassLoader classLoader = new PluginClassLoader(); + public static final PluginClassLoader classLoader = new PluginClassLoader(); public static TransporterServer server; protected static boolean testMode; protected static boolean fastDbMode; @@ -437,12 +437,7 @@ public class Main { directory.mkdirs(); } File[] files = directory.listFiles( - new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".game"); - } - } + (dir, name) -> name.endsWith(".game") ); for (File file : files) { file.delete(); diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 9baa6960273..8406cad4886 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -44,6 +44,7 @@ import mage.players.net.UserGroup; import mage.server.game.GamesRoomManager; import mage.server.util.ConfigSettings; import mage.server.util.SystemUtil; +import mage.util.RandomUtil; import org.apache.log4j.Logger; import org.jboss.remoting.callback.AsynchInvokerCallbackHandler; import org.jboss.remoting.callback.Callback; @@ -90,6 +91,9 @@ public class Session { sendErrorMessageToClient(returnMessage); return returnMessage; } + + RandomString randomString = new RandomString(10); + password = randomString.nextString(); returnMessage = validatePassword(password, userName); if (returnMessage != null) { sendErrorMessageToClient(returnMessage); @@ -103,6 +107,8 @@ public class Session { AuthorizedUserRepository.instance.add(userName, password, email); String subject = "XMage Registration Completed"; String text = "You are successfully registered as " + userName + "."; + text += " Your initial, generated password is: " + password; + boolean success; if (!ConfigSettings.getInstance().getMailUser().isEmpty()) { success = MailClient.sendMessage(email, subject, text); @@ -110,9 +116,14 @@ public class Session { success = MailgunClient.sendMessage(email, subject, text); } if (success) { - logger.info("Sent a registration confirmation email to " + email + " for " + userName); + String ok = "Sent a registration confirmation / initial password email to " + email + " for " + userName; + logger.info(ok); + sendInfoMessageToClient(ok); } else { - logger.error("Failed sending a registration confirmation email to " + email + " for " + userName); + String err = "Failed sending a registration confirmation / initial password email to " + email + " for " + userName; + logger.error(err); + sendErrorMessageToClient(err); + return err; } return null; } @@ -396,6 +407,13 @@ public class Session { fireCallback(new ClientCallback("showUserMessage", null, messageData)); } + public void sendInfoMessageToClient(String message) { + List messageData = new LinkedList<>(); + messageData.add("Information about connecting to the server"); + messageData.add(message); + fireCallback(new ClientCallback("showUserMessage", null, messageData)); + } + public static Throwable getBasicCause(Throwable cause) { Throwable t = cause; while (t.getCause() != null) { @@ -407,3 +425,35 @@ public class Session { return t; } } + +class RandomString { + + private static final char[] symbols; + + static { + StringBuilder tmp = new StringBuilder(); + for (char ch = '0'; ch <= '9'; ++ch) { + tmp.append(ch); + } + for (char ch = 'a'; ch <= 'z'; ++ch) { + tmp.append(ch); + } + symbols = tmp.toString().toCharArray(); + } + + private final char[] buf; + + public RandomString(int length) { + if (length < 8) { + length = 8; + } + buf = new char[length]; + } + + public String nextString() { + for (int idx = 0; idx < buf.length; ++idx) { + buf[idx] = symbols[RandomUtil.nextInt(symbols.length)]; + } + return new String(buf); + } +} diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index ad824fdcc76..4fdc16b1009 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -30,13 +30,13 @@ package mage.server; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; + import mage.MageException; import mage.players.net.UserData; import org.apache.log4j.Logger; import org.jboss.remoting.callback.InvokerCallbackHandler; /** - * * @author BetaSteward_at_googlemail.com */ public class SessionManager { @@ -47,6 +47,7 @@ public class SessionManager { public static SessionManager getInstance() { return INSTANCE; } + private final ConcurrentHashMap sessions = new ConcurrentHashMap<>(); public Session getSession(String sessionId) { @@ -127,7 +128,7 @@ public class SessionManager { public void disconnect(String sessionId, DisconnectReason reason) { Session session = sessions.get(sessionId); if (session != null) { - if (!reason.equals(DisconnectReason.AdminDisconnect)) { + if (reason != DisconnectReason.AdminDisconnect) { if (!sessions.containsKey(sessionId)) { // session was removed meanwhile by another thread so we can return return; diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index 6b1704182fc..bf42791c755 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -34,6 +34,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; + import mage.MageException; import mage.cards.decks.Deck; import mage.cards.decks.DeckCardLists; @@ -72,7 +73,6 @@ import mage.view.ChatMessage; import org.apache.log4j.Logger; /** - * * @author BetaSteward_at_googlemail.com */ public class TableController { @@ -90,7 +90,7 @@ public class TableController { private Tournament tournament; private ScheduledFuture futureTimeout; - protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); + protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); public TableController(UUID roomId, UUID userId, MatchOptions options) { this.userId = userId; @@ -128,20 +128,17 @@ public class TableController { private void init() { match.addTableEventListener( - new Listener() { - @Override - public void event(TableEvent event) { - try { - switch (event.getEventType()) { - case SIDEBOARD: - sideboard(event.getPlayerId(), event.getDeck()); - break; + (Listener) event -> { + try { + switch (event.getEventType()) { + case SIDEBOARD: + sideboard(event.getPlayerId(), event.getDeck()); + break; + } + } catch (MageException ex) { + logger.fatal("Table event listener error", ex); } - } catch (MageException ex) { - logger.fatal("Table event listener error", ex); } - } - } ); } @@ -297,14 +294,14 @@ public class TableController { user.showUserMessage("Join Table", message); return false; } - + // Check power level for table (currently only used for EDH/Commander table) int edhPowerLevel = table.getMatch().getOptions().getEdhPowerLevel(); if (edhPowerLevel > 0 && table.getValidator().getName().toLowerCase().equals("commander")) { int deckEdhPowerLevel = table.getValidator().getEdhPowerLevel(deck); if (deckEdhPowerLevel > edhPowerLevel) { String message = new StringBuilder("Your deck appears to be too powerful for this table.\n\nReduce the number of extra turn cards, infect, counters, fogs, reconsider your commander. ") - .append("\nThe table requirement has a maximum power level of ").append(edhPowerLevel).append (" whilst your deck has a calculated power level of ") + .append("\nThe table requirement has a maximum power level of ").append(edhPowerLevel).append(" whilst your deck has a calculated power level of ") .append(deckEdhPowerLevel).toString(); user.showUserMessage("Join Table", message); return false; @@ -415,7 +412,7 @@ public class TableController { } else { logger.fatal("Tournament == null table: " + table.getId() + " userId: " + userId); } - } else if (TableState.SIDEBOARDING.equals(table.getState())) { + } else if (TableState.SIDEBOARDING == table.getState()) { match.updateDeck(playerId, deck); } else { // deck was meanwhile submitted so the autoupdate can be ignored @@ -441,7 +438,7 @@ public class TableController { } } -// public boolean replayTable(UUID userId) { + // public boolean replayTable(UUID userId) { // if (table.getState() != TableState.FINISHED) { // return false; // } @@ -479,8 +476,8 @@ public class TableController { } if (table != null && this.userId != null && this.userId.equals(userId) // tourn. sub tables have no creator user - && (table.getState().equals(TableState.WAITING) - || table.getState().equals(TableState.READY_TO_START))) { + && (table.getState() == TableState.WAITING + || table.getState() == TableState.READY_TO_START)) { // table not started yet and user is the owner, remove the table TableManager.getInstance().removeTable(table.getId()); } else { @@ -503,7 +500,7 @@ public class TableController { logger.debug("User not found - userId: " + userId + " tableId:" + table.getId()); } userPlayerMap.remove(userId); - } else if (!table.getState().equals(TableState.FINISHED)) { + } else if (table.getState() != TableState.FINISHED) { if (table.isTournament()) { logger.debug("Quit tournament sub tables for userId: " + userId); TableManager.getInstance().userQuitTournamentSubTables(tournament.getId(), userId); @@ -520,7 +517,7 @@ public class TableController { } match.quitMatch(playerId); } else { - if (table.getState().equals(TableState.SIDEBOARDING)) { + if (table.getState() == TableState.SIDEBOARDING) { if (!matchPlayer.isDoneSideboarding()) { // submit deck to finish sideboarding and trigger match start / end matchPlayer.submitDeck(matchPlayer.getDeck()); @@ -549,7 +546,7 @@ public class TableController { } public synchronized void startMatch() { - if (table.getState().equals(TableState.STARTING)) { + if (table.getState() == TableState.STARTING) { try { if (table.isTournamentSubTable()) { logger.info("Tourn. match started id:" + match.getId() + " tournId: " + table.getTournament().getId()); @@ -633,7 +630,7 @@ public class TableController { public synchronized void startTournament(UUID userId) { try { - if (userId.equals(this.userId) && table.getState().equals(TableState.STARTING)) { + if (userId.equals(this.userId) && table.getState() == TableState.STARTING) { tournament.setStartTime(); TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId()); for (Entry entry : userPlayerMap.entrySet()) { @@ -765,7 +762,6 @@ public class TableController { /** * Tables of normal matches or tournament sub tables are no longer needed, * if the match ends. - * */ private void closeTable() { this.matchEnd(); @@ -781,7 +777,7 @@ public class TableController { if (!matchPlayer.hasQuit()) { User user = UserManager.getInstance().getUser(entry.getKey()); if (user != null) { - if (table.getState().equals(TableState.SIDEBOARDING)) { + if (table.getState()==TableState.SIDEBOARDING) { StringBuilder sb = new StringBuilder(); if (table.isTournamentSubTable()) { sb.append("Your tournament match of round "); @@ -814,12 +810,7 @@ public class TableController { cancelTimeout(); if (seconds > 0) { futureTimeout = timeoutExecutor.schedule( - new Runnable() { - @Override - public void run() { - autoSideboard(); - } - }, + () -> autoSideboard(), seconds, TimeUnit.SECONDS ); } @@ -851,7 +842,7 @@ public class TableController { } public void swapSeats(int seatNum1, int seatNum2) { - if (table.getState().equals(TableState.READY_TO_START)) { + if (table.getState()==TableState.READY_TO_START) { if (seatNum1 >= 0 && seatNum2 >= 0 && seatNum1 < table.getSeats().length && seatNum2 < table.getSeats().length) { Player swapPlayer = table.getSeats()[seatNum1].getPlayer(); String swapType = table.getSeats()[seatNum1].getPlayerType(); @@ -884,7 +875,7 @@ public class TableController { public boolean isTournamentStillValid() { if (table.getTournament() != null) { - if (!table.getState().equals(TableState.WAITING) && !table.getState().equals(TableState.READY_TO_START) && !table.getState().equals(TableState.STARTING)) { + if (table.getState() != TableState.WAITING && table.getState() != TableState.READY_TO_START && table.getState() != TableState.STARTING) { TournamentController tournamentController = TournamentManager.getInstance().getTournamentController(table.getTournament().getId()); if (tournamentController != null) { return tournamentController.isTournamentStillValid(table.getState()); @@ -931,7 +922,7 @@ public class TableController { int humanPlayers = 0; int aiPlayers = 0; int validHumanPlayers = 0; - if (!(table.getState().equals(TableState.WAITING) || table.getState().equals(TableState.STARTING) || table.getState().equals(TableState.READY_TO_START))) { + if (!(table.getState() == TableState.WAITING || table.getState() == TableState.STARTING || table.getState() == TableState.READY_TO_START)) { if (match == null) { logger.debug("- Match table with no match:"); logger.debug("-- matchId:" + match.getId() + " [" + match.getName() + "]"); @@ -955,9 +946,9 @@ public class TableController { } if (matchPlayer.getPlayer().isHuman()) { humanPlayers++; - if ((table.getState().equals(TableState.WAITING) - || table.getState().equals(TableState.STARTING) - || table.getState().equals(TableState.READY_TO_START)) + if ((table.getState() == TableState.WAITING + || table.getState() == TableState.STARTING + || table.getState() == TableState.READY_TO_START) || !match.isDoneSideboarding() || (!matchPlayer.hasQuit() && match.getGame() != null && matchPlayer.getPlayer().isInGame())) { User user = UserManager.getInstance().getUser(userPlayerEntry.getKey()); @@ -998,7 +989,7 @@ public class TableController { } public synchronized boolean changeTableStateToStarting() { - if (!getTable().getState().equals(TableState.READY_TO_START)) { + if (getTable().getState() != TableState.READY_TO_START) { // tournament is not ready, can't start return false; } diff --git a/Mage.Server/src/main/java/mage/server/TableManager.java b/Mage.Server/src/main/java/mage/server/TableManager.java index 1ba1e242b4e..0eb78b7c840 100644 --- a/Mage.Server/src/main/java/mage/server/TableManager.java +++ b/Mage.Server/src/main/java/mage/server/TableManager.java @@ -64,7 +64,7 @@ import org.apache.log4j.Logger; */ public class TableManager { - protected static ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); + protected static final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); // protected static ScheduledExecutorService expireExecutor = ThreadExecutor.getInstance().getExpireExecutor(); @@ -87,14 +87,11 @@ public class TableManager { } private TableManager() { - expireExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - try { - checkTableHealthState(); - } catch(Exception ex) { - logger.fatal("Check table health state job error:", ex); - } + expireExecutor.scheduleAtFixedRate(() -> { + try { + checkTableHealthState(); + } catch(Exception ex) { + logger.fatal("Check table health state job error:", ex); } }, EXPIRE_CHECK_PERIOD, EXPIRE_CHECK_PERIOD, TimeUnit.MINUTES); } @@ -347,7 +344,7 @@ public class TableManager { } // If table is not finished, the table has to be removed completly because it's not a normal state (if finished it will be removed in GamesRoomImpl.Update()) - if (!table.getState().equals(TableState.FINISHED)) { + if (table.getState()!=TableState.FINISHED) { if (game != null) { GameManager.getInstance().removeGame(game.getId()); } @@ -398,7 +395,7 @@ public class TableManager { tableCopy.addAll(tables.values()); for (Table table : tableCopy) { try { - if (!table.getState().equals(TableState.FINISHED)) { + if (table.getState()!=TableState.FINISHED) { // remove tables and games not valid anymore logger.debug(table.getId() + " [" + table.getName()+ "] " + formatter.format(table.getStartTime() == null ? table.getCreateTime() : table.getCreateTime()) +" (" + table.getState().toString() + ") " + (table.isTournament() ? "- Tournament":"")); TableController tableController = getController(table.getId()); diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java index af9677dec55..cc0cdd5795b 100644 --- a/Mage.Server/src/main/java/mage/server/User.java +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -37,6 +37,7 @@ import java.util.Map.Entry; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; + import mage.cards.decks.Deck; import mage.constants.ManaType; import mage.constants.TableState; @@ -61,7 +62,6 @@ import mage.view.TableClientMessage; import org.apache.log4j.Logger; /** - * * @author BetaSteward_at_googlemail.com */ public class User { @@ -70,7 +70,7 @@ public class User { public enum UserState { - Created, Connected, Disconnected, Reconnected, Expired; + Created, Connected, Disconnected, Reconnected, Expired } private final UUID userId; @@ -199,7 +199,7 @@ public class User { public void lostConnection() { // Because watched games don't get restored after reconnection call stop watching - for (Iterator iterator = watchedGames.iterator(); iterator.hasNext();) { + for (Iterator iterator = watchedGames.iterator(); iterator.hasNext(); ) { UUID gameId = iterator.next(); GameManager.getInstance().stopWatching(gameId, userId); iterator.remove(); @@ -208,7 +208,7 @@ public class User { } public boolean isConnected() { - return userState.equals(UserState.Connected) || userState.equals(UserState.Reconnected); + return userState == UserState.Connected || userState == UserState.Reconnected; } public String getDisconnectDuration() { @@ -762,7 +762,7 @@ public class User { public int getNumberOfNotStartedTables() { int number = 0; for (Table table : tables.values()) { - if (table.getState().equals(TableState.WAITING) || table.getState().equals(TableState.STARTING)) { + if (table.getState() == TableState.WAITING || table.getState() == TableState.STARTING) { number++; } } @@ -772,7 +772,7 @@ public class User { public int getNumberOfNotFinishedTables() { int number = 0; for (Table table : tables.values()) { - if (table.getState().equals(TableState.FINISHED)) { + if (table.getState() == TableState.FINISHED) { number++; } else { TableController tableController = TableManager.getInstance().getController(table.getId()); @@ -783,6 +783,13 @@ public class User { } return number; } + + public String getEmail() { + if (authorizedUser != null) { + return authorizedUser.email; + } + return ""; + } private void updateAuthorizedUser() { if (authorizedUser != null) { diff --git a/Mage.Server/src/main/java/mage/server/UserManager.java b/Mage.Server/src/main/java/mage/server/UserManager.java index 867a17c25b5..aadf74bc92c 100644 --- a/Mage.Server/src/main/java/mage/server/UserManager.java +++ b/Mage.Server/src/main/java/mage/server/UserManager.java @@ -52,7 +52,7 @@ import org.apache.log4j.Logger; */ public class UserManager { - protected static ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); + protected static final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); private static final Logger LOGGER = Logger.getLogger(UserManager.class); @@ -68,12 +68,7 @@ public class UserManager { } private UserManager() { - expireExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - checkExpired(); - } - }, 60, 60, TimeUnit.SECONDS); + expireExecutor.scheduleAtFixedRate(() -> checkExpired(), 60, 60, TimeUnit.SECONDS); } public User createUser(String userName, String host, AuthorizedUser authorizedUser) { @@ -137,21 +132,18 @@ public class UserManager { final User user = users.get(userId); if (user != null) { USER_EXECUTOR.execute( - new Runnable() { - @Override - public void run() { - try { - LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + "]"); - user.remove(reason); - LOGGER.debug("USER REMOVE END - " + user.getName()); - } catch (Exception ex) { - handleException(ex); - } finally { - users.remove(userId); - usersByName.remove(user.getName()); + () -> { + try { + LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + "]"); + user.remove(reason); + LOGGER.debug("USER REMOVE END - " + user.getName()); + } catch (Exception ex) { + handleException(ex); + } finally { + users.remove(userId); + usersByName.remove(user.getName()); + } } - } - } ); } else { LOGGER.warn("Trying to remove userId: " + userId + " - but it does not exist."); @@ -212,14 +204,11 @@ public class UserManager { } public void updateUserHistory() { - USER_EXECUTOR.execute(new Runnable() { - @Override - public void run() { - for (String updatedUser : UserStatsRepository.instance.updateUserStats()) { - User user = getUserByName(updatedUser); - if (user != null) { - user.resetUserStats(); - } + USER_EXECUTOR.execute(() -> { + for (String updatedUser : UserStatsRepository.instance.updateUserStats()) { + User user = getUserByName(updatedUser); + if (user != null) { + user.resetUserStats(); } } }); diff --git a/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java b/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java index ad10a8b3fc3..d38208c1c52 100644 --- a/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java +++ b/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java @@ -44,7 +44,7 @@ public class CubeFactory { private static final CubeFactory INSTANCE = new CubeFactory(); private static final Logger logger = Logger.getLogger(CubeFactory.class); - private Map draftCubes = new LinkedHashMap(); + private final Map draftCubes = new LinkedHashMap(); public static CubeFactory getInstance() { return INSTANCE; @@ -57,8 +57,8 @@ public class CubeFactory { DraftCube draftCube; Constructor con; try { - con = draftCubes.get(draftCubeName).getConstructor(new Class[]{}); - draftCube = (DraftCube)con.newInstance(new Object[] {}); + con = draftCubes.get(draftCubeName).getConstructor(); + draftCube = (DraftCube)con.newInstance(); } catch (Exception ex) { logger.fatal("CubeFactory error", ex); return null; @@ -73,8 +73,8 @@ public class CubeFactory { DraftCube draftCube; Constructor con; try { - con = draftCubes.get(draftCubeName).getConstructor(new Class[]{Deck.class}); - draftCube = (DraftCube)con.newInstance(new Object[] {cubeFromDeck}); + con = draftCubes.get(draftCubeName).getConstructor(Deck.class); + draftCube = (DraftCube)con.newInstance(cubeFromDeck); } catch (Exception ex) { logger.fatal("CubeFactory error", ex); return null; diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftController.java b/Mage.Server/src/main/java/mage/server/draft/DraftController.java index b96417b6798..02e45110a8a 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftController.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftController.java @@ -74,9 +74,7 @@ public class DraftController { private void init() { draft.addTableEventListener( - new Listener () { - @Override - public void event(TableEvent event) { + (Listener) event -> { try { switch (event.getEventType()) { case UPDATE: @@ -91,12 +89,9 @@ public class DraftController { logger.fatal("Table event listener error", ex); } } - } ); draft.addPlayerQueryEventListener( - new Listener () { - @Override - public void event(PlayerQueryEvent event) { + (Listener) event -> { try { switch (event.getQueryType()) { case PICK_CARD: @@ -108,7 +103,6 @@ public class DraftController { logger.fatal("Table event listener error", ex); } } - } ); for (DraftPlayer player: draft.getPlayers()) { if (!player.getPlayer().isHuman()) { @@ -156,12 +150,7 @@ public class DraftController { if (!draft.isStarted() && allJoined()) { draft.setStarted(); ThreadExecutor.getInstance().getCallExecutor().execute( - new Runnable() { - @Override - public void run() { - startDraft(); - } - }); + () -> startDraft()); } } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java index 7a7d045fc1d..068d58c04db 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java @@ -52,14 +52,14 @@ public class DraftSession { protected final static Logger logger = Logger.getLogger(DraftSession.class); - protected UUID userId; - protected UUID playerId; - protected Draft draft; + protected final UUID userId; + protected final UUID playerId; + protected final Draft draft; protected boolean killed = false; protected UUID markedCard; private ScheduledFuture futureTimeout; - protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); + protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); public DraftSession(Draft draft, UUID userId, UUID playerId) { this.userId = userId; @@ -125,12 +125,7 @@ public class DraftSession { cancelTimeout(); if (seconds > 0) { futureTimeout = timeoutExecutor.schedule( - new Runnable() { - @Override - public void run() { - DraftManager.getInstance().timeout(draft.getId(), userId); - } - }, + () -> DraftManager.getInstance().timeout(draft.getId(), userId), seconds, TimeUnit.SECONDS ); } diff --git a/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java b/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java index 4a693cbc661..ceff42329a1 100644 --- a/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java +++ b/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java @@ -57,8 +57,8 @@ public class DeckValidatorFactory { DeckValidator validator; Constructor con; try { - con = deckTypes.get(deckType).getConstructor(new Class[]{}); - validator = (DeckValidator)con.newInstance(new Object[] {}); + con = deckTypes.get(deckType).getConstructor(); + validator = (DeckValidator)con.newInstance(); } catch (Exception ex) { logger.fatal("DeckValidatorFactory error", ex); return null; diff --git a/Mage.Server/src/main/java/mage/server/game/GameController.java b/Mage.Server/src/main/java/mage/server/game/GameController.java index 8794de5b56a..79a9d63cdfd 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameController.java +++ b/Mage.Server/src/main/java/mage/server/game/GameController.java @@ -99,24 +99,24 @@ public class GameController implements GameCallback { private static final ExecutorService gameExecutor = ThreadExecutor.getInstance().getGameExecutor(); private static final Logger logger = Logger.getLogger(GameController.class); - protected ScheduledExecutorService joinWaitingExecutor = Executors.newSingleThreadScheduledExecutor(); + protected final ScheduledExecutorService joinWaitingExecutor = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture futureTimeout; - protected static ScheduledExecutorService timeoutIdleExecutor = ThreadExecutor.getInstance().getTimeoutIdleExecutor(); + protected static final ScheduledExecutorService timeoutIdleExecutor = ThreadExecutor.getInstance().getTimeoutIdleExecutor(); - private ConcurrentHashMap gameSessions = new ConcurrentHashMap<>(); - private ConcurrentHashMap watchers = new ConcurrentHashMap<>(); - private ConcurrentHashMap timers = new ConcurrentHashMap<>(); + private final ConcurrentHashMap gameSessions = new ConcurrentHashMap<>(); + private final ConcurrentHashMap watchers = new ConcurrentHashMap<>(); + private final ConcurrentHashMap timers = new ConcurrentHashMap<>(); - private ConcurrentHashMap userPlayerMap; - private UUID gameSessionId; - private Game game; - private UUID chatId; - private UUID tableId; - private UUID choosingPlayerId; + private final ConcurrentHashMap userPlayerMap; + private final UUID gameSessionId; + private final Game game; + private final UUID chatId; + private final UUID tableId; + private final UUID choosingPlayerId; private Future gameFuture; private boolean useTimeout = true; - private GameOptions gameOptions; + private final GameOptions gameOptions; private UUID userReqestingRollback; private int turnsToRollback; @@ -155,133 +155,124 @@ public class GameController implements GameCallback { private void init() { game.addTableEventListener( - new Listener() { - @Override - public void event(TableEvent event) { - try { - PriorityTimer timer; - UUID playerId; - switch (event.getEventType()) { - case UPDATE: - updateGame(); - break; - case INFO: - ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, ChatMessage.MessageType.GAME, null); - logger.trace(game.getId() + " " + event.getMessage()); - break; - case STATUS: - ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), ChatMessage.MessageType.GAME, null); - logger.trace(game.getId() + " " + event.getMessage()); - break; - case ERROR: - error(event.getMessage(), event.getException()); - break; - case END_GAME_INFO: - endGameInfo(); - break; - case INIT_TIMER: - final UUID initPlayerId = event.getPlayerId(); - if (initPlayerId == null) { - throw new MageException("INIT_TIMER: playerId can't be null"); - } - createPlayerTimer(event.getPlayerId(), game.getPriorityTime()); - break; - case RESUME_TIMER: - playerId = event.getPlayerId(); - if (playerId == null) { - throw new MageException("RESUME_TIMER: playerId can't be null"); - } - timer = timers.get(playerId); - if (timer == null) { - Player player = game.getState().getPlayer(playerId); - if (player != null) { - timer = createPlayerTimer(event.getPlayerId(), player.getPriorityTimeLeft()); - } else { - throw new MageException("RESUME_TIMER: player can't be null"); + (Listener) event -> { + try { + PriorityTimer timer; + UUID playerId; + switch (event.getEventType()) { + case UPDATE: + updateGame(); + break; + case INFO: + ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.GAME, null); + logger.trace(game.getId() + " " + event.getMessage()); + break; + case STATUS: + ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), MessageType.GAME, null); + logger.trace(game.getId() + " " + event.getMessage()); + break; + case ERROR: + error(event.getMessage(), event.getException()); + break; + case END_GAME_INFO: + endGameInfo(); + break; + case INIT_TIMER: + final UUID initPlayerId = event.getPlayerId(); + if (initPlayerId == null) { + throw new MageException("INIT_TIMER: playerId can't be null"); } - } - timer.resume(); - break; - case PAUSE_TIMER: - playerId = event.getPlayerId(); - if (playerId == null) { - throw new MageException("PAUSE_TIMER: playerId can't be null"); - } - timer = timers.get(playerId); - if (timer == null) { - throw new MageException("PAUSE_TIMER: couldn't find timer for player: " + playerId); - } - timer.pause(); - break; + createPlayerTimer(event.getPlayerId(), game.getPriorityTime()); + break; + case RESUME_TIMER: + playerId = event.getPlayerId(); + if (playerId == null) { + throw new MageException("RESUME_TIMER: playerId can't be null"); + } + timer = timers.get(playerId); + if (timer == null) { + Player player = game.getState().getPlayer(playerId); + if (player != null) { + timer = createPlayerTimer(event.getPlayerId(), player.getPriorityTimeLeft()); + } else { + throw new MageException("RESUME_TIMER: player can't be null"); + } + } + timer.resume(); + break; + case PAUSE_TIMER: + playerId = event.getPlayerId(); + if (playerId == null) { + throw new MageException("PAUSE_TIMER: playerId can't be null"); + } + timer = timers.get(playerId); + if (timer == null) { + throw new MageException("PAUSE_TIMER: couldn't find timer for player: " + playerId); + } + timer.pause(); + break; + } + } catch (MageException ex) { + logger.fatal("Table event listener error ", ex); } - } catch (MageException ex) { - logger.fatal("Table event listener error ", ex); } - } - } ); game.addPlayerQueryEventListener( - new Listener() { - @Override - public void event(PlayerQueryEvent event) { - logger.trace(new StringBuilder(event.getPlayerId().toString()).append("--").append(event.getQueryType()).append("--").append(event.getMessage()).toString()); - try { - switch (event.getQueryType()) { - case ASK: - ask(event.getPlayerId(), event.getMessage(), event.getOptions()); - break; - case PICK_TARGET: - target(event.getPlayerId(), event.getMessage(), event.getCards(), event.getPerms(), event.getTargets(), event.isRequired(), event.getOptions()); - break; - case PICK_ABILITY: - target(event.getPlayerId(), event.getMessage(), event.getAbilities(), event.isRequired(), event.getOptions()); - break; - case SELECT: - select(event.getPlayerId(), event.getMessage(), event.getOptions()); - break; - case PLAY_MANA: - playMana(event.getPlayerId(), event.getMessage(), event.getOptions()); - break; - case PLAY_X_MANA: - playXMana(event.getPlayerId(), event.getMessage()); - break; - case CHOOSE_ABILITY: - String objectName = null; - if (event.getChoices() != null && event.getChoices().size() > 0) { - objectName = event.getChoices().iterator().next(); - } - chooseAbility(event.getPlayerId(), objectName, event.getAbilities()); - break; - case CHOOSE_PILE: - choosePile(event.getPlayerId(), event.getMessage(), event.getPile1(), event.getPile2()); - break; - case CHOOSE_MODE: - chooseMode(event.getPlayerId(), event.getModes()); - break; - case CHOOSE_CHOICE: - chooseChoice(event.getPlayerId(), event.getChoice()); - break; - case AMOUNT: - amount(event.getPlayerId(), event.getMessage(), event.getMin(), event.getMax()); - break; - case PERSONAL_MESSAGE: - informPersonal(event.getPlayerId(), event.getMessage()); - break; + (Listener) event -> { + logger.trace(new StringBuilder(event.getPlayerId().toString()).append("--").append(event.getQueryType()).append("--").append(event.getMessage()).toString()); + try { + switch (event.getQueryType()) { + case ASK: + ask(event.getPlayerId(), event.getMessage(), event.getOptions()); + break; + case PICK_TARGET: + target(event.getPlayerId(), event.getMessage(), event.getCards(), event.getPerms(), event.getTargets(), event.isRequired(), event.getOptions()); + break; + case PICK_ABILITY: + target(event.getPlayerId(), event.getMessage(), event.getAbilities(), event.isRequired(), event.getOptions()); + break; + case SELECT: + select(event.getPlayerId(), event.getMessage(), event.getOptions()); + break; + case PLAY_MANA: + playMana(event.getPlayerId(), event.getMessage(), event.getOptions()); + break; + case PLAY_X_MANA: + playXMana(event.getPlayerId(), event.getMessage()); + break; + case CHOOSE_ABILITY: + String objectName = null; + if (event.getChoices() != null && event.getChoices().size() > 0) { + objectName = event.getChoices().iterator().next(); + } + chooseAbility(event.getPlayerId(), objectName, event.getAbilities()); + break; + case CHOOSE_PILE: + choosePile(event.getPlayerId(), event.getMessage(), event.getPile1(), event.getPile2()); + break; + case CHOOSE_MODE: + chooseMode(event.getPlayerId(), event.getModes()); + break; + case CHOOSE_CHOICE: + chooseChoice(event.getPlayerId(), event.getChoice()); + break; + case AMOUNT: + amount(event.getPlayerId(), event.getMessage(), event.getMin(), event.getMax()); + break; + case PERSONAL_MESSAGE: + informPersonal(event.getPlayerId(), event.getMessage()); + break; + } + } catch (MageException ex) { + logger.fatal("Player event listener error ", ex); } - } catch (MageException ex) { - logger.fatal("Player event listener error ", ex); } - } - } ); - joinWaitingExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - try { - sendInfoAboutPlayersNotJoinedYet(); - } catch (Exception ex) { - logger.fatal("Send info about player not joined yet:", ex); - } + joinWaitingExecutor.scheduleAtFixedRate(() -> { + try { + sendInfoAboutPlayersNotJoinedYet(); + } catch (Exception ex) { + logger.fatal("Send info about player not joined yet:", ex); } }, 15, 15, TimeUnit.SECONDS); checkStart(); @@ -303,12 +294,9 @@ public class GameController implements GameCallback { final UUID initPlayerId = playerId; long delayMs = 250L; // run each 250 ms - Action executeOnNoTimeLeft = new Action() { - @Override - public void execute() throws MageException { - game.timerTimeout(initPlayerId); - logger.debug("Player has no time left to end the match: " + initPlayerId + ". Conceding."); - } + Action executeOnNoTimeLeft = () -> { + game.timerTimeout(initPlayerId); + logger.debug("Player has no time left to end the match: " + initPlayerId + ". Conceding."); }; PriorityTimer timer = new PriorityTimer(count, delayMs, executeOnNoTimeLeft); @@ -402,12 +390,7 @@ public class GameController implements GameCallback { if (allJoined()) { joinWaitingExecutor.shutdownNow(); ThreadExecutor.getInstance().getCallExecutor().execute( - new Runnable() { - @Override - public void run() { - startGame(); - } - }); + () -> startGame()); } } @@ -703,49 +686,24 @@ public class GameController implements GameCallback { } public void sendPlayerUUID(UUID userId, final UUID data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerUUID(data); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerUUID(data)); } public void sendPlayerString(UUID userId, final String data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerString(data); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerString(data)); } public void sendPlayerManaType(UUID userId, final UUID manaTypePlayerId, final ManaType data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerManaType(data, manaTypePlayerId); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerManaType(data, manaTypePlayerId)); } public void sendPlayerBoolean(UUID userId, final Boolean data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerBoolean(data); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerBoolean(data)); } public void sendPlayerInteger(UUID userId, final Integer data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerInteger(data); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerInteger(data)); } @@ -779,120 +737,69 @@ public class GameController implements GameCallback { } private synchronized void ask(UUID playerId, final String question, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).ask(question, options); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).ask(question, options)); } private synchronized void chooseAbility(UUID playerId, final String objectName, final List choices) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).chooseAbility(new AbilityPickerView(objectName, choices)); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).chooseAbility(new AbilityPickerView(objectName, choices))); } private synchronized void choosePile(UUID playerId, final String message, final List pile1, final List pile2) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).choosePile(message, new CardsView(pile1), new CardsView(pile2)); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).choosePile(message, new CardsView(pile1), new CardsView(pile2))); } private synchronized void chooseMode(UUID playerId, final Map modes) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).chooseAbility(new AbilityPickerView(modes)); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).chooseAbility(new AbilityPickerView(modes))); } private synchronized void chooseChoice(UUID playerId, final Choice choice) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).chooseChoice(choice); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).chooseChoice(choice)); } private synchronized void target(UUID playerId, final String question, final Cards cards, final List perms, final Set targets, final boolean required, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - if (cards != null) { - // Zone targetZone = (Zone) options.get("targetZone"); - // Are there really situations where a player selects from a list of face down cards? - // So always show face up for selection - // boolean showFaceDown = targetZone != null && targetZone.equals(Zone.PICK); - boolean showFaceDown = true; - getGameSession(playerId).target(question, new CardsView(game, cards.getCards(game), showFaceDown, true), targets, required, options); - } else if (perms != null) { - CardsView permsView = new CardsView(); - for (Permanent perm : perms) { - permsView.put(perm.getId(), new PermanentView(perm, game.getCard(perm.getId()), playerId, game)); - } - getGameSession(playerId).target(question, permsView, targets, required, options); - } else { - getGameSession(playerId).target(question, new CardsView(), targets, required, options); + perform(playerId, playerId1 -> { + if (cards != null) { + // Zone targetZone = (Zone) options.get("targetZone"); + // Are there really situations where a player selects from a list of face down cards? + // So always show face up for selection + // boolean showFaceDown = targetZone != null && targetZone.equals(Zone.PICK); + boolean showFaceDown = true; + getGameSession(playerId1).target(question, new CardsView(game, cards.getCards(game), showFaceDown, true), targets, required, options); + } else if (perms != null) { + CardsView permsView = new CardsView(); + for (Permanent perm : perms) { + permsView.put(perm.getId(), new PermanentView(perm, game.getCard(perm.getId()), playerId1, game)); } + getGameSession(playerId1).target(question, permsView, targets, required, options); + } else { + getGameSession(playerId1).target(question, new CardsView(), targets, required, options); } }); } private synchronized void target(UUID playerId, final String question, final Collection abilities, final boolean required, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - CardsView cardsView = new CardsView(abilities, game); - getGameSession(playerId).target(question, cardsView, null, required, options); - } + perform(playerId, playerId1 -> { + CardsView cardsView = new CardsView(abilities, game); + getGameSession(playerId1).target(question, cardsView, null, required, options); }); } private synchronized void select(final UUID playerId, final String message, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).select(message, options); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).select(message, options)); } private synchronized void playMana(UUID playerId, final String message, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).playMana(message, options); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).playMana(message, options)); } private synchronized void playXMana(UUID playerId, final String message) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).playXMana(message); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).playXMana(message)); } private synchronized void amount(UUID playerId, final String message, final int min, final int max) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).getAmount(message, min, max); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).getAmount(message, min, max)); } private void informOthers(UUID playerId) throws MageException { @@ -939,12 +846,7 @@ public class GameController implements GameCallback { } private synchronized void informPersonal(UUID playerId, final String message) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).informPersonal(message); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).informPersonal(message)); } private void error(String message, Exception ex) { @@ -977,12 +879,9 @@ public class GameController implements GameCallback { try { OutputStream file = new FileOutputStream("saved/" + game.getId().toString() + ".game"); OutputStream buffer = new BufferedOutputStream(file); - ObjectOutput output = new ObjectOutputStream(new GZIPOutputStream(buffer)); - try { + try (ObjectOutput output = new ObjectOutputStream(new GZIPOutputStream(buffer))) { output.writeObject(game); output.writeObject(game.getGameStates()); - } finally { - output.close(); } logger.debug("Saved game:" + game.getId()); return true; @@ -1074,12 +973,7 @@ public class GameController implements GameCallback { } cancelTimeout(); futureTimeout = timeoutIdleExecutor.schedule( - new Runnable() { - @Override - public void run() { - idleTimeout(playerId); - } - }, + () -> idleTimeout(playerId), Main.isTestMode() ? 3600 : ConfigSettings.getInstance().getMaxSecondsIdle(), TimeUnit.SECONDS ); diff --git a/Mage.Server/src/main/java/mage/server/game/GameFactory.java b/Mage.Server/src/main/java/mage/server/game/GameFactory.java index fe13cb3dd92..c3a22eb59b1 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameFactory.java +++ b/Mage.Server/src/main/java/mage/server/game/GameFactory.java @@ -64,8 +64,8 @@ public class GameFactory { Match match; Constructor con; try { - con = games.get(gameType).getConstructor(new Class[]{MatchOptions.class}); - match = con.newInstance(new Object[] {options}); + con = games.get(gameType).getConstructor(MatchOptions.class); + match = con.newInstance(options); } catch (Exception ex) { logger.fatal("Error creating match - " + gameType, ex); return null; diff --git a/Mage.Server/src/main/java/mage/server/game/GameReplay.java b/Mage.Server/src/main/java/mage/server/game/GameReplay.java index d6e8b961584..820bc9a6d32 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameReplay.java +++ b/Mage.Server/src/main/java/mage/server/game/GameReplay.java @@ -87,16 +87,12 @@ public class GameReplay { try{ InputStream file = new FileInputStream("saved/" + gameId.toString() + ".game"); InputStream buffer = new BufferedInputStream(file); - ObjectInput input = new CopierObjectInputStream(Main.classLoader, new GZIPInputStream(buffer)); - try { - Game loadGame = (Game)input.readObject(); - GameStates states = (GameStates)input.readObject(); + try (ObjectInput input = new CopierObjectInputStream(Main.classLoader, new GZIPInputStream(buffer))) { + Game loadGame = (Game) input.readObject(); + GameStates states = (GameStates) input.readObject(); loadGame.loadGameStates(states); return loadGame; } - finally { - input.close(); - } } catch(ClassNotFoundException ex) { logger.fatal("Cannot load game. Class not found.", ex); diff --git a/Mage.Server/src/main/java/mage/server/game/GameSessionPlayer.java b/Mage.Server/src/main/java/mage/server/game/GameSessionPlayer.java index c9273f401dc..76137efcca3 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameSessionPlayer.java +++ b/Mage.Server/src/main/java/mage/server/game/GameSessionPlayer.java @@ -282,34 +282,31 @@ public class GameSessionPlayer extends GameSessionWatcher { final Player player = game.getPlayer(playerId); if (player != null && player.isInGame()) { callExecutor.execute( - new Runnable() { - @Override - public void run() { - try { - if (game.getStartTime() == null) { - // gameController is still waiting to start the game - player.leave(); - } else { - // game was already started - player.quit(game); - } - - } catch (Exception ex) { - if (ex != null) { - // It seems this can happen if two threads try to end the game at the exact same time (one wins and one ends here) - logger.fatal("Game session game quit exception " + (ex.getMessage() == null ? "null" : ex.getMessage())); - logger.debug("- gameId:" + game.getId() + " playerId: " + playerId); - if (ex.getCause() != null) { - logger.debug("- Cause: " + (ex.getCause().getMessage() == null ? "null" : ex.getCause().getMessage()), ex); + () -> { + try { + if (game.getStartTime() == null) { + // gameController is still waiting to start the game + player.leave(); } else { - logger.debug("- ex: " + ex.toString(), ex); + // game was already started + player.quit(game); + } + + } catch (Exception ex) { + if (ex != null) { + // It seems this can happen if two threads try to end the game at the exact same time (one wins and one ends here) + logger.fatal("Game session game quit exception " + (ex.getMessage() == null ? "null" : ex.getMessage())); + logger.debug("- gameId:" + game.getId() + " playerId: " + playerId); + if (ex.getCause() != null) { + logger.debug("- Cause: " + (ex.getCause().getMessage() == null ? "null" : ex.getCause().getMessage()), ex); + } else { + logger.debug("- ex: " + ex.toString(), ex); + } + } else { + logger.fatal("Game session game quit exception - null gameId:" + game.getId() + " playerId: " + playerId); } - } else { - logger.fatal("Game session game quit exception - null gameId:" + game.getId() + " playerId: " + playerId); } } - } - } ); } diff --git a/Mage.Server/src/main/java/mage/server/game/GameSessionWatcher.java b/Mage.Server/src/main/java/mage/server/game/GameSessionWatcher.java index 134899e36b9..e1cd8bf9d1f 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameSessionWatcher.java +++ b/Mage.Server/src/main/java/mage/server/game/GameSessionWatcher.java @@ -51,10 +51,10 @@ public class GameSessionWatcher { protected final static Logger logger = Logger.getLogger(GameSessionWatcher.class); - protected UUID userId; - protected Game game; + protected final UUID userId; + protected final Game game; protected boolean killed = false; - protected boolean isPlayer; + protected final boolean isPlayer; public GameSessionWatcher(UUID userId, Game game, boolean isPlayer) { this.userId = userId; diff --git a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java index e7f218b88ec..6f6d57d8760 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java @@ -37,6 +37,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; + import mage.MageException; import mage.cards.decks.DeckCardLists; import mage.constants.TableState; @@ -58,7 +59,6 @@ import mage.view.UsersView; import org.apache.log4j.Logger; /** - * * @author BetaSteward_at_googlemail.com */ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { @@ -73,16 +73,13 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { private final ConcurrentHashMap tables = new ConcurrentHashMap<>(); public GamesRoomImpl() { - UPDATE_EXECUTOR.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - try { - update(); - } catch (Exception ex) { - LOGGER.fatal("Games room update exception! " + ex.toString(), ex); - } - + UPDATE_EXECUTOR.scheduleAtFixedRate(() -> { + try { + update(); + } catch (Exception ex) { + LOGGER.fatal("Games room update exception! " + ex.toString(), ex); } + }, 2, 2, TimeUnit.SECONDS); } @@ -95,7 +92,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { ArrayList tableList = new ArrayList<>(); ArrayList matchList = new ArrayList<>(); List allTables = new ArrayList<>(tables.values()); - Collections.sort(allTables, new TableListSorter()); + allTables.sort(new TableListSorter()); for (Table table : allTables) { if (table.getState() != TableState.FINISHED) { tableList.add(new TableView(table)); @@ -136,7 +133,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } } - Collections.sort(users, new UserNameSorter()); + users.sort(new UserNameSorter()); List roomUserInfo = new ArrayList<>(); roomUserInfo.add(new RoomUsersView(users, GameManager.getInstance().getNumberActiveGames(), @@ -235,11 +232,11 @@ class TableListSorter implements Comparator
{ @Override public int compare(Table one, Table two) { if (one.getState() != null && two.getState() != null) { - if (!TableState.SIDEBOARDING.equals(one.getState()) && !TableState.DUELING.equals(one.getState())) { + if (TableState.SIDEBOARDING != one.getState() && TableState.DUELING != one.getState()) { if (one.getState().compareTo(two.getState()) != 0) { return one.getState().compareTo(two.getState()); } - } else if (!TableState.SIDEBOARDING.equals(two.getState()) && !TableState.DUELING.equals(two.getState())) { + } else if (TableState.SIDEBOARDING != two.getState() && TableState.DUELING != two.getState()) { if (one.getState().compareTo(two.getState()) != 0) { return one.getState().compareTo(two.getState()); } diff --git a/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java b/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java index 2bee468263a..9d9581aa837 100644 --- a/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java +++ b/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java @@ -59,8 +59,8 @@ public class PlayerFactory { try { Class playerTypeClass = playerTypes.get(playerType); if (playerTypeClass != null) { - con = playerTypeClass.getConstructor(new Class[]{String.class, RangeOfInfluence.class, int.class}); - player = (Player)con.newInstance(new Object[] {name, range, skill}); + con = playerTypeClass.getConstructor(String.class, RangeOfInfluence.class, int.class); + player = (Player)con.newInstance(name, range, skill); logger.trace("Player created: " + name + " - " + player.getId()); return player; } diff --git a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java index c426fbe7db3..f7735c48b11 100644 --- a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java +++ b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java @@ -43,7 +43,7 @@ import mage.view.GameView; public class ReplaySession implements GameCallback { private final GameReplay replay; - protected UUID userId; + protected final UUID userId; ReplaySession(UUID gameId, UUID userId) { this.replay = new GameReplay(gameId); diff --git a/Mage.Server/src/main/java/mage/server/record/TableRecordRepository.java b/Mage.Server/src/main/java/mage/server/record/TableRecordRepository.java index 927a474c397..c5fec8d5c97 100644 --- a/Mage.Server/src/main/java/mage/server/record/TableRecordRepository.java +++ b/Mage.Server/src/main/java/mage/server/record/TableRecordRepository.java @@ -24,7 +24,7 @@ public enum TableRecordRepository { private Dao dao; - private TableRecordRepository() { + TableRecordRepository() { File file = new File("db"); if (!file.exists()) { file.mkdirs(); diff --git a/Mage.Server/src/main/java/mage/server/record/UserStatsRepository.java b/Mage.Server/src/main/java/mage/server/record/UserStatsRepository.java index 4da53b93e33..1bf6b3f4743 100644 --- a/Mage.Server/src/main/java/mage/server/record/UserStatsRepository.java +++ b/Mage.Server/src/main/java/mage/server/record/UserStatsRepository.java @@ -30,7 +30,7 @@ public enum UserStatsRepository { private Dao dao; - private UserStatsRepository() { + UserStatsRepository() { File file = new File("db"); if (!file.exists()) { file.mkdirs(); diff --git a/Mage.Server/src/main/java/mage/server/services/impl/FeedbackServiceImpl.java b/Mage.Server/src/main/java/mage/server/services/impl/FeedbackServiceImpl.java index 1f26af508fb..2f53fe21cac 100644 --- a/Mage.Server/src/main/java/mage/server/services/impl/FeedbackServiceImpl.java +++ b/Mage.Server/src/main/java/mage/server/services/impl/FeedbackServiceImpl.java @@ -12,7 +12,7 @@ import java.util.Calendar; public enum FeedbackServiceImpl implements FeedbackService { instance; - private static Logger log = Logger.getLogger(FeedbackServiceImpl.class); + private static final Logger log = Logger.getLogger(FeedbackServiceImpl.class); @Override public void feedback(String username, String title, String type, String message, String email, String host) { diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java index aabe8bf37ae..1b62b18759e 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -88,68 +88,62 @@ public class TournamentController { private void init() { tournament.addTableEventListener( - new Listener() { - @Override - public void event(TableEvent event) { - switch (event.getEventType()) { - case CHECK_STATE_PLAYERS: - checkPlayersState(); - break; - case INFO: - ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS, null); - logger.debug(tournament.getId() + " " + event.getMessage()); - break; - case START_DRAFT: - startDraft(event.getDraft()); - break; - case CONSTRUCT: - if (!isAbort()) { - construct(); - } else { - endTournament(); - } - break; - case START_MATCH: - if (!isAbort()) { - initTournament(); // set state - startMatch(event.getPair(), event.getMatchOptions()); - } - break; - case START_MULTIPLAYER_MATCH: - if (!isAbort()) { - initTournament(); // set state - MatchOptions matchOptions = event.getMatchOptions(); - if (matchOptions != null && event.getMultiplayerRound() != null) { - for (TournamentPlayer player : event.getMultiplayerRound().getAllPlayers()) { - matchOptions.getPlayerTypes().add(player.getPlayerType()); - } - } - - startMultiplayerMatch(event.getMultiplayerRound(), event.getMatchOptions()); - } - break; - case END: - endTournament(); - break; - } - } - } - ); - tournament.addPlayerQueryEventListener( - new Listener() { - @Override - public void event(PlayerQueryEvent event) { - try { - switch (event.getQueryType()) { + (Listener) event -> { + switch (event.getEventType()) { + case CHECK_STATE_PLAYERS: + checkPlayersState(); + break; + case INFO: + ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS, null); + logger.debug(tournament.getId() + " " + event.getMessage()); + break; + case START_DRAFT: + startDraft(event.getDraft()); + break; case CONSTRUCT: - construct(event.getPlayerId(), event.getMax()); + if (!isAbort()) { + construct(); + } else { + endTournament(); + } + break; + case START_MATCH: + if (!isAbort()) { + initTournament(); // set state + startMatch(event.getPair(), event.getMatchOptions()); + } + break; + case START_MULTIPLAYER_MATCH: + if (!isAbort()) { + initTournament(); // set state + MatchOptions matchOptions = event.getMatchOptions(); + if (matchOptions != null && event.getMultiplayerRound() != null) { + for (TournamentPlayer player : event.getMultiplayerRound().getAllPlayers()) { + matchOptions.getPlayerTypes().add(player.getPlayerType()); + } + } + + startMultiplayerMatch(event.getMultiplayerRound(), event.getMatchOptions()); + } + break; + case END: + endTournament(); break; } - } catch (MageException ex) { - logger.fatal("Player event listener error", ex); } - } - } + ); + tournament.addPlayerQueryEventListener( + (Listener) event -> { + try { + switch (event.getQueryType()) { + case CONSTRUCT: + construct(event.getPlayerId(), event.getMax()); + break; + } + } catch (MageException ex) { + logger.fatal("Player event listener error", ex); + } + } ); for (TournamentPlayer player : tournament.getPlayers()) { if (!player.getPlayer().isHuman()) { @@ -208,12 +202,7 @@ public class TournamentController { private void checkStart() { if (!started && allJoined()) { ThreadExecutor.getInstance().getCallExecutor().execute( - new Runnable() { - @Override - public void run() { - startTournament(); - } - }); + () -> startTournament()); } } @@ -313,7 +302,7 @@ public class TournamentController { } private void initTournament() { - if (!TableManager.getInstance().getTable(tableId).getState().equals(TableState.DUELING)) { + if (TableManager.getInstance().getTable(tableId).getState()!=TableState.DUELING) { TableManager.getInstance().initTournament(tableId); } } @@ -396,7 +385,7 @@ public class TournamentController { // quit active matches of that tournament TableManager.getInstance().userQuitTournamentSubTables(tournament.getId(), userId); status = TourneyQuitStatus.DURING_ROUND; - } else if (tournamentPlayer.getState().equals(TournamentPlayerState.DRAFTING)) { + } else if (tournamentPlayer.getState()==TournamentPlayerState.DRAFTING) { info = "during Draft phase"; if (!checkToReplaceDraftPlayerByAi(userId, tournamentPlayer)) { this.abortDraftTournament(); @@ -410,7 +399,7 @@ public class TournamentController { } } status = TourneyQuitStatus.DURING_DRAFTING; - } else if (tournamentPlayer.getState().equals(TournamentPlayerState.CONSTRUCTING)) { + } else if (tournamentPlayer.getState()==TournamentPlayerState.CONSTRUCTING) { info = "during Construction phase"; status = TourneyQuitStatus.DURING_CONSTRUCTION; } else { @@ -534,7 +523,7 @@ public class TournamentController { } } } - if (activePlayers < 2 && !tableState.equals(TableState.WAITING)) { + if (activePlayers < 2 && tableState!=TableState.WAITING) { logger.debug("Tournament has less than 2 active players - tournamentId: " + tournament.getId() + " state: " + tableState.toString()); return false; } diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java index ddfd7d14459..4a09cc84fe8 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java @@ -66,8 +66,8 @@ public class TournamentFactory { Tournament tournament; Constructor con; try { - con = tournaments.get(tournamentType).getConstructor(new Class[]{TournamentOptions.class}); - tournament = con.newInstance(new Object[] {options}); + con = tournaments.get(tournamentType).getConstructor(TournamentOptions.class); + tournament = con.newInstance(options); // transfer set information, create short info string for included sets tournament.setTournamentType(tournamentTypes.get(tournamentType)); if (tournament.getTournamentType().isLimited()) { diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java index d0a16c71882..2ac77761d03 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java @@ -49,14 +49,14 @@ import java.util.concurrent.TimeUnit; public class TournamentSession { protected final static Logger logger = Logger.getLogger(TournamentSession.class); - protected UUID userId; - protected UUID playerId; - protected UUID tableId; - protected Tournament tournament; + protected final UUID userId; + protected final UUID playerId; + protected final UUID tableId; + protected final Tournament tournament; protected boolean killed = false; private ScheduledFuture futureTimeout; - protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); + protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); public TournamentSession(Tournament tournament, UUID userId, UUID tableId, UUID playerId) { this.userId = userId; @@ -129,16 +129,13 @@ public class TournamentSession { cancelTimeout(); if (seconds > 0) { futureTimeout = timeoutExecutor.schedule( - new Runnable() { - @Override - public void run() { + () -> { try { TournamentManager.getInstance().timeout(tournament.getId(), userId); } catch (Exception e) { logger.fatal("TournamentSession error - userId " + userId + " tId " + tournament.getId(), e); } - } - }, + }, seconds, TimeUnit.SECONDS ); } diff --git a/Mage.Server/src/main/java/mage/server/util/ServerMessagesUtil.java b/Mage.Server/src/main/java/mage/server/util/ServerMessagesUtil.java index 7ba4ca5cb49..fe2e2212b21 100644 --- a/Mage.Server/src/main/java/mage/server/util/ServerMessagesUtil.java +++ b/Mage.Server/src/main/java/mage/server/util/ServerMessagesUtil.java @@ -74,12 +74,7 @@ public class ServerMessagesUtil { public ServerMessagesUtil() { updateExecutor = Executors.newSingleThreadScheduledExecutor(); - updateExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - reloadMessages(); - } - }, 5, 5 * 60, TimeUnit.SECONDS); + updateExecutor.scheduleAtFixedRate(() -> reloadMessages(), 5, 5 * 60, TimeUnit.SECONDS); } public static ServerMessagesUtil getInstance() { diff --git a/Mage.Server/src/main/java/mage/server/util/SystemUtil.java b/Mage.Server/src/main/java/mage/server/util/SystemUtil.java index d7fb2254a69..00cd7ea3132 100644 --- a/Mage.Server/src/main/java/mage/server/util/SystemUtil.java +++ b/Mage.Server/src/main/java/mage/server/util/SystemUtil.java @@ -1,16 +1,5 @@ package mage.server.util; -import java.io.File; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Scanner; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import mage.cards.Card; import mage.cards.repository.CardInfo; import mage.cards.repository.CardRepository; @@ -19,6 +8,14 @@ import mage.game.Game; import mage.players.Player; import mage.util.RandomUtil; +import java.io.File; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * @author nantuko */ @@ -56,8 +53,7 @@ public class SystemUtil { logger.info("Parsing init.txt... "); - Scanner scanner = new Scanner(f); - try { + try (Scanner scanner = new Scanner(f)) { while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); if (line.trim().isEmpty() || line.startsWith("#")) { @@ -114,8 +110,6 @@ public class SystemUtil { swapWithAnyCard(game, player, card, gameZone); } } - } finally { - scanner.close(); } } catch (Exception e) { logger.fatal("", e); @@ -132,14 +126,17 @@ public class SystemUtil { // Put the card in Exile to start. Otherwise the game doesn't know where to remove the card from. game.getExile().getPermanentExile().add(card); game.setZone(card.getId(), Zone.EXILED); - if (zone.equals(Zone.BATTLEFIELD)) { - card.putOntoBattlefield(game, Zone.EXILED, null, player.getId()); - } else if (zone.equals(Zone.LIBRARY)) { - card.setZone(Zone.LIBRARY, game); - game.getExile().getPermanentExile().remove(card); - player.getLibrary().putOnTop(card, game); - } else { - card.moveToZone(zone, null, game, false); + switch (zone) { + case BATTLEFIELD: + card.putOntoBattlefield(game, Zone.EXILED, null, player.getId()); + break; + case LIBRARY: + card.setZone(Zone.LIBRARY, game); + game.getExile().getPermanentExile().remove(card); + player.getLibrary().putOnTop(card, game); + break; + default: + card.moveToZone(zone, null, game, false); } logger.info("Added card to player's " + zone.toString() + ": " + card.getName() + ", player = " + player.getName()); } @@ -179,8 +176,8 @@ public class SystemUtil { /** * Get a diff between two dates * - * @param date1 the oldest date - * @param date2 the newest date + * @param date1 the oldest date + * @param date2 the newest date * @param timeUnit the unit in which you want the diff * @return the diff value, in the provided unit */ diff --git a/Mage.Sets/pom.xml b/Mage.Sets/pom.xml index 18096ae963a..f6bd1c16b29 100644 --- a/Mage.Sets/pom.xml +++ b/Mage.Sets/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 org.mage diff --git a/Mage.Sets/src/mage/cards/a/ActOfAggression.java b/Mage.Sets/src/mage/cards/a/ActOfAggression.java index 84da3a7dce3..dbfbafa4e18 100644 --- a/Mage.Sets/src/mage/cards/a/ActOfAggression.java +++ b/Mage.Sets/src/mage/cards/a/ActOfAggression.java @@ -30,7 +30,6 @@ package mage.cards.a; import java.util.UUID; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.Rarity; import mage.abilities.effects.common.UntapTargetEffect; import mage.abilities.effects.common.continuous.GainAbilityTargetEffect; import mage.abilities.effects.common.continuous.GainControlTargetEffect; diff --git a/Mage.Sets/src/mage/cards/a/AdaptiveAutomaton.java b/Mage.Sets/src/mage/cards/a/AdaptiveAutomaton.java index b71eec19106..2cd05794a68 100644 --- a/Mage.Sets/src/mage/cards/a/AdaptiveAutomaton.java +++ b/Mage.Sets/src/mage/cards/a/AdaptiveAutomaton.java @@ -35,10 +35,12 @@ import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.ContinuousEffectImpl; import mage.abilities.effects.common.ChooseCreatureTypeEffect; import mage.abilities.effects.common.continuous.BoostAllOfChosenSubtypeEffect; +import mage.abilities.effects.common.enterAttribute.EnterAttributeAddChosenSubtypeEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; +import mage.constants.EnterEventType; import mage.constants.Layer; import mage.constants.Outcome; import mage.constants.SubLayer; @@ -61,15 +63,18 @@ public class AdaptiveAutomaton extends CardImpl { } public AdaptiveAutomaton(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT,CardType.CREATURE},"{3}"); + super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{3}"); this.subtype.add("Construct"); this.power = new MageInt(2); this.toughness = new MageInt(2); // As Adaptive Automaton enters the battlefield, choose a creature type. - this.addAbility(new AsEntersBattlefieldAbility(new ChooseCreatureTypeEffect(Outcome.BoostCreature))); // Adaptive Automaton is the chosen type in addition to its other types. + AsEntersBattlefieldAbility ability = new AsEntersBattlefieldAbility(new ChooseCreatureTypeEffect(Outcome.BoostCreature), null, EnterEventType.SELF); + ability.addEffect(new EnterAttributeAddChosenSubtypeEffect()); + this.addAbility(ability); + this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new AdaptiveAutomatonAddSubtypeEffect())); // Other creatures you control of the chosen type get +1/+1. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostAllOfChosenSubtypeEffect(1, 1, Duration.WhileOnBattlefield, filter, true))); diff --git a/Mage.Sets/src/mage/cards/a/AdrianaCaptainOfTheGuard.java b/Mage.Sets/src/mage/cards/a/AdrianaCaptainOfTheGuard.java index e05d317b97f..7fd967d6764 100644 --- a/Mage.Sets/src/mage/cards/a/AdrianaCaptainOfTheGuard.java +++ b/Mage.Sets/src/mage/cards/a/AdrianaCaptainOfTheGuard.java @@ -31,7 +31,6 @@ import java.util.UUID; import mage.MageInt; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.common.continuous.GainAbilityControlledEffect; -import mage.abilities.keyword.DeathtouchAbility; import mage.abilities.keyword.MeleeAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/a/AegisAutomaton.java b/Mage.Sets/src/mage/cards/a/AegisAutomaton.java index 46104e1bdd1..2f5422b4524 100644 --- a/Mage.Sets/src/mage/cards/a/AegisAutomaton.java +++ b/Mage.Sets/src/mage/cards/a/AegisAutomaton.java @@ -47,7 +47,7 @@ import mage.target.common.TargetControlledCreaturePermanent; */ public class AegisAutomaton extends CardImpl { - private static final FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("another target creature"); + private static final FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("another target creature you control"); static { filter.add(new AnotherPredicate()); diff --git a/Mage.Sets/src/mage/cards/a/AirdropAeronauts.java b/Mage.Sets/src/mage/cards/a/AirdropAeronauts.java index b2806a5ab4a..8a87624a65e 100644 --- a/Mage.Sets/src/mage/cards/a/AirdropAeronauts.java +++ b/Mage.Sets/src/mage/cards/a/AirdropAeronauts.java @@ -32,11 +32,12 @@ import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.RevoltCondition; -import mage.abilities.decorator.ConditionalOneShotEffect; +import mage.abilities.decorator.ConditionalTriggeredAbility; import mage.abilities.effects.common.GainLifeEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.AbilityWord; import mage.constants.CardType; import mage.watchers.common.RevoltWatcher; @@ -58,8 +59,12 @@ public class AirdropAeronauts extends CardImpl { this.addAbility(FlyingAbility.getInstance()); // Revolt — When Airdrop Aeronauts enters the battlefield, if a permanent you controlled left the battlefield this turn, you gain 5 life. - Ability ability = new EntersBattlefieldTriggeredAbility( - new ConditionalOneShotEffect(new GainLifeEffect(5), RevoltCondition.getInstance()), false, "Revolt — "); + Ability ability = new ConditionalTriggeredAbility(new EntersBattlefieldTriggeredAbility( + new GainLifeEffect(5), false), RevoltCondition.getInstance(), + "Revolt — When {this} enters the battlefield, if a permanent you controlled left" + + " the battlefield this turn, you gain 5 life." + ); + ability.setAbilityWord(AbilityWord.REVOLT); this.addAbility(ability, new RevoltWatcher()); } diff --git a/Mage.Sets/src/mage/cards/a/AjaniUnyielding.java b/Mage.Sets/src/mage/cards/a/AjaniUnyielding.java index c601b0fea71..ab908ea712a 100644 --- a/Mage.Sets/src/mage/cards/a/AjaniUnyielding.java +++ b/Mage.Sets/src/mage/cards/a/AjaniUnyielding.java @@ -29,7 +29,6 @@ package mage.cards.a; import mage.abilities.LoyaltyAbility; import mage.abilities.common.PlanswalkerEntersWithLoyalityCountersAbility; -import mage.abilities.effects.common.ExileTargetEffect; import mage.abilities.effects.common.RevealLibraryPutIntoHandEffect; import mage.abilities.effects.common.SwordsToPlowsharesEffect; import mage.abilities.effects.common.counter.AddCountersAllEffect; @@ -38,7 +37,6 @@ import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.TargetController; import mage.counters.CounterType; -import mage.filter.common.FilterCreaturePermanent; import mage.filter.common.FilterPermanentCard; import mage.filter.common.FilterPlaneswalkerPermanent; import mage.filter.predicate.Predicates; @@ -49,6 +47,7 @@ import mage.target.common.TargetCreaturePermanent; import java.util.UUID; import mage.constants.Zone; +import mage.filter.common.FilterControlledCreaturePermanent; /** * @author JRHerlehy @@ -56,12 +55,10 @@ import mage.constants.Zone; public class AjaniUnyielding extends CardImpl { private static final FilterPermanentCard nonlandPermanentFilter = new FilterPermanentCard("nonland permanent cards"); - private static final FilterCreaturePermanent creatureFilter = new FilterCreaturePermanent("creature you control"); private static final FilterPlaneswalkerPermanent planeswalkerFilter = new FilterPlaneswalkerPermanent("other planeswalker you control"); static { nonlandPermanentFilter.add(Predicates.not(new CardTypePredicate(CardType.LAND))); - creatureFilter.add(new ControllerPredicate(TargetController.YOU)); planeswalkerFilter.add(new ControllerPredicate(TargetController.YOU)); planeswalkerFilter.add(new AnotherPredicate()); } @@ -77,12 +74,11 @@ public class AjaniUnyielding extends CardImpl { // -2: Exile target creature. Its controller gains life equal to its power. LoyaltyAbility ajaniAbility2 = new LoyaltyAbility(new SwordsToPlowsharesEffect(), -2); - ajaniAbility2.addEffect(new ExileTargetEffect()); ajaniAbility2.addTarget(new TargetCreaturePermanent()); this.addAbility(ajaniAbility2); // -9: Put five +1/+1 counters on each creature you control and five loyalty counters on each other planeswalker you control. - LoyaltyAbility ajaniAbility3 = new LoyaltyAbility(new AddCountersAllEffect(CounterType.P1P1.createInstance(5), creatureFilter), -9); + LoyaltyAbility ajaniAbility3 = new LoyaltyAbility(new AddCountersAllEffect(CounterType.P1P1.createInstance(5), new FilterControlledCreaturePermanent()), -9); ajaniAbility3.addEffect(new AddCountersAllEffect(CounterType.LOYALTY.createInstance(5), planeswalkerFilter)); this.addAbility(ajaniAbility3); } diff --git a/Mage.Sets/src/mage/cards/a/AjanisAid.java b/Mage.Sets/src/mage/cards/a/AjanisAid.java index 408d35ec295..28247cd3b24 100644 --- a/Mage.Sets/src/mage/cards/a/AjanisAid.java +++ b/Mage.Sets/src/mage/cards/a/AjanisAid.java @@ -28,29 +28,20 @@ package mage.cards.a; import java.util.UUID; -import mage.MageObject; -import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.SacrificeSourceCost; import mage.abilities.effects.Effect; -import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.PreventNextDamageFromChosenSourceToYouEffect; -import mage.cards.Card; +import mage.abilities.effects.common.search.SearchLibraryGraveyardPutInHandEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.cards.Cards; -import mage.cards.CardsImpl; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.FilterCard; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.NamePredicate; -import mage.game.Game; -import mage.players.Player; -import mage.target.TargetCard; /** * @@ -58,12 +49,18 @@ import mage.target.TargetCard; */ public class AjanisAid extends CardImpl { + private final static FilterCard filter = new FilterCard("Ajani, Valiant Protector"); + + static { + filter.add(new NamePredicate("Ajani, Valiant Protector")); + } + public AjanisAid(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{G}{W}"); // When Ajani's Aid enters the battlefield, you may search your library and/or graveyard for a card named Ajani, Valiant Protector, reveal it, // and put it into your hand. If you search your library this way, shuffle it. - this.addAbility(new EntersBattlefieldTriggeredAbility(new AjanisAidEffect())); + this.addAbility(new EntersBattlefieldTriggeredAbility(new SearchLibraryGraveyardPutInHandEffect(filter), true)); // Sacrifice Ajani's Aid: Prevent all combat damage a creature of your choice would deal this turn. Effect effect = new PreventNextDamageFromChosenSourceToYouEffect(Duration.EndOfTurn, new FilterCreaturePermanent("creature of your choice"), true); @@ -80,52 +77,3 @@ public class AjanisAid extends CardImpl { return new AjanisAid(this); } } - -class AjanisAidEffect extends OneShotEffect { - - public AjanisAidEffect() { - super(Outcome.Benefit); - staticText = "You may search your library and/or graveyard for a card named Ajani, Valiant Protector, reveal it, and put it into your hand. " - + "If you search your library this way, shuffle it"; - } - - public AjanisAidEffect(final AjanisAidEffect effect) { - super(effect); - } - - @Override - public AjanisAidEffect copy() { - return new AjanisAidEffect(this); - } - - @Override - public boolean apply(Game game, Ability source) { - Player controller = game.getPlayer(source.getControllerId()); - MageObject sourceObject = source.getSourceObject(game); - if (controller != null && sourceObject != null && controller.chooseUse(outcome, "Search your library and/or graveyard for a card named Ajani, Valiant Protector?", source, game)) { - //Search your library and graveyard - Cards allCards = new CardsImpl(); - boolean librarySearched = false; - if (controller.chooseUse(outcome, "Search also your library?", source, game)) { - librarySearched = true; - allCards.addAll(controller.getLibrary().getCardList()); - } - allCards.addAll(controller.getGraveyard()); - FilterCard filter = new FilterCard("a card named Ajani, Valiant Protector"); - filter.add(new NamePredicate("Ajani, Valiant Protector")); - TargetCard target = new TargetCard(0, 1, Zone.ALL, new FilterCard()); - if (controller.choose(outcome, allCards, target, game)) { - Card cardFound = game.getCard(target.getFirstTarget()); - if (cardFound != null) { - controller.revealCards(sourceObject.getIdName(), new CardsImpl(cardFound), game); - controller.moveCards(cardFound, Zone.HAND, source, game); - } - } - if (librarySearched) { - controller.shuffleLibrary(source, game); - } - return true; - } - return false; - } -} diff --git a/Mage.Sets/src/mage/cards/a/AlphaStatus.java b/Mage.Sets/src/mage/cards/a/AlphaStatus.java index eb158a88028..40e1b2c1513 100644 --- a/Mage.Sets/src/mage/cards/a/AlphaStatus.java +++ b/Mage.Sets/src/mage/cards/a/AlphaStatus.java @@ -40,7 +40,6 @@ import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; -import mage.constants.Rarity; import mage.constants.Zone; import mage.filter.common.FilterCreaturePermanent; import mage.game.Game; diff --git a/Mage.Sets/src/mage/cards/a/ApprenticeNecromancer.java b/Mage.Sets/src/mage/cards/a/ApprenticeNecromancer.java new file mode 100644 index 00000000000..9c37338b784 --- /dev/null +++ b/Mage.Sets/src/mage/cards/a/ApprenticeNecromancer.java @@ -0,0 +1,131 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.a; + +import java.util.UUID; +import mage.MageInt; +import mage.abilities.Ability; +import mage.abilities.DelayedTriggeredAbility; +import mage.abilities.common.SimpleActivatedAbility; +import mage.abilities.common.delayed.AtTheBeginOfNextEndStepDelayedTriggeredAbility; +import mage.abilities.costs.common.SacrificeSourceCost; +import mage.abilities.costs.common.TapSourceCost; +import mage.abilities.costs.mana.ColoredManaCost; +import mage.abilities.effects.ContinuousEffect; +import mage.abilities.effects.OneShotEffect; +import mage.abilities.effects.common.SacrificeTargetEffect; +import mage.abilities.effects.common.continuous.GainAbilityTargetEffect; +import mage.abilities.keyword.HasteAbility; +import mage.cards.Card; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.constants.ColoredManaSymbol; +import mage.constants.Duration; +import mage.constants.Outcome; +import mage.constants.Zone; +import mage.filter.common.FilterCreatureCard; +import mage.game.Game; +import mage.game.permanent.Permanent; +import mage.players.Player; +import mage.target.common.TargetCardInYourGraveyard; +import mage.target.targetpointer.FixedTarget; + +/** + * + * @author spjspj + */ +public class ApprenticeNecromancer extends CardImpl { + + public ApprenticeNecromancer(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}"); + + this.subtype.add("Zombie"); + this.subtype.add("Wizard"); + this.power = new MageInt(1); + this.toughness = new MageInt(1); + + // {B}, {tap}, Sacrifice Apprentice Necromancer: Return target creature card from your graveyard to the battlefield. That creature gains haste. At the beginning of the next end step, sacrifice it. + Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new ApprenticeNecromancerEffect(), new ColoredManaCost(ColoredManaSymbol.B)); + ability.addCost(new TapSourceCost()); + ability.addCost(new SacrificeSourceCost()); + ability.addTarget(new TargetCardInYourGraveyard(new FilterCreatureCard("creature card from your graveyard"))); + this.addAbility(ability); + } + + public ApprenticeNecromancer(final ApprenticeNecromancer card) { + super(card); + } + + @Override + public ApprenticeNecromancer copy() { + return new ApprenticeNecromancer(this); + } +} + +class ApprenticeNecromancerEffect extends OneShotEffect { + + public ApprenticeNecromancerEffect() { + super(Outcome.PutCreatureInPlay); + this.staticText = "Return target creature card from your graveyard to the battlefield. That creature gains haste. At the beginning of the next end step, sacrifice it"; + } + + public ApprenticeNecromancerEffect(final ApprenticeNecromancerEffect effect) { + super(effect); + } + + @Override + public ApprenticeNecromancerEffect copy() { + return new ApprenticeNecromancerEffect(this); + } + + @Override + public boolean apply(Game game, Ability source) { + Card card = game.getCard(this.getTargetPointer().getFirst(game, source)); + Player controller = game.getPlayer(source.getControllerId()); + if (controller != null && card != null) { + if (controller.moveCards(card, Zone.BATTLEFIELD, source, game)) { + Permanent creature = game.getPermanent(card.getId()); + if (creature != null) { + // Gains haste + ContinuousEffect effect = new GainAbilityTargetEffect(HasteAbility.getInstance(), Duration.Custom); + effect.setTargetPointer(new FixedTarget(creature, game)); + game.addEffect(effect, source); + + // Sacrifice at beginning of next end step + SacrificeTargetEffect sacrificeEffect = new SacrificeTargetEffect("sacrifice the creature", source.getControllerId()); + sacrificeEffect.setTargetPointer(new FixedTarget(creature, game)); + DelayedTriggeredAbility delayedAbility = new AtTheBeginOfNextEndStepDelayedTriggeredAbility(sacrificeEffect); + game.addDelayedTriggeredAbility(delayedAbility, source); + } + } + return true; + } + return false; + } +} diff --git a/Mage.Sets/src/mage/cards/a/ArchiveTrap.java b/Mage.Sets/src/mage/cards/a/ArchiveTrap.java index 1c9c1f43313..924278348e7 100644 --- a/Mage.Sets/src/mage/cards/a/ArchiveTrap.java +++ b/Mage.Sets/src/mage/cards/a/ArchiveTrap.java @@ -1,16 +1,16 @@ /* * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR @@ -20,12 +20,11 @@ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. */ - package mage.cards.a; import java.util.HashSet; @@ -53,16 +52,16 @@ import mage.watchers.Watcher; public class ArchiveTrap extends CardImpl { public ArchiveTrap(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{3}{U}{U}"); - + super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{3}{U}{U}"); + this.subtype.add("Trap"); // If an opponent searched his or her library this turn, you may pay {0} rather than pay Archive Trap's mana cost. this.addAbility(new AlternativeCostSourceAbility(new GenericManaCost(0), OpponentSearchesLibCondition.getInstance()), new ArchiveTrapWatcher()); - + // Target opponent puts the top thirteen cards of his or her library into his or her graveyard. this.getSpellAbility().addTarget(new TargetOpponent()); - this.getSpellAbility().addEffect(new PutLibraryIntoGraveTargetEffect(13)); + this.getSpellAbility().addEffect(new PutLibraryIntoGraveTargetEffect(13)); } public ArchiveTrap(final ArchiveTrap card) { @@ -78,7 +77,7 @@ public class ArchiveTrap extends CardImpl { class ArchiveTrapWatcher extends Watcher { Set playerIds = new HashSet<>(); - + public ArchiveTrapWatcher() { super("LibrarySearched", WatcherScope.GAME); } @@ -95,7 +94,8 @@ class ArchiveTrapWatcher extends Watcher { @Override public void watch(GameEvent event, Game game) { - if (event.getType() == EventType.LIBRARY_SEARCHED) { + if (event.getType() == EventType.LIBRARY_SEARCHED + && event.getTargetId().equals(event.getPlayerId())) { // player searched own library playerIds.add(event.getPlayerId()); } } @@ -106,7 +106,6 @@ class ArchiveTrapWatcher extends Watcher { playerIds.clear(); } - public Set getPlayersSearchedLibrary() { return playerIds; } @@ -115,7 +114,7 @@ class ArchiveTrapWatcher extends Watcher { class OpponentSearchesLibCondition implements Condition { private static final OpponentSearchesLibCondition fInstance = new OpponentSearchesLibCondition(); - + public static Condition getInstance() { return fInstance; } @@ -138,5 +137,5 @@ class OpponentSearchesLibCondition implements Condition { public String toString() { return "If an opponent searched his or her library this turn"; } - + } diff --git a/Mage.Sets/src/mage/cards/a/AsylumVisitor.java b/Mage.Sets/src/mage/cards/a/AsylumVisitor.java index 124d7e988cc..ec4777f15f5 100644 --- a/Mage.Sets/src/mage/cards/a/AsylumVisitor.java +++ b/Mage.Sets/src/mage/cards/a/AsylumVisitor.java @@ -62,6 +62,7 @@ public class AsylumVisitor extends CardImpl { "At the beginning of each player's upkeep, if that player has no cards in hand, you draw a card and you lose 1 life."); Effect effect = new LoseLifeSourceControllerEffect(1); effect.setText("and you lose 1 life"); + ability.addEffect(effect); this.addAbility(ability); // Madness {1}{B} diff --git a/Mage.Sets/src/mage/cards/a/AtalyaSamiteMaster.java b/Mage.Sets/src/mage/cards/a/AtalyaSamiteMaster.java new file mode 100644 index 00000000000..e330d44467f --- /dev/null +++ b/Mage.Sets/src/mage/cards/a/AtalyaSamiteMaster.java @@ -0,0 +1,100 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.a; + +import java.util.UUID; +import mage.MageInt; +import mage.abilities.Ability; +import mage.abilities.Mode; +import mage.abilities.common.SimpleActivatedAbility; +import mage.abilities.costs.VariableCost; +import mage.abilities.costs.common.TapSourceCost; +import mage.abilities.costs.mana.ManaCostsImpl; +import mage.abilities.costs.mana.VariableManaCost; +import mage.abilities.dynamicvalue.common.ManacostVariableValue; +import mage.abilities.effects.common.GainLifeEffect; +import mage.abilities.effects.common.PreventDamageToTargetEffect; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.constants.Duration; +import mage.constants.Zone; +import mage.filter.FilterMana; +import mage.target.common.TargetCreaturePermanent; + +/** + * + * @author spjspj + */ +public class AtalyaSamiteMaster extends CardImpl { + + private static final FilterMana filterWhiteMana = new FilterMana(); + + static { + filterWhiteMana.setWhite(true); + } + + public AtalyaSamiteMaster(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{W}{W}"); + + this.supertype.add("Legendary"); + this.subtype.add("Human"); + this.subtype.add("Cleric"); + this.power = new MageInt(2); + this.toughness = new MageInt(3); + + // {X}, {tap}: Choose one - Prevent the next X damage that would be dealt to target creature this turn; or you gain X life. Spend only white mana on X. + PreventDamageToTargetEffect effect = new PreventDamageToTargetEffect(Duration.EndOfTurn, false, true, new ManacostVariableValue()); + effect.setText("Prevent the next X damage that would be dealt to target creature this turn"); + Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, effect, new ManaCostsImpl("{X}")); + ability.addCost(new TapSourceCost()); + + VariableCost variableCost = ability.getManaCostsToPay().getVariableCosts().get(0); + if (variableCost instanceof VariableManaCost) { + ((VariableManaCost) variableCost).setFilter(filterWhiteMana); + } + + ability.addTarget(new TargetCreaturePermanent()); + + // or you gain X life + Mode mode = new Mode(); + mode.getEffects().add(new GainLifeEffect(new ManacostVariableValue())); + ability.addMode(mode); + + this.addAbility(ability); + } + + public AtalyaSamiteMaster(final AtalyaSamiteMaster card) { + super(card); + } + + @Override + public AtalyaSamiteMaster copy() { + return new AtalyaSamiteMaster(this); + } +} diff --git a/Mage.Sets/src/mage/cards/a/AuramancersGuise.java b/Mage.Sets/src/mage/cards/a/AuramancersGuise.java new file mode 100644 index 00000000000..00f22293095 --- /dev/null +++ b/Mage.Sets/src/mage/cards/a/AuramancersGuise.java @@ -0,0 +1,134 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.a; + +import java.util.List; +import java.util.UUID; +import mage.target.common.TargetCreaturePermanent; +import mage.abilities.Ability; +import mage.abilities.common.SimpleStaticAbility; +import mage.abilities.dynamicvalue.DynamicValue; +import mage.abilities.effects.Effect; +import mage.abilities.effects.common.AttachEffect; +import mage.abilities.effects.common.continuous.BoostEnchantedEffect; +import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect; +import mage.constants.Outcome; +import mage.target.TargetPermanent; +import mage.abilities.keyword.EnchantAbility; +import mage.abilities.keyword.VigilanceAbility; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.AttachmentType; +import mage.constants.CardType; +import mage.constants.Duration; +import mage.constants.Zone; +import mage.game.Game; +import mage.game.permanent.Permanent; + +/** + * + * @author spjspj + */ +public class AuramancersGuise extends CardImpl { + + public AuramancersGuise(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{U}{U}"); + + this.subtype.add("Aura"); + + // Enchant creature + TargetPermanent auraTarget = new TargetCreaturePermanent(); + this.getSpellAbility().addTarget(auraTarget); + this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature)); + Ability ability = new EnchantAbility(auraTarget.getTargetName()); + this.addAbility(ability); + + // Enchanted creature gets +2/+2 for each Aura attached to it and has vigilance. + DynamicValue ptBoost = new EnchantedCreatureAurasCount(); + BoostEnchantedEffect effect = new BoostEnchantedEffect(ptBoost, ptBoost, Duration.WhileOnBattlefield); + effect.setText("Enchanted creature gets +2/+2 for each Aura attached to it"); + SimpleStaticAbility ability2 = new SimpleStaticAbility(Zone.BATTLEFIELD, effect); + ability2.addEffect(new GainAbilityAttachedEffect(VigilanceAbility.getInstance(), AttachmentType.AURA)); + this.addAbility(ability2); + } + + public AuramancersGuise(final AuramancersGuise card) { + super(card); + } + + @Override + public AuramancersGuise copy() { + return new AuramancersGuise(this); + } +} + +class EnchantedCreatureAurasCount implements DynamicValue { + + public EnchantedCreatureAurasCount() { + } + + public EnchantedCreatureAurasCount(final EnchantedCreatureAurasCount dynamicValue) { + } + + @Override + public int calculate(Game game, Ability source, Effect effect) { + int count = 0; + Permanent aura = game.getPermanent(source.getSourceId()); + if (aura != null) { + Permanent permanent = game.getPermanent(aura.getAttachedTo()); + if (permanent != null) { + List attachments = permanent.getAttachments(); + for (UUID attachmentId : attachments) { + Permanent attached = game.getPermanent(attachmentId); + if (attached != null && attached.getSubtype(game).contains("Aura")) { + count++; + } + + } + return 2 * count; + } + } + return count; + } + + @Override + public EnchantedCreatureAurasCount copy() { + return new EnchantedCreatureAurasCount(this); + } + + @Override + public String toString() { + return "1"; + } + + @Override + public String getMessage() { + return "of its auras"; + } + +} diff --git a/Mage.Sets/src/mage/cards/a/AvatarOfFury.java b/Mage.Sets/src/mage/cards/a/AvatarOfFury.java index 5e45cbd3db6..659077c6a5f 100644 --- a/Mage.Sets/src/mage/cards/a/AvatarOfFury.java +++ b/Mage.Sets/src/mage/cards/a/AvatarOfFury.java @@ -54,18 +54,18 @@ import mage.util.CardUtil; public class AvatarOfFury extends CardImpl { public AvatarOfFury(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{6}{R}{R}"); + super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{6}{R}{R}"); this.subtype.add("Avatar"); this.power = new MageInt(6); this.toughness = new MageInt(6); // If an opponent controls seven or more lands, Avatar of Fury costs {6} less to cast. - this.addAbility(new AvatarOfFuryAdjustingCostsAbility()); + this.addAbility(new AvatarOfFuryAdjustingCostsAbility()); // Flying this.addAbility(FlyingAbility.getInstance()); // {R}: Avatar of Fury gets +1/+0 until end of turn. - this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new BoostSourceEffect(1,0, Duration.EndOfTurn), new ManaCostsImpl("{R}"))); + this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new BoostSourceEffect(1, 0, Duration.EndOfTurn), new ManaCostsImpl("{R}"))); } public AvatarOfFury(final AvatarOfFury card) { @@ -100,11 +100,13 @@ class AvatarOfFuryAdjustingCostsAbility extends SimpleStaticAbility implements A @Override public void adjustCosts(Ability ability, Game game) { - FilterPermanent filter = new FilterLandPermanent(); - for (UUID playerId: game.getOpponents(ability.getControllerId())) { - if (game.getBattlefield().countAll(filter, playerId, game) > 6) { - CardUtil.adjustCost((SpellAbility)ability, 6); - break; + if (ability instanceof SpellAbility) { // Prevent adjustment of activated ability + FilterPermanent filter = new FilterLandPermanent(); + for (UUID playerId : game.getOpponents(ability.getControllerId())) { + if (game.getBattlefield().countAll(filter, playerId, game) > 6) { + CardUtil.adjustCost((SpellAbility) ability, 6); + break; + } } } } diff --git a/Mage.Sets/src/mage/cards/a/AxebaneGuardian.java b/Mage.Sets/src/mage/cards/a/AxebaneGuardian.java index 38469e3dcd6..0f52894c221 100644 --- a/Mage.Sets/src/mage/cards/a/AxebaneGuardian.java +++ b/Mage.Sets/src/mage/cards/a/AxebaneGuardian.java @@ -30,7 +30,6 @@ package mage.cards.a; import java.util.UUID; import mage.MageInt; import mage.Mana; -import mage.abilities.costs.common.TapSourceCost; import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; import mage.abilities.keyword.DefenderAbility; import mage.abilities.mana.DynamicManaAbility; diff --git a/Mage.Sets/src/mage/cards/b/BaralChiefOfCompliance.java b/Mage.Sets/src/mage/cards/b/BaralChiefOfCompliance.java index 4ef4168d43b..c314cb69d42 100644 --- a/Mage.Sets/src/mage/cards/b/BaralChiefOfCompliance.java +++ b/Mage.Sets/src/mage/cards/b/BaralChiefOfCompliance.java @@ -29,8 +29,8 @@ package mage.cards.b; import java.util.UUID; import mage.MageInt; -import mage.abilities.TriggeredAbilityImpl; import mage.abilities.common.SimpleStaticAbility; +import mage.abilities.common.SpellCounteredControllerTriggeredAbility; import mage.abilities.effects.common.DrawDiscardControllerEffect; import mage.abilities.effects.common.cost.SpellsCostReductionControllerEffect; import mage.cards.CardImpl; @@ -40,11 +40,6 @@ import mage.constants.Zone; import mage.filter.FilterCard; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.CardTypePredicate; -import mage.game.Game; -import mage.game.events.GameEvent; -import mage.game.events.GameEvent.EventType; -import mage.game.stack.Spell; -import mage.game.stack.StackObject; /** * @@ -74,7 +69,7 @@ public class BaralChiefOfCompliance extends CardImpl { this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new SpellsCostReductionControllerEffect(filter, 1))); // Whenever a spell or ability you control counters a spell, you may draw a card. If you do, discard a card. - this.addAbility(new BaralChiefOfComplianceTriggeredAbility()); + this.addAbility(new SpellCounteredControllerTriggeredAbility(new DrawDiscardControllerEffect(), true)); } public BaralChiefOfCompliance(final BaralChiefOfCompliance card) { @@ -86,42 +81,3 @@ public class BaralChiefOfCompliance extends CardImpl { return new BaralChiefOfCompliance(this); } } - -class BaralChiefOfComplianceTriggeredAbility extends TriggeredAbilityImpl { - - public BaralChiefOfComplianceTriggeredAbility() { - super(Zone.BATTLEFIELD, new DrawDiscardControllerEffect(), true); - } - - public BaralChiefOfComplianceTriggeredAbility(final BaralChiefOfComplianceTriggeredAbility ability) { - super(ability); - } - - @Override - public BaralChiefOfComplianceTriggeredAbility copy() { - return new BaralChiefOfComplianceTriggeredAbility(this); - } - - @Override - public boolean checkEventType(GameEvent event, Game game) { - return event.getType() == EventType.COUNTERED; - } - - @Override - public boolean checkTrigger(GameEvent event, Game game) { - StackObject stackObjectThatCountered = (StackObject) game.getStack().getStackObject(event.getSourceId()); - if (stackObjectThatCountered == null) { - stackObjectThatCountered = (StackObject) game.getLastKnownInformation(event.getSourceId(), Zone.STACK); - } - if (stackObjectThatCountered != null && stackObjectThatCountered.getControllerId().equals(getControllerId())) { - StackObject counteredStackObject = (StackObject) game.getLastKnownInformation(event.getTargetId(), Zone.STACK); - return counteredStackObject != null && (counteredStackObject instanceof Spell); - } - return false; - } - - @Override - public String getRule() { - return "Whenever a spell or ability you control counters a spell, " + super.getRule(); - } -} diff --git a/Mage.Sets/src/mage/cards/b/BlindWorship.java b/Mage.Sets/src/mage/cards/b/BlindWorship.java index 63f8fdf3999..567e38f8e53 100644 --- a/Mage.Sets/src/mage/cards/b/BlindWorship.java +++ b/Mage.Sets/src/mage/cards/b/BlindWorship.java @@ -46,7 +46,6 @@ import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.common.FilterCreaturePermanent; -import mage.filter.predicate.permanent.AnotherPredicate; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; diff --git a/Mage.Sets/src/mage/cards/b/BorosFuryShield.java b/Mage.Sets/src/mage/cards/b/BorosFuryShield.java index 1af0c9598a6..fcd96342cf7 100644 --- a/Mage.Sets/src/mage/cards/b/BorosFuryShield.java +++ b/Mage.Sets/src/mage/cards/b/BorosFuryShield.java @@ -34,7 +34,6 @@ import mage.abilities.decorator.ConditionalOneShotEffect; import mage.abilities.effects.Effect; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.PreventDamageByTargetEffect; -import mage.abilities.effects.common.UntapAllControllerEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; @@ -42,7 +41,6 @@ import mage.constants.ColoredManaSymbol; import mage.constants.Duration; import mage.constants.Outcome; import mage.filter.common.FilterAttackingOrBlockingCreature; -import mage.filter.common.FilterControlledCreaturePermanent; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; diff --git a/Mage.Sets/src/mage/cards/b/BurdenOfGreed.java b/Mage.Sets/src/mage/cards/b/BurdenOfGreed.java index 234e13493f7..19a9ff4f991 100644 --- a/Mage.Sets/src/mage/cards/b/BurdenOfGreed.java +++ b/Mage.Sets/src/mage/cards/b/BurdenOfGreed.java @@ -30,15 +30,12 @@ package mage.cards.b; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.dynamicvalue.DynamicValue; -import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; -import mage.abilities.dynamicvalue.common.PermanentsTargetOpponentControlsCount; import mage.abilities.effects.Effect; import mage.abilities.effects.common.LoseLifeTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.common.FilterArtifactPermanent; -import mage.filter.predicate.other.OwnerIdPredicate; import mage.filter.predicate.permanent.ControllerIdPredicate; import mage.filter.predicate.permanent.TappedPredicate; import mage.game.Game; diff --git a/Mage.Sets/src/mage/cards/c/CapriciousEfreet.java b/Mage.Sets/src/mage/cards/c/CapriciousEfreet.java index 096c1ee7f70..c9b0a4a91d6 100644 --- a/Mage.Sets/src/mage/cards/c/CapriciousEfreet.java +++ b/Mage.Sets/src/mage/cards/c/CapriciousEfreet.java @@ -28,7 +28,6 @@ package mage.cards.c; import java.util.ArrayList; -import java.util.Random; import java.util.UUID; import mage.constants.CardType; import mage.constants.Outcome; diff --git a/Mage.Sets/src/mage/cards/c/CarnivalOfSouls.java b/Mage.Sets/src/mage/cards/c/CarnivalOfSouls.java new file mode 100644 index 00000000000..4f0b1878bfa --- /dev/null +++ b/Mage.Sets/src/mage/cards/c/CarnivalOfSouls.java @@ -0,0 +1,72 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.c; + +import java.util.UUID; + +import mage.Mana; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.abilities.Ability; +import mage.abilities.effects.Effect; +import mage.abilities.effects.common.LoseLifeSourceControllerEffect; +import mage.abilities.common.EntersBattlefieldAllTriggeredAbility; +import mage.abilities.effects.common.AddManaToManaPoolSourceControllerEffect; +import mage.constants.SetTargetPointer; +import mage.constants.Zone; +import mage.filter.common.FilterCreaturePermanent; + +/** + * + * @author Galatolol + */ +public class CarnivalOfSouls extends CardImpl { + + public CarnivalOfSouls(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{B}"); + + + // Whenever a creature enters the battlefield, you lose 1 life and add {B} to your mana pool. + Ability ability = new EntersBattlefieldAllTriggeredAbility(Zone.BATTLEFIELD, new LoseLifeSourceControllerEffect(1), + new FilterCreaturePermanent("a creature"), false, SetTargetPointer.PERMANENT, null, false); + Effect effect = new AddManaToManaPoolSourceControllerEffect(Mana.BlackMana(1)); + effect.setText("and add {B} to your mana pool."); + ability.addEffect(effect); + this.addAbility(ability); + } + + public CarnivalOfSouls(final CarnivalOfSouls card) { + super(card); + } + + @Override + public CarnivalOfSouls copy() { + return new CarnivalOfSouls(this); + } +} diff --git a/Mage.Sets/src/mage/cards/c/CeruleanWyvern.java b/Mage.Sets/src/mage/cards/c/CeruleanWyvern.java index 1edb7163dae..6d78503a13a 100644 --- a/Mage.Sets/src/mage/cards/c/CeruleanWyvern.java +++ b/Mage.Sets/src/mage/cards/c/CeruleanWyvern.java @@ -35,8 +35,6 @@ import mage.abilities.keyword.ProtectionAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.filter.FilterCard; -import mage.filter.predicate.mageobject.ColorPredicate; /** * diff --git a/Mage.Sets/src/mage/cards/c/ChampionOfLambholt.java b/Mage.Sets/src/mage/cards/c/ChampionOfLambholt.java index 564ff597cea..68e8bb89601 100644 --- a/Mage.Sets/src/mage/cards/c/ChampionOfLambholt.java +++ b/Mage.Sets/src/mage/cards/c/ChampionOfLambholt.java @@ -27,34 +27,36 @@ */ package mage.cards.c; -import mage.constants.CardType; +import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; +import mage.abilities.common.EntersBattlefieldAllTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.RestrictionEffect; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.CardType; import mage.constants.Duration; +import mage.constants.TargetController; import mage.constants.Zone; import mage.counters.CounterType; -import mage.game.Game; -import mage.game.permanent.Permanent; - -import java.util.UUID; -import mage.abilities.common.EntersBattlefieldAllTriggeredAbility; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.permanent.AnotherPredicate; +import mage.filter.predicate.permanent.ControllerPredicate; +import mage.game.Game; +import mage.game.permanent.Permanent; /** * @author noxx */ public class ChampionOfLambholt extends CardImpl { - private static FilterCreaturePermanent filter = new FilterCreaturePermanent("another creature"); + private final static FilterCreaturePermanent filter = new FilterCreaturePermanent("another creature"); static { filter.add(new AnotherPredicate()); + filter.add(new ControllerPredicate(TargetController.YOU)); } public ChampionOfLambholt(UUID ownerId, CardSetInfo setInfo) { diff --git a/Mage.Sets/src/mage/cards/c/ChandrasRevolution.java b/Mage.Sets/src/mage/cards/c/ChandrasRevolution.java index 36facecd20b..7099c2b18ee 100644 --- a/Mage.Sets/src/mage/cards/c/ChandrasRevolution.java +++ b/Mage.Sets/src/mage/cards/c/ChandrasRevolution.java @@ -36,10 +36,8 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; -import mage.filter.common.FilterLandPermanent; import mage.game.Game; import mage.game.permanent.Permanent; -import mage.target.Target; import mage.target.common.TargetCreaturePermanent; import mage.target.common.TargetLandPermanent; import mage.target.targetpointer.FixedTarget; @@ -53,13 +51,9 @@ public class ChandrasRevolution extends CardImpl { public ChandrasRevolution(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{R}"); - // Chandra's Revolution deals 4 damage to target creature. - Target target = new TargetCreaturePermanent(); - this.getSpellAbility().addTarget(target); - - // Tap target land. That land doesn't untap during its controller's next untap step. - Target target2 = new TargetLandPermanent(new FilterLandPermanent()); - this.getSpellAbility().addTarget(target2); + // Chandra's Revolution deals 4 damage to target creature. Tap target land. That land doesn't untap during its controller's next untap step. + this.getSpellAbility().addTarget(new TargetCreaturePermanent()); + this.getSpellAbility().addTarget(new TargetLandPermanent()); this.getSpellAbility().addEffect(new ChandrasRevolutionEffect()); } diff --git a/Mage.Sets/src/mage/cards/c/ChargingCinderhorn.java b/Mage.Sets/src/mage/cards/c/ChargingCinderhorn.java index 3b83b66ce6c..6a6c6610270 100644 --- a/Mage.Sets/src/mage/cards/c/ChargingCinderhorn.java +++ b/Mage.Sets/src/mage/cards/c/ChargingCinderhorn.java @@ -31,7 +31,6 @@ import java.util.Set; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; -import mage.abilities.Mode; import mage.abilities.common.BeginningOfEndStepTriggeredAbility; import mage.abilities.condition.Condition; import mage.abilities.dynamicvalue.DynamicValue; diff --git a/Mage.Sets/src/mage/cards/c/CharmbreakerDevils.java b/Mage.Sets/src/mage/cards/c/CharmbreakerDevils.java index a3f518e02dd..da6a675bf85 100644 --- a/Mage.Sets/src/mage/cards/c/CharmbreakerDevils.java +++ b/Mage.Sets/src/mage/cards/c/CharmbreakerDevils.java @@ -27,7 +27,6 @@ */ package mage.cards.c; -import java.util.Random; import java.util.UUID; import mage.constants.CardType; import mage.constants.Duration; diff --git a/Mage.Sets/src/mage/cards/c/ChiefOfTheEdge.java b/Mage.Sets/src/mage/cards/c/ChiefOfTheEdge.java index b9bbb0a2190..6419764cc32 100644 --- a/Mage.Sets/src/mage/cards/c/ChiefOfTheEdge.java +++ b/Mage.Sets/src/mage/cards/c/ChiefOfTheEdge.java @@ -35,7 +35,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.Rarity; import mage.constants.Zone; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.SubtypePredicate; diff --git a/Mage.Sets/src/mage/cards/c/ChiefOfTheScale.java b/Mage.Sets/src/mage/cards/c/ChiefOfTheScale.java index 81c75b30d1b..474a2fb5ca5 100644 --- a/Mage.Sets/src/mage/cards/c/ChiefOfTheScale.java +++ b/Mage.Sets/src/mage/cards/c/ChiefOfTheScale.java @@ -35,7 +35,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.Rarity; import mage.constants.Zone; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.SubtypePredicate; diff --git a/Mage.Sets/src/mage/cards/c/ChitteringHost.java b/Mage.Sets/src/mage/cards/c/ChitteringHost.java index 5dd2b7d9687..483cd5585a6 100644 --- a/Mage.Sets/src/mage/cards/c/ChitteringHost.java +++ b/Mage.Sets/src/mage/cards/c/ChitteringHost.java @@ -39,7 +39,6 @@ import mage.cards.CardSetInfo; import mage.cards.MeldCard; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.Rarity; import mage.filter.common.FilterControlledCreaturePermanent; import java.util.UUID; diff --git a/Mage.Sets/src/mage/cards/c/ChordOfCalling.java b/Mage.Sets/src/mage/cards/c/ChordOfCalling.java index b1e87f3c7d1..bd3263ae9c4 100644 --- a/Mage.Sets/src/mage/cards/c/ChordOfCalling.java +++ b/Mage.Sets/src/mage/cards/c/ChordOfCalling.java @@ -28,22 +28,12 @@ package mage.cards.c; import java.util.UUID; -import mage.abilities.Ability; -import mage.abilities.effects.OneShotEffect; +import mage.abilities.effects.common.search.SearchLibraryWithLessCMCPutInPlayEffect; import mage.abilities.keyword.ConvokeAbility; -import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Outcome; -import mage.constants.Zone; -import mage.filter.Filter; -import mage.filter.FilterCard; -import mage.filter.predicate.mageobject.CardTypePredicate; -import mage.filter.predicate.mageobject.ConvertedManaCostPredicate; -import mage.game.Game; -import mage.players.Player; -import mage.target.common.TargetCardInLibrary; +import mage.filter.common.FilterCreatureCard; /** * @@ -52,13 +42,13 @@ import mage.target.common.TargetCardInLibrary; public class ChordOfCalling extends CardImpl { public ChordOfCalling(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{X}{G}{G}{G}"); + super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{X}{G}{G}{G}"); // Convoke (Your creatures can help cast this spell. Each creature you tap while casting this spell pays for {1} or one mana of that creature's color.) this.addAbility(new ConvokeAbility()); // Search your library for a creature card with converted mana cost X or less and put it onto the battlefield. Then shuffle your library. - this.getSpellAbility().addEffect(new ChordofCallingSearchEffect()); + this.getSpellAbility().addEffect(new SearchLibraryWithLessCMCPutInPlayEffect(new FilterCreatureCard())); } public ChordOfCalling(final ChordOfCalling card) { @@ -70,48 +60,3 @@ public class ChordOfCalling extends CardImpl { return new ChordOfCalling(this); } } - -class ChordofCallingSearchEffect extends OneShotEffect { - - ChordofCallingSearchEffect() { - super(Outcome.PutCreatureInPlay); - staticText = "Search your library for a creature card with converted mana cost X or less, put it onto the battlefield, then shuffle your library"; - } - - ChordofCallingSearchEffect(final ChordofCallingSearchEffect effect) { - super(effect); - } - - @Override - public boolean apply(Game game, Ability source) { - Player player = game.getPlayer(source.getControllerId()); - Card sourceCard = game.getCard(source.getSourceId()); - if (player == null || sourceCard == null) { - return false; - } - int xCost = source.getManaCostsToPay().getX(); - FilterCard filter = new FilterCard(new StringBuilder("creature card with converted mana cost ").append(xCost).append(" or less").toString()); - filter.add(new CardTypePredicate(CardType.CREATURE)); - //Set the mana cost one higher to 'emulate' a less than or equal to comparison. - filter.add(new ConvertedManaCostPredicate(Filter.ComparisonType.LessThan, xCost + 1)); - TargetCardInLibrary target = new TargetCardInLibrary(0, 1, filter); - if (player.searchLibrary(target, game)) { - if (target.getTargets().size() > 0) { - Card card = player.getLibrary().getCard(target.getFirstTarget(), game); - if (card != null) { - game.informPlayers(new StringBuilder(sourceCard.getName()).append(": Put ").append(card.getName()).append(" onto the battlefield").toString()); - card.putOntoBattlefield(game, Zone.LIBRARY, source.getSourceId(), source.getControllerId()); - } - } - player.shuffleLibrary(source, game); - return true; - } - player.shuffleLibrary(source, game); - return false; - } - - @Override - public ChordofCallingSearchEffect copy() { - return new ChordofCallingSearchEffect(this); - } -} diff --git a/Mage.Sets/src/mage/cards/c/CloakOfInvisibility.java b/Mage.Sets/src/mage/cards/c/CloakOfInvisibility.java index 6b5bcb08377..826c6203345 100644 --- a/Mage.Sets/src/mage/cards/c/CloakOfInvisibility.java +++ b/Mage.Sets/src/mage/cards/c/CloakOfInvisibility.java @@ -30,7 +30,6 @@ package mage.cards.c; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; -import mage.abilities.effects.RestrictionEffect; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.combat.CantBeBlockedByCreaturesAttachedEffect; import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect; @@ -46,8 +45,6 @@ import mage.constants.Zone; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.SubtypePredicate; -import mage.game.Game; -import mage.game.permanent.Permanent; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; diff --git a/Mage.Sets/src/mage/cards/c/CoalGolem.java b/Mage.Sets/src/mage/cards/c/CoalGolem.java index 16aca1ace66..dbb9a1e40ab 100644 --- a/Mage.Sets/src/mage/cards/c/CoalGolem.java +++ b/Mage.Sets/src/mage/cards/c/CoalGolem.java @@ -33,7 +33,6 @@ import mage.Mana; import mage.abilities.Ability; import mage.abilities.costs.common.SacrificeSourceCost; import mage.abilities.costs.mana.GenericManaCost; -import mage.abilities.effects.common.BasicManaEffect; import mage.abilities.mana.SimpleManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/c/CogworkAssembler.java b/Mage.Sets/src/mage/cards/c/CogworkAssembler.java index a5ce6219cb1..0432779b8ba 100644 --- a/Mage.Sets/src/mage/cards/c/CogworkAssembler.java +++ b/Mage.Sets/src/mage/cards/c/CogworkAssembler.java @@ -42,10 +42,9 @@ import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.Zone; -import mage.filter.StaticFilters; import mage.game.Game; import mage.game.permanent.Permanent; -import mage.target.common.TargetControlledPermanent; +import mage.target.common.TargetArtifactPermanent; import mage.target.targetpointer.FixedTarget; /** @@ -63,7 +62,7 @@ public class CogworkAssembler extends CardImpl { // {7}: Create a token that's a copy of target artifact. That token gains haste. Exile it at the beginning of the next end step. Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new CogworkAssemblerCreateTokenEffect(), new GenericManaCost(7)); - ability.addTarget(new TargetControlledPermanent(StaticFilters.FILTER_CONTROLLED_PERMANENT_ARTIFACT)); + ability.addTarget(new TargetArtifactPermanent()); this.addAbility(ability); } diff --git a/Mage.Sets/src/mage/cards/c/CountlessGearsRenegade.java b/Mage.Sets/src/mage/cards/c/CountlessGearsRenegade.java index afa170bb53d..7c11d16303f 100644 --- a/Mage.Sets/src/mage/cards/c/CountlessGearsRenegade.java +++ b/Mage.Sets/src/mage/cards/c/CountlessGearsRenegade.java @@ -25,23 +25,22 @@ * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. */ - package mage.cards.c; +import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.RevoltCondition; -import mage.abilities.decorator.ConditionalOneShotEffect; +import mage.abilities.decorator.ConditionalTriggeredAbility; import mage.abilities.effects.common.CreateTokenEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.AbilityWord; import mage.constants.CardType; import mage.game.permanent.token.ServoToken; import mage.watchers.common.RevoltWatcher; -import java.util.UUID; - /** * @author JRHerlehy */ @@ -57,9 +56,11 @@ public class CountlessGearsRenegade extends CardImpl { // Revolt — When Countless Gears Renegade enters the battlefield, if a permanent you controlled // left the battlefield this turn, create a 1/1 colorless Servo artifact creature token. - Ability ability = new EntersBattlefieldTriggeredAbility( - new ConditionalOneShotEffect(new CreateTokenEffect(new ServoToken(), 1), RevoltCondition.getInstance()), - false, "Revolt — "); + Ability ability = new ConditionalTriggeredAbility(new EntersBattlefieldTriggeredAbility( + new CreateTokenEffect(new ServoToken(), 1), false), RevoltCondition.getInstance(), + "Revolt — When {this} enters the battlefield, if a permanent you controlled left" + + " the battlefield this turn, create a 1/1 colorless Servo artifact creature token."); + ability.setAbilityWord(AbilityWord.REVOLT); ability.addWatcher(new RevoltWatcher()); this.addAbility(ability); } diff --git a/Mage.Sets/src/mage/cards/c/Curfew.java b/Mage.Sets/src/mage/cards/c/Curfew.java index 169bfcb3b74..11c06ac8c42 100644 --- a/Mage.Sets/src/mage/cards/c/Curfew.java +++ b/Mage.Sets/src/mage/cards/c/Curfew.java @@ -39,14 +39,10 @@ import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.common.FilterControlledCreaturePermanent; -import mage.filter.common.FilterControlledPermanent; import mage.game.Game; -import mage.game.events.GameEvent; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.common.TargetControlledCreaturePermanent; -import mage.target.common.TargetControlledPermanent; -import mage.target.common.TargetCreaturePermanent; /** * diff --git a/Mage.Sets/src/mage/cards/d/DaringDemolition.java b/Mage.Sets/src/mage/cards/d/DaringDemolition.java index 58ba75539d0..ab85bbe754c 100644 --- a/Mage.Sets/src/mage/cards/d/DaringDemolition.java +++ b/Mage.Sets/src/mage/cards/d/DaringDemolition.java @@ -47,7 +47,7 @@ public class DaringDemolition extends CardImpl { private final static FilterPermanent filter = new FilterPermanent("creature or Vehicle"); static { - Predicates.or(new CardTypePredicate(CardType.CREATURE), new SubtypePredicate("Vehicle")); + filter.add(Predicates.or(new CardTypePredicate(CardType.CREATURE), new SubtypePredicate("Vehicle"))); } public DaringDemolition(UUID ownerId, CardSetInfo setInfo) { diff --git a/Mage.Sets/src/mage/cards/d/DeadeyeHarpooner.java b/Mage.Sets/src/mage/cards/d/DeadeyeHarpooner.java index 9bfaaa6996c..bf07e3ace78 100644 --- a/Mage.Sets/src/mage/cards/d/DeadeyeHarpooner.java +++ b/Mage.Sets/src/mage/cards/d/DeadeyeHarpooner.java @@ -32,10 +32,11 @@ import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.RevoltCondition; -import mage.abilities.decorator.ConditionalOneShotEffect; +import mage.abilities.decorator.ConditionalTriggeredAbility; import mage.abilities.effects.common.DestroyTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.AbilityWord; import mage.constants.CardType; import mage.filter.common.FilterOpponentsCreaturePermanent; import mage.filter.predicate.permanent.TappedPredicate; @@ -63,11 +64,12 @@ public class DeadeyeHarpooner extends CardImpl { this.toughness = new MageInt(2); // Revolt — When Deadeye Harpooner enters the battlefield, if a permanent you controlled left the battlefield this turn, destroy target tapped creature an opponent controls. - Ability ability = new EntersBattlefieldTriggeredAbility( - new ConditionalOneShotEffect(new DestroyTargetEffect(), RevoltCondition.getInstance()), - false, - "Revolt — " + Ability ability = new ConditionalTriggeredAbility(new EntersBattlefieldTriggeredAbility( + new DestroyTargetEffect(), false), RevoltCondition.getInstance(), + "Revolt — When {this} enters the battlefield, if a permanent you controlled left" + + " the battlefield this turn, destroy target tapped creature an opponent controls." ); + ability.setAbilityWord(AbilityWord.REVOLT); ability.addTarget(new TargetOpponentsCreaturePermanent(filter)); ability.addWatcher(new RevoltWatcher()); this.addAbility(ability); diff --git a/Mage.Sets/src/mage/cards/d/DisruptingShoal.java b/Mage.Sets/src/mage/cards/d/DisruptingShoal.java index 7ea8a7d49be..135d930f682 100644 --- a/Mage.Sets/src/mage/cards/d/DisruptingShoal.java +++ b/Mage.Sets/src/mage/cards/d/DisruptingShoal.java @@ -38,7 +38,6 @@ import mage.abilities.effects.OneShotEffect; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.cards.CardSetInfo; import mage.cards.SplitCard; import mage.constants.CardType; import mage.constants.Outcome; diff --git a/Mage.Sets/src/mage/cards/d/DistemperOfTheBlood.java b/Mage.Sets/src/mage/cards/d/DistemperOfTheBlood.java index fa67866e62e..abff2196f66 100644 --- a/Mage.Sets/src/mage/cards/d/DistemperOfTheBlood.java +++ b/Mage.Sets/src/mage/cards/d/DistemperOfTheBlood.java @@ -30,7 +30,6 @@ package mage.cards.d; import java.util.UUID; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.Effect; -import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.effects.common.continuous.BoostTargetEffect; import mage.abilities.effects.common.continuous.GainAbilityTargetEffect; import mage.abilities.keyword.MadnessAbility; diff --git a/Mage.Sets/src/mage/cards/d/DivergentGrowth.java b/Mage.Sets/src/mage/cards/d/DivergentGrowth.java new file mode 100644 index 00000000000..986041f9664 --- /dev/null +++ b/Mage.Sets/src/mage/cards/d/DivergentGrowth.java @@ -0,0 +1,67 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.d; + +import java.util.UUID; + +import mage.abilities.effects.common.continuous.GainAbilityAllEffect; +import mage.abilities.mana.ActivatedManaAbilityImpl; +import mage.abilities.mana.AnyColorManaAbility; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.constants.Duration; +import mage.filter.common.FilterControlledLandPermanent; +import mage.abilities.effects.Effect; + +/** + * + * @author Galatolol + */ +public class DivergentGrowth extends CardImpl { + + public DivergentGrowth(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{G}"); + + + // Until end of turn, lands you control gain "{tap}: Add one mana of any color to your mana pool." + ActivatedManaAbilityImpl ability = new AnyColorManaAbility(); + Effect effect = new GainAbilityAllEffect(ability, Duration.EndOfTurn, new FilterControlledLandPermanent()); + effect.setText("Until end of turn, lands you control gain \"{T}: Add one mana of any color to your mana pool.\""); + this.getSpellAbility().addEffect(effect); + } + + public DivergentGrowth(final DivergentGrowth card) { + super(card); + } + + @Override + public DivergentGrowth copy() { + return new DivergentGrowth(this); + } +} diff --git a/Mage.Sets/src/mage/cards/d/DreamLeash.java b/Mage.Sets/src/mage/cards/d/DreamLeash.java index 80e9e8fdbbc..809e8d331ce 100644 --- a/Mage.Sets/src/mage/cards/d/DreamLeash.java +++ b/Mage.Sets/src/mage/cards/d/DreamLeash.java @@ -39,12 +39,9 @@ import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.Zone; -import mage.filter.FilterPermanent; -import mage.filter.predicate.permanent.TappedPredicate; import mage.game.Game; import mage.game.permanent.Permanent; import mage.target.TargetPermanent; -import mage.target.common.TargetCreaturePermanent; /** * diff --git a/Mage.Sets/src/mage/cards/d/DrillSkimmer.java b/Mage.Sets/src/mage/cards/d/DrillSkimmer.java index 5f81a89f6fe..39724be4189 100644 --- a/Mage.Sets/src/mage/cards/d/DrillSkimmer.java +++ b/Mage.Sets/src/mage/cards/d/DrillSkimmer.java @@ -29,25 +29,20 @@ package mage.cards.d; import java.util.UUID; import mage.MageInt; -import mage.ObjectColor; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.condition.Condition; import mage.abilities.condition.common.PermanentsOnTheBattlefieldCondition; import mage.abilities.decorator.ConditionalContinuousEffect; import mage.abilities.effects.common.continuous.GainAbilitySourceEffect; import mage.abilities.keyword.FlyingAbility; -import mage.abilities.keyword.LifelinkAbility; import mage.abilities.keyword.ShroudAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Zone; -import mage.filter.common.FilterControlledArtifactPermanent; import mage.filter.common.FilterControlledCreaturePermanent; -import mage.filter.common.FilterControlledPlaneswalkerPermanent; import mage.filter.predicate.mageobject.CardTypePredicate; -import mage.filter.predicate.mageobject.ColorPredicate; import mage.filter.predicate.permanent.AnotherPredicate; /** diff --git a/Mage.Sets/src/mage/cards/d/DwarvenLandslide.java b/Mage.Sets/src/mage/cards/d/DwarvenLandslide.java index 85b7b706680..cae767d2f2f 100644 --- a/Mage.Sets/src/mage/cards/d/DwarvenLandslide.java +++ b/Mage.Sets/src/mage/cards/d/DwarvenLandslide.java @@ -42,7 +42,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.common.FilterControlledLandPermanent; -import mage.filter.common.FilterLandPermanent; import mage.game.Game; import mage.target.common.TargetControlledPermanent; import mage.target.common.TargetLandPermanent; diff --git a/Mage.Sets/src/mage/cards/e/EerieInterlude.java b/Mage.Sets/src/mage/cards/e/EerieInterlude.java index a71b6bf0657..2d5c954b8ac 100644 --- a/Mage.Sets/src/mage/cards/e/EerieInterlude.java +++ b/Mage.Sets/src/mage/cards/e/EerieInterlude.java @@ -38,7 +38,6 @@ import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.ReturnToBattlefieldUnderOwnerControlTargetEffect; import mage.cards.Card; import mage.cards.CardImpl; -import mage.cards.CardSetInfo; import mage.cards.Cards; import mage.cards.CardsImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/e/EfficientConstruction.java b/Mage.Sets/src/mage/cards/e/EfficientConstruction.java index dd6d4423a7e..fd2e6addb8f 100644 --- a/Mage.Sets/src/mage/cards/e/EfficientConstruction.java +++ b/Mage.Sets/src/mage/cards/e/EfficientConstruction.java @@ -42,13 +42,11 @@ import mage.game.permanent.token.ThopterColorlessToken; */ public class EfficientConstruction extends CardImpl { - private static final FilterArtifactSpell filter = new FilterArtifactSpell("an artifact spell"); - public EfficientConstruction(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{3}{U}"); // Whenever you cast an artifact spell, create a 1/1 colorless Thopter artifact creature token with flying. - this.addAbility(new SpellCastControllerTriggeredAbility(new CreateTokenEffect(new ThopterColorlessToken()), filter, false)); + this.addAbility(new SpellCastControllerTriggeredAbility(new CreateTokenEffect(new ThopterColorlessToken()), new FilterArtifactSpell("an artifact spell"), false)); } public EfficientConstruction(final EfficientConstruction card) { diff --git a/Mage.Sets/src/mage/cards/e/EmbodimentOfFury.java b/Mage.Sets/src/mage/cards/e/EmbodimentOfFury.java index b3978962446..37ad396db97 100644 --- a/Mage.Sets/src/mage/cards/e/EmbodimentOfFury.java +++ b/Mage.Sets/src/mage/cards/e/EmbodimentOfFury.java @@ -40,16 +40,12 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.TargetController; import mage.constants.Zone; import mage.filter.FilterPermanent; import mage.filter.common.FilterControlledLandPermanent; -import mage.filter.common.FilterLandPermanent; import mage.filter.predicate.mageobject.CardTypePredicate; -import mage.filter.predicate.permanent.ControllerPredicate; import mage.game.permanent.token.Token; import mage.target.TargetPermanent; -import mage.target.common.TargetLandPermanent; /** * diff --git a/Mage.Sets/src/mage/cards/e/EnergyField.java b/Mage.Sets/src/mage/cards/e/EnergyField.java index 34d5b3bb32a..5e601c6636b 100644 --- a/Mage.Sets/src/mage/cards/e/EnergyField.java +++ b/Mage.Sets/src/mage/cards/e/EnergyField.java @@ -28,6 +28,7 @@ package mage.cards.e; import java.util.UUID; + import mage.abilities.Ability; import mage.abilities.common.PutCardIntoGraveFromAnywhereAllTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; @@ -43,13 +44,12 @@ import mage.game.Game; import mage.game.events.GameEvent; /** - * * @author Plopman */ public class EnergyField extends CardImpl { public EnergyField(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{1}{U}"); + super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{U}"); // Prevent all damage that would be dealt to you by sources you don't control. @@ -100,8 +100,8 @@ class EnergyFieldEffect extends PreventionEffectImpl { @Override public boolean applies(GameEvent event, Ability source, Game game) { - if (event.getType().equals(GameEvent.EventType.DAMAGE_PLAYER)) { - if (event.getTargetId().equals(source.getControllerId()) && game.getControllerId(event.getSourceId()) != source.getControllerId()){ + if (event.getType() == GameEvent.EventType.DAMAGE_PLAYER) { + if (event.getTargetId().equals(source.getControllerId()) && game.getControllerId(event.getSourceId()) != source.getControllerId()) { return super.applies(event, source, game); } } diff --git a/Mage.Sets/src/mage/cards/e/EnlightenedAscetic.java b/Mage.Sets/src/mage/cards/e/EnlightenedAscetic.java index 3e349dcfe84..482932feecc 100644 --- a/Mage.Sets/src/mage/cards/e/EnlightenedAscetic.java +++ b/Mage.Sets/src/mage/cards/e/EnlightenedAscetic.java @@ -35,9 +35,6 @@ import mage.abilities.effects.common.DestroyTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.filter.common.FilterEnchantmentPermanent; -import mage.target.Target; -import mage.target.TargetPermanent; import mage.target.common.TargetEnchantmentPermanent; /** diff --git a/Mage.Sets/src/mage/cards/e/EssenceFlux.java b/Mage.Sets/src/mage/cards/e/EssenceFlux.java index 9f017c9c24b..d40cc6e44d1 100644 --- a/Mage.Sets/src/mage/cards/e/EssenceFlux.java +++ b/Mage.Sets/src/mage/cards/e/EssenceFlux.java @@ -35,7 +35,6 @@ import mage.abilities.effects.common.ExileTargetForSourceEffect; import mage.abilities.effects.common.counter.AddCountersTargetEffect; import mage.cards.Card; import mage.cards.CardImpl; -import mage.cards.CardSetInfo; import mage.cards.Cards; import mage.cards.CardsImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/f/FairgroundsTrumpeter.java b/Mage.Sets/src/mage/cards/f/FairgroundsTrumpeter.java index 4fd107f1179..6d31fd6d877 100644 --- a/Mage.Sets/src/mage/cards/f/FairgroundsTrumpeter.java +++ b/Mage.Sets/src/mage/cards/f/FairgroundsTrumpeter.java @@ -54,17 +54,17 @@ import mage.watchers.Watcher; public class FairgroundsTrumpeter extends CardImpl { public FairgroundsTrumpeter(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{G}"); + super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{G}"); this.subtype.add("Elephant"); this.power = new MageInt(2); this.toughness = new MageInt(2); // At the beginning of each end step, if a +1/+1 counter was placed on a permanent under your control this turn, put a +1/+1 counter on Fairgrounds Trumpeter. this.addAbility(new ConditionalTriggeredAbility(new BeginningOfEndStepTriggeredAbility( - new AddCountersSourceEffect(CounterType.P1P1.createInstance()), - TargetController.ANY, false), FairgroundsTrumpeterCondition.getInstance(), - "At the beginning of each end step, if a +1/+1 counter was placed on a permanent under your control this turn, put a +1/+1 counter on Fairgrounds Trumpeter."), - new FairgroundsTrumpeterWatcher()); + new AddCountersSourceEffect(CounterType.P1P1.createInstance()), + TargetController.ANY, false), FairgroundsTrumpeterCondition.getInstance(), + "At the beginning of each end step, if a +1/+1 counter was placed on a permanent under your control this turn, put a +1/+1 counter on {this}."), + new FairgroundsTrumpeterWatcher()); } public FairgroundsTrumpeter(final FairgroundsTrumpeter card) { @@ -87,7 +87,7 @@ class FairgroundsTrumpeterCondition implements Condition { @Override public boolean apply(Game game, Ability source) { - FairgroundsTrumpeterWatcher watcher = (FairgroundsTrumpeterWatcher) game.getState().getWatchers().get("FairgroundsTrumpeterWatcher"); + FairgroundsTrumpeterWatcher watcher = (FairgroundsTrumpeterWatcher) game.getState().getWatchers().get(FairgroundsTrumpeterWatcher.class.getName()); return watcher != null && watcher.p1p1AddedToPermanent(source.getControllerId()); } @@ -103,7 +103,7 @@ class FairgroundsTrumpeterWatcher extends Watcher { private final Set players = new HashSet<>(); public FairgroundsTrumpeterWatcher() { - super("FairgroundsTrumpeterWatcher", WatcherScope.GAME); + super(FairgroundsTrumpeterWatcher.class.getName(), WatcherScope.GAME); } public FairgroundsTrumpeterWatcher(final FairgroundsTrumpeterWatcher watcher) { @@ -115,7 +115,7 @@ class FairgroundsTrumpeterWatcher extends Watcher { public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.COUNTER_ADDED && event.getData().equals(CounterType.P1P1.getName())) { Permanent permanent = game.getPermanentOrLKIBattlefield(event.getTargetId()); - if (permanent != null && permanent.getCardType().contains(CardType.CREATURE)) { + if (permanent != null) { players.add(permanent.getControllerId()); } } @@ -135,4 +135,3 @@ class FairgroundsTrumpeterWatcher extends Watcher { return new FairgroundsTrumpeterWatcher(this); } } - diff --git a/Mage.Sets/src/mage/cards/f/FarsightMask.java b/Mage.Sets/src/mage/cards/f/FarsightMask.java index 5f70115d9c0..b395b3a8b47 100644 --- a/Mage.Sets/src/mage/cards/f/FarsightMask.java +++ b/Mage.Sets/src/mage/cards/f/FarsightMask.java @@ -28,6 +28,7 @@ package mage.cards.f; import java.util.UUID; + import mage.constants.CardType; import mage.constants.Zone; import mage.abilities.TriggeredAbilityImpl; @@ -39,13 +40,12 @@ import mage.game.events.GameEvent; import mage.game.permanent.Permanent; /** - * * @author North */ public class FarsightMask extends CardImpl { public FarsightMask(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT},"{5}"); + super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{5}"); // Whenever a source an opponent controls deals damage to you, if Farsight Mask is untapped, you may draw a card. this.addAbility(new FarsightMaskTriggeredAbility()); @@ -78,7 +78,7 @@ class FarsightMaskTriggeredAbility extends TriggeredAbilityImpl { @Override public boolean checkEventType(GameEvent event, Game game) { - return event.getType().equals(GameEvent.EventType.DAMAGED_PLAYER); + return event.getType() == GameEvent.EventType.DAMAGED_PLAYER; } @Override diff --git a/Mage.Sets/src/mage/cards/f/FatalPush.java b/Mage.Sets/src/mage/cards/f/FatalPush.java index 37057f3b0ad..33503498e84 100644 --- a/Mage.Sets/src/mage/cards/f/FatalPush.java +++ b/Mage.Sets/src/mage/cards/f/FatalPush.java @@ -1,96 +1,101 @@ -/* - * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of BetaSteward_at_googlemail.com. - */ -package mage.cards.f; - -import java.util.UUID; -import mage.abilities.Ability; -import mage.abilities.condition.common.RevoltCondition; -import mage.abilities.effects.OneShotEffect; -import mage.cards.CardImpl; -import mage.cards.CardSetInfo; -import mage.constants.CardType; -import mage.constants.Outcome; -import mage.game.Game; -import mage.game.permanent.Permanent; -import mage.target.common.TargetCreaturePermanent; -import mage.watchers.common.RevoltWatcher; - -/** - * - * @author emerald000 - */ -public class FatalPush extends CardImpl { - - public FatalPush(UUID ownerId, CardSetInfo setInfo) { - super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{B}"); - - // Destroy target creature if it has converted mana cost 2 or less. - // Revolt — Destroy that creature if it has converted mana cost 4 or less instead if a permanent you controlled left the battlefield this turn. - this.getSpellAbility().addEffect(new FatalPushEffect()); - this.getSpellAbility().addWatcher(new RevoltWatcher()); - this.getSpellAbility().addTarget(new TargetCreaturePermanent()); - } - - public FatalPush(final FatalPush card) { - super(card); - } - - @Override - public FatalPush copy() { - return new FatalPush(this); - } -} -class FatalPushEffect extends OneShotEffect { - - FatalPushEffect() { - super(Outcome.DestroyPermanent); - this.staticText = "Destroy target creature if it has converted mana cost 2 or less.
Revolt — Destroy that creature if it has converted mana cost 4 or less instead if a permanent you controlled left the battlefield this turn."; - } - - FatalPushEffect(final FatalPushEffect effect) { - super(effect); - } - - @Override - public FatalPushEffect copy() { - return new FatalPushEffect(this); - } - - @Override - public boolean apply(Game game, Ability source) { - Permanent targetCreature = game.getPermanent(this.getTargetPointer().getFirst(game, source)); - if (targetCreature != null) { - int cmc = targetCreature.getConvertedManaCost(); - if (cmc <= 2 || (RevoltCondition.getInstance().apply(game, source) && cmc <= 4)) { - targetCreature.destroy(source.getSourceId(), game, false); - } - return true; - } - return false; - } -} +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.f; + +import java.util.UUID; +import mage.abilities.Ability; +import mage.abilities.condition.common.RevoltCondition; +import mage.abilities.effects.OneShotEffect; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.constants.Outcome; +import mage.game.Game; +import mage.game.permanent.Permanent; +import mage.players.Player; +import mage.target.common.TargetCreaturePermanent; +import mage.watchers.common.RevoltWatcher; + +/** + * + * @author emerald000 + */ +public class FatalPush extends CardImpl { + + public FatalPush(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{B}"); + + // Destroy target creature if it has converted mana cost 2 or less. + // Revolt — Destroy that creature if it has converted mana cost 4 or less instead if a permanent you controlled left the battlefield this turn. + this.getSpellAbility().addEffect(new FatalPushEffect()); + this.getSpellAbility().addWatcher(new RevoltWatcher()); + this.getSpellAbility().addTarget(new TargetCreaturePermanent()); + } + + public FatalPush(final FatalPush card) { + super(card); + } + + @Override + public FatalPush copy() { + return new FatalPush(this); + } +} + +class FatalPushEffect extends OneShotEffect { + + FatalPushEffect() { + super(Outcome.DestroyPermanent); + this.staticText = "Destroy target creature if it has converted mana cost 2 or less.
Revolt — Destroy that creature if it has converted mana cost 4 or less instead if a permanent you controlled left the battlefield this turn."; + } + + FatalPushEffect(final FatalPushEffect effect) { + super(effect); + } + + @Override + public FatalPushEffect copy() { + return new FatalPushEffect(this); + } + + @Override + public boolean apply(Game game, Ability source) { + Player controller = game.getPlayer(source.getControllerId()); + if (controller != null) { + Permanent targetCreature = game.getPermanent(this.getTargetPointer().getFirst(game, source)); + if (targetCreature != null) { + int cmc = targetCreature.getConvertedManaCost(); + if (cmc <= 2 || (RevoltCondition.getInstance().apply(game, source) && cmc <= 4)) { + targetCreature.destroy(source.getSourceId(), game, false); + } + } + return true; + } + return false; + } +} diff --git a/Mage.Sets/src/mage/cards/f/FelidarGuardian.java b/Mage.Sets/src/mage/cards/f/FelidarGuardian.java index 39693e481e0..2cb2214b319 100644 --- a/Mage.Sets/src/mage/cards/f/FelidarGuardian.java +++ b/Mage.Sets/src/mage/cards/f/FelidarGuardian.java @@ -47,6 +47,12 @@ import mage.target.common.TargetControlledPermanent; */ public class FelidarGuardian extends CardImpl { + private static final FilterControlledPermanent filter = new FilterControlledPermanent("another target permanent you control"); + + static { + filter.add(new AnotherPredicate()); + } + public FelidarGuardian(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{W}"); @@ -60,8 +66,6 @@ public class FelidarGuardian extends CardImpl { effect.setApplyEffectsAfter(); Ability ability = new EntersBattlefieldTriggeredAbility(effect, true); ability.addEffect(new ReturnToBattlefieldUnderOwnerControlTargetEffect(false, true)); - FilterControlledPermanent filter = new FilterControlledPermanent("another target permanent you control"); - filter.add(new AnotherPredicate()); ability.addTarget(new TargetControlledPermanent(filter)); this.addAbility(ability); diff --git a/Mage.Sets/src/mage/cards/f/FlailingDrake.java b/Mage.Sets/src/mage/cards/f/FlailingDrake.java index 28b4f1ca451..2297de3860a 100644 --- a/Mage.Sets/src/mage/cards/f/FlailingDrake.java +++ b/Mage.Sets/src/mage/cards/f/FlailingDrake.java @@ -38,6 +38,7 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; +import mage.filter.common.FilterCreaturePermanent; /** * @@ -56,7 +57,7 @@ public class FlailingDrake extends CardImpl { // Whenever Flailing Drake blocks or becomes blocked by a creature, that creature gets +1/+1 until end of turn. Effect effect = new BoostTargetEffect(+1, +1, Duration.EndOfTurn); effect.setText("that creature gets +1/+1 until end of turn"); - Ability ability = new BlocksOrBecomesBlockedTriggeredAbility(effect, false); + Ability ability = new BlocksOrBecomesBlockedTriggeredAbility(effect, new FilterCreaturePermanent("a creature"), false, null, true); this.addAbility(ability); } diff --git a/Mage.Sets/src/mage/cards/f/FoundryAssembler.java b/Mage.Sets/src/mage/cards/f/FoundryAssembler.java index f1068de4aea..4e38c4dd810 100644 --- a/Mage.Sets/src/mage/cards/f/FoundryAssembler.java +++ b/Mage.Sets/src/mage/cards/f/FoundryAssembler.java @@ -43,8 +43,7 @@ public class FoundryAssembler extends CardImpl { public FoundryAssembler(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{5}"); - this.subtype.add("Assembly"); - this.subtype.add("Worker"); + this.subtype.add("Assembly-Worker"); this.power = new MageInt(3); this.toughness = new MageInt(3); diff --git a/Mage.Sets/src/mage/cards/f/FrenziedFugue.java b/Mage.Sets/src/mage/cards/f/FrenziedFugue.java index 39bc33a5a3b..27ab625d1fd 100644 --- a/Mage.Sets/src/mage/cards/f/FrenziedFugue.java +++ b/Mage.Sets/src/mage/cards/f/FrenziedFugue.java @@ -28,6 +28,7 @@ package mage.cards.f; import java.util.UUID; + import mage.abilities.Ability; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.effects.Effect; @@ -51,7 +52,6 @@ import mage.target.TargetPermanent; import mage.target.targetpointer.FixedTarget; /** - * * @author LevelX2 */ public class FrenziedFugue extends CardImpl { @@ -98,13 +98,13 @@ class FrenziedFugueTriggeredAbility extends TriggeredAbilityImpl { @Override public boolean checkEventType(GameEvent event, Game game) { - return event.getType().equals(EventType.ENTERS_THE_BATTLEFIELD) || event.getType().equals(EventType.UPKEEP_STEP_PRE); + return event.getType() == EventType.ENTERS_THE_BATTLEFIELD || event.getType() == EventType.UPKEEP_STEP_PRE; } @Override public boolean checkTrigger(GameEvent event, Game game) { boolean result; - if (event.getType().equals(EventType.ENTERS_THE_BATTLEFIELD)) { + if (event.getType()==EventType.ENTERS_THE_BATTLEFIELD) { result = event.getTargetId().equals(this.getSourceId()); } else { result = event.getPlayerId().equals(this.getControllerId()); diff --git a/Mage.Sets/src/mage/cards/g/GearshiftAce.java b/Mage.Sets/src/mage/cards/g/GearshiftAce.java index c6595507cb5..0b2355c60b4 100644 --- a/Mage.Sets/src/mage/cards/g/GearshiftAce.java +++ b/Mage.Sets/src/mage/cards/g/GearshiftAce.java @@ -29,8 +29,6 @@ package mage.cards.g; import java.util.UUID; import mage.MageInt; -import mage.abilities.TriggeredAbilityImpl; -import mage.abilities.effects.Effect; import mage.abilities.effects.common.CrewsVehicleSourceTriggeredAbility; import mage.abilities.effects.common.continuous.GainAbilityTargetEffect; import mage.abilities.keyword.FirstStrikeAbility; @@ -38,10 +36,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.Zone; -import mage.game.Game; -import mage.game.events.GameEvent; -import mage.target.targetpointer.FixedTarget; /** * diff --git a/Mage.Sets/src/mage/cards/g/GemstoneCaverns.java b/Mage.Sets/src/mage/cards/g/GemstoneCaverns.java index 931d1d875d6..9cf89058ee9 100644 --- a/Mage.Sets/src/mage/cards/g/GemstoneCaverns.java +++ b/Mage.Sets/src/mage/cards/g/GemstoneCaverns.java @@ -66,7 +66,7 @@ public class GemstoneCaverns extends CardImpl { // If Gemstone Caverns is in your opening hand and you're not playing first, you may begin the game with Gemstone Caverns on the battlefield with a luck counter on it. If you do, exile a card from your hand. this.addAbility(new GemstoneCavernsAbility()); - // {tap}: Add {C} to your mana pool. If Gemstone Caverns has a luck counter on it, instead add one mana of any color to your mana pool. + // {T}: Add {C} to your mana pool. If Gemstone Caverns has a luck counter on it, instead add one mana of any color to your mana pool. Ability ability = new ConditionalManaAbility(Zone.BATTLEFIELD, new ConditionalManaEffect( new AddManaOfAnyColorEffect(), diff --git a/Mage.Sets/src/mage/cards/g/GhostlyFlicker.java b/Mage.Sets/src/mage/cards/g/GhostlyFlicker.java index 74aead99b53..ee1bc2c82ce 100644 --- a/Mage.Sets/src/mage/cards/g/GhostlyFlicker.java +++ b/Mage.Sets/src/mage/cards/g/GhostlyFlicker.java @@ -27,12 +27,16 @@ */ package mage.cards.g; -import mage.constants.CardType; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import mage.MageObject; import mage.abilities.Ability; import mage.abilities.effects.OneShotEffect; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.common.FilterControlledPermanent; @@ -40,10 +44,9 @@ import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.CardTypePredicate; import mage.game.Game; import mage.game.permanent.Permanent; +import mage.players.Player; import mage.target.common.TargetControlledPermanent; -import java.util.UUID; - /** * @author noxx */ @@ -59,8 +62,7 @@ public class GhostlyFlicker extends CardImpl { } public GhostlyFlicker(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{2}{U}"); - + super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{2}{U}"); // Exile two target artifacts, creatures, and/or lands you control, then return those cards to the battlefield under your control. this.getSpellAbility().addTarget(new TargetControlledPermanent(2, 2, filter, false)); @@ -95,20 +97,28 @@ class GhostlyFlickerEffect extends OneShotEffect { @Override public boolean apply(Game game, Ability source) { - UUID exileId = source.getSourceId(); - for (UUID permanentId : targetPointer.getTargets(game, source)) { - Permanent target = game.getPermanent(permanentId); - if (target != null) { - target.moveToExile(exileId, "Ghostly Flicker", source.getSourceId(), game); - Card card = game.getCard(target.getId()); - if (card != null) { - Zone currentZone = game.getState().getZone(card.getId()); - card.putOntoBattlefield(game, currentZone, source.getSourceId(), source.getControllerId()); + Player controller = game.getPlayer(source.getControllerId()); + MageObject sourceObject = source.getSourceObject(game); + if (controller != null && sourceObject != null) { + Set toExile = new HashSet<>(); + for (UUID permanentId : targetPointer.getTargets(game, source)) { + Permanent target = game.getPermanent(permanentId); + if (target != null) { + toExile.add(target); } } + controller.moveCards(toExile, Zone.EXILED, source, game); + game.applyEffects(); + Set toBattlefield = new HashSet<>(); + for (Card card : toExile) { + Zone currentZone = game.getState().getZone(card.getId()); + if (!Zone.BATTLEFIELD.equals(currentZone) && Zone.isPublicZone(currentZone)) { + toBattlefield.add(game.getCard(card.getId())); + } + } + controller.moveCards(toBattlefield, Zone.BATTLEFIELD, source, game); + return true; } - - return true; + return false; } } - diff --git a/Mage.Sets/src/mage/cards/g/Ghoulraiser.java b/Mage.Sets/src/mage/cards/g/Ghoulraiser.java index 29a348e05b9..c1c4a36b084 100644 --- a/Mage.Sets/src/mage/cards/g/Ghoulraiser.java +++ b/Mage.Sets/src/mage/cards/g/Ghoulraiser.java @@ -27,7 +27,6 @@ */ package mage.cards.g; -import java.util.Random; import java.util.UUID; import mage.constants.CardType; import mage.constants.Outcome; diff --git a/Mage.Sets/src/mage/cards/g/GoblinChieftain.java b/Mage.Sets/src/mage/cards/g/GoblinChieftain.java index a56507d4023..2b15368cdff 100644 --- a/Mage.Sets/src/mage/cards/g/GoblinChieftain.java +++ b/Mage.Sets/src/mage/cards/g/GoblinChieftain.java @@ -64,6 +64,7 @@ public class GoblinChieftain extends CardImpl { Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, effect); effect = new GainAbilityControlledEffect(HasteAbility.getInstance(), Duration.WhileOnBattlefield, StaticFilters.FILTER_PERMANENT_CREATURE_GOBLINS, true); effect.setText("and have haste"); + ability.addEffect(effect); this.addAbility(ability); } diff --git a/Mage.Sets/src/mage/cards/g/GoldnightCommander.java b/Mage.Sets/src/mage/cards/g/GoldnightCommander.java index ab2e5db8c50..d58511e3920 100644 --- a/Mage.Sets/src/mage/cards/g/GoldnightCommander.java +++ b/Mage.Sets/src/mage/cards/g/GoldnightCommander.java @@ -28,15 +28,15 @@ package mage.cards.g; import java.util.UUID; -import mage.constants.CardType; import mage.MageInt; +import mage.abilities.common.EntersBattlefieldAllTriggeredAbility; import mage.abilities.effects.common.continuous.BoostControlledEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.CardType; import mage.constants.Duration; -import mage.abilities.common.EntersBattlefieldAllTriggeredAbility; import mage.constants.Zone; -import mage.filter.common.FilterCreaturePermanent; +import mage.filter.common.FilterControlledCreaturePermanent; import mage.filter.predicate.permanent.AnotherPredicate; /** @@ -44,7 +44,7 @@ import mage.filter.predicate.permanent.AnotherPredicate; */ public class GoldnightCommander extends CardImpl { - private static FilterCreaturePermanent filter = new FilterCreaturePermanent("another creature"); + private final static FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("another creature"); static { filter.add(new AnotherPredicate()); diff --git a/Mage.Sets/src/mage/cards/g/GreenSunsZenith.java b/Mage.Sets/src/mage/cards/g/GreenSunsZenith.java index 50e66653ac5..2c98d38df55 100644 --- a/Mage.Sets/src/mage/cards/g/GreenSunsZenith.java +++ b/Mage.Sets/src/mage/cards/g/GreenSunsZenith.java @@ -29,36 +29,34 @@ package mage.cards.g; import java.util.UUID; import mage.ObjectColor; -import mage.abilities.Ability; -import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.ShuffleSpellEffect; -import mage.cards.Card; +import mage.abilities.effects.common.search.SearchLibraryWithLessCMCPutInPlayEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Outcome; -import mage.constants.Zone; -import mage.filter.Filter; import mage.filter.FilterCard; import mage.filter.predicate.mageobject.CardTypePredicate; import mage.filter.predicate.mageobject.ColorPredicate; -import mage.filter.predicate.mageobject.ConvertedManaCostPredicate; -import mage.game.Game; -import mage.players.Player; -import mage.target.common.TargetCardInLibrary; /** * @author Loki */ public class GreenSunsZenith extends CardImpl { - public GreenSunsZenith(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{X}{G}"); + private static final FilterCard filter = new FilterCard("green creature"); + + static { + filter.add(new ColorPredicate(ObjectColor.GREEN)); + filter.add(new CardTypePredicate(CardType.CREATURE)); + } + + public GreenSunsZenith(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{X}{G}"); + + // Search your library for a green creature card with converted mana cost X or less, put it onto the battlefield, then shuffle your library. + this.getSpellAbility().addEffect(new SearchLibraryWithLessCMCPutInPlayEffect(filter)); - // Search your library for a green creature card with converted mana cost X or less, - // put it onto the battlefield, then shuffle your library. // Shuffle Green Sun's Zenith into its owner's library. - this.getSpellAbility().addEffect(new GreenSunsZenithSearchEffect()); this.getSpellAbility().addEffect(ShuffleSpellEffect.getInstance()); } @@ -72,48 +70,3 @@ public class GreenSunsZenith extends CardImpl { } } - -class GreenSunsZenithSearchEffect extends OneShotEffect { - - GreenSunsZenithSearchEffect() { - super(Outcome.PutCreatureInPlay); - staticText = "Search your library for a green creature card with converted mana cost X or less, put it onto the battlefield, then shuffle your library"; - } - - GreenSunsZenithSearchEffect(final GreenSunsZenithSearchEffect effect) { - super(effect); - } - - @Override - public boolean apply(Game game, Ability source) { - Player controller = game.getPlayer(source.getControllerId()); - if (controller == null) { - return false; - } - //Set the mana cost one higher to 'emulate' a less than or equal to comparison. - int xValue = source.getManaCostsToPay().getX() + 1; - FilterCard filter = new FilterCard("green creature card with converted mana cost " + xValue + " or less"); - filter.add(new ColorPredicate(ObjectColor.GREEN)); - filter.add(new CardTypePredicate(CardType.CREATURE)); - filter.add(new ConvertedManaCostPredicate(Filter.ComparisonType.LessThan, xValue)); - TargetCardInLibrary target = new TargetCardInLibrary(filter); - if (controller.searchLibrary(target, game)) { - if (target.getTargets().size() > 0) { - Card card = controller.getLibrary().getCard(target.getFirstTarget(), game); - if (card != null) { - controller.moveCards(card, Zone.BATTLEFIELD, source, game); - } - } - controller.shuffleLibrary(source, game); - return true; - } - controller.shuffleLibrary(source, game); - return false; - } - - @Override - public GreenSunsZenithSearchEffect copy() { - return new GreenSunsZenithSearchEffect(this); - } - -} diff --git a/Mage.Sets/src/mage/cards/g/GremlinInfestation.java b/Mage.Sets/src/mage/cards/g/GremlinInfestation.java index 499fd8a1108..6aae9b9f781 100644 --- a/Mage.Sets/src/mage/cards/g/GremlinInfestation.java +++ b/Mage.Sets/src/mage/cards/g/GremlinInfestation.java @@ -28,7 +28,6 @@ package mage.cards.g; import java.util.UUID; -import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.BeginningOfEndStepTriggeredAbility; import mage.abilities.common.DiesAttachedTriggeredAbility; @@ -42,7 +41,7 @@ import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.TargetController; -import mage.game.permanent.token.Token; +import mage.game.permanent.token.GremlinToken; import mage.target.TargetPermanent; import mage.target.common.TargetArtifactPermanent; @@ -70,7 +69,7 @@ public class GremlinInfestation extends CardImpl { this.addAbility(new BeginningOfEndStepTriggeredAbility(new DamageAttachedControllerEffect(2), TargetController.YOU, false)); // When enchanted artifact is put into a graveyard, create a 2/2 red Gremlin creature token. - this.addAbility(new DiesAttachedTriggeredAbility(new CreateTokenEffect(new GremlinInfestationToken()), "enchanted artifact", false, false)); + this.addAbility(new DiesAttachedTriggeredAbility(new CreateTokenEffect(new GremlinToken()), "enchanted artifact", false, false)); } public GremlinInfestation(final GremlinInfestation card) { @@ -82,17 +81,3 @@ public class GremlinInfestation extends CardImpl { return new GremlinInfestation(this); } } - -class GremlinInfestationToken extends Token { - - GremlinInfestationToken() { - super("Gremlin", "2/2 red Gremlin creature token"); - this.setOriginalExpansionSetCode("AER"); - cardType.add(CardType.CREATURE); - color.setRed(true); - subtype.add("Gremlin"); - power = new MageInt(2); - toughness = new MageInt(2); - - } -} diff --git a/Mage.Sets/src/mage/cards/g/GriffinProtector.java b/Mage.Sets/src/mage/cards/g/GriffinProtector.java index 08db606a29f..d743791c1ce 100644 --- a/Mage.Sets/src/mage/cards/g/GriffinProtector.java +++ b/Mage.Sets/src/mage/cards/g/GriffinProtector.java @@ -28,16 +28,16 @@ package mage.cards.g; import java.util.UUID; -import mage.constants.CardType; import mage.MageInt; import mage.abilities.common.EntersBattlefieldAllTriggeredAbility; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Zone; -import mage.filter.common.FilterCreaturePermanent; +import mage.filter.common.FilterControlledCreaturePermanent; import mage.filter.predicate.permanent.AnotherPredicate; /** @@ -46,7 +46,7 @@ import mage.filter.predicate.permanent.AnotherPredicate; */ public class GriffinProtector extends CardImpl { - private static FilterCreaturePermanent filter = new FilterCreaturePermanent("another creature"); + private final static FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("another creature"); static { filter.add(new AnotherPredicate()); diff --git a/Mage.Sets/src/mage/cards/g/GrimoireThief.java b/Mage.Sets/src/mage/cards/g/GrimoireThief.java index 02eae14e35a..2a52958e34b 100644 --- a/Mage.Sets/src/mage/cards/g/GrimoireThief.java +++ b/Mage.Sets/src/mage/cards/g/GrimoireThief.java @@ -43,7 +43,6 @@ import mage.abilities.effects.AsThoughEffectImpl; import mage.abilities.effects.OneShotEffect; import mage.cards.Card; import mage.cards.CardImpl; -import mage.cards.CardSetInfo; import mage.cards.Cards; import mage.cards.CardsImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/g/GruulCharm.java b/Mage.Sets/src/mage/cards/g/GruulCharm.java index 1f2d0095e44..c174bd326f6 100644 --- a/Mage.Sets/src/mage/cards/g/GruulCharm.java +++ b/Mage.Sets/src/mage/cards/g/GruulCharm.java @@ -29,7 +29,6 @@ package mage.cards.g; import java.util.UUID; -import mage.constants.CardType; import mage.constants.*; import mage.abilities.Mode; import mage.abilities.effects.common.combat.CantBlockAllEffect; diff --git a/Mage.Sets/src/mage/cards/h/HanweirTheWrithingTownship.java b/Mage.Sets/src/mage/cards/h/HanweirTheWrithingTownship.java index c48d2d2be49..744467610c8 100644 --- a/Mage.Sets/src/mage/cards/h/HanweirTheWrithingTownship.java +++ b/Mage.Sets/src/mage/cards/h/HanweirTheWrithingTownship.java @@ -35,7 +35,6 @@ import mage.abilities.keyword.TrampleAbility; import mage.cards.CardSetInfo; import mage.cards.MeldCard; import mage.constants.CardType; -import mage.constants.Rarity; import mage.game.permanent.token.EldraziHorrorToken; import java.util.UUID; diff --git a/Mage.Sets/src/mage/cards/h/HarshJudgment.java b/Mage.Sets/src/mage/cards/h/HarshJudgment.java index e4bd384823e..e0937bcaeed 100755 --- a/Mage.Sets/src/mage/cards/h/HarshJudgment.java +++ b/Mage.Sets/src/mage/cards/h/HarshJudgment.java @@ -33,9 +33,7 @@ import mage.ObjectColor; import mage.abilities.Ability; import mage.abilities.common.AsEntersBattlefieldAbility; import mage.abilities.common.SimpleStaticAbility; -import mage.abilities.effects.ContinuousEffect; import mage.abilities.effects.RedirectionEffect; -import mage.abilities.effects.ReplacementEffectImpl; import mage.abilities.effects.common.ChooseColorEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; @@ -43,10 +41,8 @@ import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.Zone; -import mage.filter.FilterInPlay; import mage.filter.common.FilterInstantOrSorceryCard; import mage.game.Game; -import mage.game.events.DamagePlayerEvent; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; import mage.game.stack.Spell; diff --git a/Mage.Sets/src/mage/cards/h/HauntedFengraf.java b/Mage.Sets/src/mage/cards/h/HauntedFengraf.java index e6c09da2c4c..d6213b12e57 100644 --- a/Mage.Sets/src/mage/cards/h/HauntedFengraf.java +++ b/Mage.Sets/src/mage/cards/h/HauntedFengraf.java @@ -27,7 +27,6 @@ */ package mage.cards.h; -import java.util.Random; import java.util.UUID; import mage.constants.CardType; diff --git a/Mage.Sets/src/mage/cards/h/HealerOfThePride.java b/Mage.Sets/src/mage/cards/h/HealerOfThePride.java index b19844cfd54..eed2676f4f2 100644 --- a/Mage.Sets/src/mage/cards/h/HealerOfThePride.java +++ b/Mage.Sets/src/mage/cards/h/HealerOfThePride.java @@ -28,14 +28,14 @@ package mage.cards.h; import java.util.UUID; -import mage.constants.CardType; import mage.MageInt; import mage.abilities.common.EntersBattlefieldAllTriggeredAbility; import mage.abilities.effects.common.GainLifeEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.CardType; import mage.constants.Zone; -import mage.filter.common.FilterCreaturePermanent; +import mage.filter.common.FilterControlledCreaturePermanent; import mage.filter.predicate.permanent.AnotherPredicate; /** @@ -44,7 +44,7 @@ import mage.filter.predicate.permanent.AnotherPredicate; */ public class HealerOfThePride extends CardImpl { - private static FilterCreaturePermanent filter = new FilterCreaturePermanent("another creature"); + private final static FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("another creature"); static { filter.add(new AnotherPredicate()); diff --git a/Mage.Sets/src/mage/cards/h/HiddenHerbalists.java b/Mage.Sets/src/mage/cards/h/HiddenHerbalists.java index 616480f3545..b3aadebfaef 100644 --- a/Mage.Sets/src/mage/cards/h/HiddenHerbalists.java +++ b/Mage.Sets/src/mage/cards/h/HiddenHerbalists.java @@ -32,7 +32,7 @@ import mage.MageInt; import mage.Mana; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.RevoltCondition; -import mage.abilities.decorator.ConditionalOneShotEffect; +import mage.abilities.decorator.ConditionalTriggeredAbility; import mage.abilities.effects.common.BasicManaEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; @@ -53,12 +53,12 @@ public class HiddenHerbalists extends CardImpl { this.power = new MageInt(2); this.toughness = new MageInt(2); - // Revolt &mdash When Hidden Herbalists enters the battlefield, if a permanent you controlled left the battlefield this turn add {G}{G} to your mana pool; + // Revolt &mdash When Hidden Herbalists enters the battlefield, if a permanent you controlled left the battlefield this turn, add {G}{G} to your mana pool; this.addAbility( - new EntersBattlefieldTriggeredAbility( - new ConditionalOneShotEffect(new BasicManaEffect(Mana.GreenMana(2)), RevoltCondition.getInstance()), - false, - "Revolt — "), + new ConditionalTriggeredAbility(new EntersBattlefieldTriggeredAbility( + new BasicManaEffect(Mana.GreenMana(2)), false), RevoltCondition.getInstance(), + "Revolt — When {this} enters the battlefield, if a permanent you controlled left" + + " the battlefield this turn, add {G}{G} to your mana pool."), new RevoltWatcher() ); } diff --git a/Mage.Sets/src/mage/cards/i/Invisibility.java b/Mage.Sets/src/mage/cards/i/Invisibility.java index 5aac55003e2..02e929a53d9 100644 --- a/Mage.Sets/src/mage/cards/i/Invisibility.java +++ b/Mage.Sets/src/mage/cards/i/Invisibility.java @@ -30,7 +30,6 @@ package mage.cards.i; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; -import mage.abilities.effects.RestrictionEffect; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.combat.CantBeBlockedByCreaturesAttachedEffect; import mage.abilities.keyword.EnchantAbility; @@ -40,8 +39,6 @@ import mage.constants.*; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.SubtypePredicate; -import mage.game.Game; -import mage.game.permanent.Permanent; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; diff --git a/Mage.Sets/src/mage/cards/i/IvoryCup.java b/Mage.Sets/src/mage/cards/i/IvoryCup.java index 079672c67f7..8c512a9724e 100644 --- a/Mage.Sets/src/mage/cards/i/IvoryCup.java +++ b/Mage.Sets/src/mage/cards/i/IvoryCup.java @@ -28,7 +28,7 @@ package mage.cards.i; import java.util.UUID; -import mage.ObjectColor; + import mage.abilities.TriggeredAbilityImpl; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.effects.common.DoIfCostPaid; diff --git a/Mage.Sets/src/mage/cards/j/JabbaTheHutt.java b/Mage.Sets/src/mage/cards/j/JabbaTheHutt.java index eefd733e328..bd38d7661ea 100644 --- a/Mage.Sets/src/mage/cards/j/JabbaTheHutt.java +++ b/Mage.Sets/src/mage/cards/j/JabbaTheHutt.java @@ -42,7 +42,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; -import mage.constants.TimingRule; import mage.constants.Zone; import mage.counters.CounterType; import mage.filter.common.FilterOpponentsCreaturePermanent; diff --git a/Mage.Sets/src/mage/cards/j/JestersScepter.java b/Mage.Sets/src/mage/cards/j/JestersScepter.java index 35412800277..cdf0ba8a8ae 100644 --- a/Mage.Sets/src/mage/cards/j/JestersScepter.java +++ b/Mage.Sets/src/mage/cards/j/JestersScepter.java @@ -42,7 +42,6 @@ import mage.abilities.effects.AsThoughEffectImpl; import mage.abilities.effects.OneShotEffect; import mage.cards.Card; import mage.cards.CardImpl; -import mage.cards.CardSetInfo; import mage.cards.Cards; import mage.cards.CardSetInfo; import mage.cards.SplitCard; diff --git a/Mage.Sets/src/mage/cards/k/KrarksThumb.java b/Mage.Sets/src/mage/cards/k/KrarksThumb.java index 9543b349c94..eac2364d634 100644 --- a/Mage.Sets/src/mage/cards/k/KrarksThumb.java +++ b/Mage.Sets/src/mage/cards/k/KrarksThumb.java @@ -27,7 +27,6 @@ */ package mage.cards.k; -import java.util.Random; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; diff --git a/Mage.Sets/src/mage/cards/k/KrosanWayfarer.java b/Mage.Sets/src/mage/cards/k/KrosanWayfarer.java index 514b76319ba..0faba446263 100644 --- a/Mage.Sets/src/mage/cards/k/KrosanWayfarer.java +++ b/Mage.Sets/src/mage/cards/k/KrosanWayfarer.java @@ -29,7 +29,6 @@ package mage.cards.k; import java.util.UUID; import mage.MageInt; -import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.SacrificeSourceCost; import mage.abilities.effects.common.PutLandFromHandOntoBattlefieldEffect; diff --git a/Mage.Sets/src/mage/cards/l/LazavDimirMastermind.java b/Mage.Sets/src/mage/cards/l/LazavDimirMastermind.java index 9cb8e216ae5..e3b356c8170 100644 --- a/Mage.Sets/src/mage/cards/l/LazavDimirMastermind.java +++ b/Mage.Sets/src/mage/cards/l/LazavDimirMastermind.java @@ -28,7 +28,6 @@ package mage.cards.l; import java.util.UUID; - import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.PutCardIntoGraveFromAnywhereAllTriggeredAbility; @@ -56,7 +55,7 @@ import mage.target.targetpointer.FixedTarget; public class LazavDimirMastermind extends CardImpl { public LazavDimirMastermind(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{U}{U}{B}{B}"); + super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{U}{U}{B}{B}"); this.supertype.add("Legendary"); this.subtype.add("Shapeshifter"); @@ -85,7 +84,6 @@ public class LazavDimirMastermind extends CardImpl { class LazavDimirEffect extends ContinuousEffectImpl { - protected UUID IdOfCopiedCard; protected Card cardToCopy; public LazavDimirEffect() { @@ -96,7 +94,6 @@ class LazavDimirEffect extends ContinuousEffectImpl { public LazavDimirEffect(final LazavDimirEffect effect) { super(effect); this.cardToCopy = effect.cardToCopy; - this.IdOfCopiedCard = effect.IdOfCopiedCard; } @Override @@ -105,17 +102,23 @@ class LazavDimirEffect extends ContinuousEffectImpl { } @Override - public boolean apply(Game game, Ability source) { - Card card = game.getCard(((FixedTarget)getTargetPointer()).getTarget()); - Permanent permanent = game.getPermanent(source.getSourceId()); - if (card == null || permanent == null) { - discard(); - return false; - } - if (IdOfCopiedCard == null || !IdOfCopiedCard.equals(card.getId())) { - IdOfCopiedCard = card.getId(); + public void init(Ability source, Game game) { + super.init(source, game); + Card card = game.getCard(((FixedTarget) getTargetPointer()).getTarget()); + if (card != null) { cardToCopy = card.copy(); cardToCopy.assignNewId(); + } else { + discard(); + } + } + + @Override + public boolean apply(Game game, Ability source) { + Permanent permanent = game.getPermanent(source.getSourceId()); + if (permanent == null) { + discard(); + return true; } permanent.getPower().setValue(cardToCopy.getPower().getValue()); permanent.getToughness().setValue(cardToCopy.getToughness().getValue()); diff --git a/Mage.Sets/src/mage/cards/l/Legerdemain.java b/Mage.Sets/src/mage/cards/l/Legerdemain.java index b33a93d273d..fa5093df707 100644 --- a/Mage.Sets/src/mage/cards/l/Legerdemain.java +++ b/Mage.Sets/src/mage/cards/l/Legerdemain.java @@ -29,7 +29,6 @@ package mage.cards.l; import java.util.UUID; import mage.MageItem; -import mage.abilities.Ability; import mage.abilities.effects.common.continuous.ExchangeControlTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/l/LiberatingCombustion.java b/Mage.Sets/src/mage/cards/l/LiberatingCombustion.java index 1d18369c1f3..5e277de6085 100644 --- a/Mage.Sets/src/mage/cards/l/LiberatingCombustion.java +++ b/Mage.Sets/src/mage/cards/l/LiberatingCombustion.java @@ -28,23 +28,13 @@ package mage.cards.l; import java.util.UUID; -import mage.MageObject; -import mage.abilities.Ability; -import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.DamageTargetEffect; -import mage.cards.Card; +import mage.abilities.effects.common.search.SearchLibraryGraveyardPutInHandEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.cards.Cards; -import mage.cards.CardsImpl; import mage.constants.CardType; -import mage.constants.Outcome; -import mage.constants.Zone; import mage.filter.FilterCard; import mage.filter.predicate.mageobject.NamePredicate; -import mage.game.Game; -import mage.players.Player; -import mage.target.TargetCard; import mage.target.common.TargetCreaturePermanent; /** @@ -53,14 +43,21 @@ import mage.target.common.TargetCreaturePermanent; */ public class LiberatingCombustion extends CardImpl { + private final static FilterCard filter = new FilterCard("Chandra, Pyrogenius"); + + static { + filter.add(new NamePredicate("Chandra, Pyrogenius")); + } + public LiberatingCombustion(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{4}{R}"); + super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{4}{R}"); // Liberating Combustion deals 6 damage to target creature. this.getSpellAbility().addEffect(new DamageTargetEffect(6)); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); + // You may search your library and/or graveyard for a card named Chandra, Pyrogenius, reveal it, and put it into your hand. If you search your library this way, shuffle it. - this.getSpellAbility().addEffect(new LiberatingCombustionEffect()); + this.getSpellAbility().addEffect(new SearchLibraryGraveyardPutInHandEffect(filter)); } public LiberatingCombustion(final LiberatingCombustion card) { @@ -72,51 +69,3 @@ public class LiberatingCombustion extends CardImpl { return new LiberatingCombustion(this); } } - -class LiberatingCombustionEffect extends OneShotEffect { - - public LiberatingCombustionEffect() { - super(Outcome.Benefit); - staticText = "You may search your library and/or graveyard for a card named Chandra, Pyrogenius, reveal it, and put it into your hand. If you search your library this way, shuffle it"; - } - - public LiberatingCombustionEffect(final LiberatingCombustionEffect effect) { - super(effect); - } - - @Override - public LiberatingCombustionEffect copy() { - return new LiberatingCombustionEffect(this); - } - - @Override - public boolean apply(Game game, Ability source) { - Player controller = game.getPlayer(source.getControllerId()); - MageObject sourceObject = source.getSourceObject(game); - if (controller != null && sourceObject != null && controller.chooseUse(outcome, "Search your library and/or graveyard for a card named Chandra, Pyrogenius?", source, game)) { - //Search your library and graveyard - Cards allCards = new CardsImpl(); - boolean librarySearched = false; - if (controller.chooseUse(outcome, "Search also your library?", source, game)) { - librarySearched = true; - allCards.addAll(controller.getLibrary().getCardList()); - } - allCards.addAll(controller.getGraveyard()); - FilterCard filter = new FilterCard("a card named Chandra, Pyrogenius"); - filter.add(new NamePredicate("Chandra, Pyrogenius")); - TargetCard target = new TargetCard(0, 1, Zone.ALL, new FilterCard()); - if (controller.choose(outcome, allCards, target, game)) { - Card cardFound = game.getCard(target.getFirstTarget()); - if (cardFound != null) { - controller.revealCards(sourceObject.getIdName(), new CardsImpl(cardFound), game); - controller.moveCards(cardFound, Zone.HAND, source, game); - } - } - if (librarySearched) { - controller.shuffleLibrary(source, game); - } - return true; - } - return false; - } -} diff --git a/Mage.Sets/src/mage/cards/l/LifecraftCavalry.java b/Mage.Sets/src/mage/cards/l/LifecraftCavalry.java index abd8b5d9823..b3962f78ec5 100644 --- a/Mage.Sets/src/mage/cards/l/LifecraftCavalry.java +++ b/Mage.Sets/src/mage/cards/l/LifecraftCavalry.java @@ -29,10 +29,8 @@ package mage.cards.l; import java.util.UUID; import mage.MageInt; -import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldAbility; import mage.abilities.condition.common.RevoltCondition; -import mage.abilities.decorator.ConditionalOneShotEffect; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.abilities.keyword.TrampleAbility; import mage.cards.CardImpl; diff --git a/Mage.Sets/src/mage/cards/l/LiquidFire.java b/Mage.Sets/src/mage/cards/l/LiquidFire.java index 22d0c4961c9..c58cb222da0 100644 --- a/Mage.Sets/src/mage/cards/l/LiquidFire.java +++ b/Mage.Sets/src/mage/cards/l/LiquidFire.java @@ -30,7 +30,6 @@ package mage.cards.l; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.costs.Cost; -import mage.abilities.costs.CostImpl; import mage.abilities.costs.VariableCostImpl; import mage.abilities.dynamicvalue.DynamicValue; import mage.abilities.dynamicvalue.common.GetXValue; diff --git a/Mage.Sets/src/mage/cards/l/LivingTerrain.java b/Mage.Sets/src/mage/cards/l/LivingTerrain.java index 4cf5431f838..3500b36697b 100644 --- a/Mage.Sets/src/mage/cards/l/LivingTerrain.java +++ b/Mage.Sets/src/mage/cards/l/LivingTerrain.java @@ -38,7 +38,6 @@ import mage.abilities.effects.common.continuous.BecomesCreatureAttachedEffect; import mage.abilities.keyword.EnchantAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.filter.common.FilterLandPermanent; import mage.game.permanent.token.Token; import mage.target.TargetPermanent; import mage.target.common.TargetLandPermanent; diff --git a/Mage.Sets/src/mage/cards/l/LongRoadHome.java b/Mage.Sets/src/mage/cards/l/LongRoadHome.java index 5f39b599ece..a3632cf939c 100644 --- a/Mage.Sets/src/mage/cards/l/LongRoadHome.java +++ b/Mage.Sets/src/mage/cards/l/LongRoadHome.java @@ -36,7 +36,6 @@ import mage.abilities.effects.ReplacementEffectImpl; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.cards.CardSetInfo; import mage.cards.MeldCard; import mage.constants.CardType; import mage.constants.Duration; diff --git a/Mage.Sets/src/mage/cards/l/LullmageMentor.java b/Mage.Sets/src/mage/cards/l/LullmageMentor.java index 3622dfa66e2..795085f1d16 100644 --- a/Mage.Sets/src/mage/cards/l/LullmageMentor.java +++ b/Mage.Sets/src/mage/cards/l/LullmageMentor.java @@ -27,48 +27,41 @@ */ package mage.cards.l; -import java.util.HashMap; -import java.util.Map; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; -import mage.abilities.TriggeredAbilityImpl; import mage.abilities.common.SimpleActivatedAbility; +import mage.abilities.common.SpellCounteredControllerTriggeredAbility; import mage.abilities.costs.common.TapTargetCost; import mage.abilities.effects.common.CounterTargetEffect; import mage.abilities.effects.common.CreateTokenEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.WatcherScope; import mage.constants.Zone; import mage.filter.common.FilterControlledCreaturePermanent; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.SubtypePredicate; import mage.filter.predicate.permanent.TappedPredicate; -import mage.game.Game; -import mage.game.events.GameEvent; -import mage.game.events.GameEvent.EventType; import mage.game.permanent.token.Token; -import mage.game.stack.StackObject; -import mage.target.Target; import mage.target.TargetSpell; import mage.target.common.TargetControlledCreaturePermanent; -import mage.watchers.Watcher; /** * * @author LevelX2 */ public class LullmageMentor extends CardImpl { + private static final FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("untapped Merfolk you control"); static { filter.add(new SubtypePredicate("Merfolk")); filter.add(Predicates.not(new TappedPredicate())); } + public LullmageMentor(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{U}{U}"); + super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{U}{U}"); this.subtype.add("Merfolk"); this.subtype.add("Wizard"); @@ -76,7 +69,8 @@ public class LullmageMentor extends CardImpl { this.toughness = new MageInt(2); // Whenever a spell or ability you control counters a spell, you may create a 1/1 blue Merfolk creature token. - this.addAbility(new LullmageMentorTriggeredAbility(), new CastedSpellsWithSpellTarget()); + this.addAbility(new SpellCounteredControllerTriggeredAbility(new CreateTokenEffect(new MerfolkToken()), true)); + // Tap seven untapped Merfolk you control: Counter target spell. Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new CounterTargetEffect(), new TapTargetCost(new TargetControlledCreaturePermanent(7, 7, filter, true))); ability.addTarget(new TargetSpell()); @@ -94,39 +88,6 @@ public class LullmageMentor extends CardImpl { } } -class LullmageMentorTriggeredAbility extends TriggeredAbilityImpl { - - public LullmageMentorTriggeredAbility() { - super(Zone.BATTLEFIELD, new CreateTokenEffect(new MerfolkToken()), false); - } - - public LullmageMentorTriggeredAbility(final LullmageMentorTriggeredAbility ability) { - super(ability); - } - - @Override - public LullmageMentorTriggeredAbility copy() { - return new LullmageMentorTriggeredAbility(this); - } - - @Override - public boolean checkEventType(GameEvent event, Game game) { - return event.getType() == EventType.COUNTERED; - } - - @Override - public boolean checkTrigger(GameEvent event, Game game) { - CastedSpellsWithSpellTarget watcher = (CastedSpellsWithSpellTarget) game.getState().getWatchers().get("CastedSpellsWithSpellTarget"); - UUID controllerIdCounter = watcher.getControllerSpell(event.getSourceId(), event.getTargetId()); - return controllerIdCounter != null && controllerIdCounter.equals(controllerId); - } - - @Override - public String getRule() { - return new StringBuilder("Whenever a spell or ability you control counters a spell, ").append(super.getRule()).toString(); - } -} - class MerfolkToken extends Token { public MerfolkToken() { @@ -138,59 +99,3 @@ class MerfolkToken extends Token { toughness = new MageInt(1); } } - -class CastedSpellsWithSpellTarget extends Watcher { - - private final Map casted = new HashMap<>(); - - public CastedSpellsWithSpellTarget() { - super("CastedSpellsWithSpellTarget", WatcherScope.GAME); - } - - public CastedSpellsWithSpellTarget(final CastedSpellsWithSpellTarget watcher) { - super(watcher); - for (Map.Entry entry: watcher.casted.entrySet()) { - casted.put(entry.getKey(), entry.getValue()); - } - } - - @Override - public void watch(GameEvent event, Game game) { - if (event.getType() == GameEvent.EventType.SPELL_CAST || event.getType() == GameEvent.EventType.ACTIVATED_ABILITY) { - StackObject stackObject = game.getStack().getStackObject(event.getTargetId()); - if (stackObject == null) { - stackObject = (StackObject) game.getLastKnownInformation(event.getTargetId(), Zone.STACK); - } - if (stackObject != null && stackObject.getStackAbility() != null) { - for (Target target: stackObject.getStackAbility().getTargets()) { - if (target instanceof TargetSpell && target.getFirstTarget() != null) { - casted.put(getKey(target.getFirstTarget(), stackObject.getSourceId()), stackObject.getControllerId()); - } - } - } - } - } - - private String getKey(UUID targetId, UUID sourceId) { - return new StringBuilder(targetId.toString()).append("_").append(sourceId.toString()).toString(); - } - - public UUID getControllerSpell(UUID sourceId, UUID counteredSpell) { - if (sourceId != null && counteredSpell != null){ - return casted.get(getKey(counteredSpell, sourceId)); - } - return null; - } - - @Override - public void reset() { - super.reset(); - casted.clear(); - } - - @Override - public CastedSpellsWithSpellTarget copy() { - return new CastedSpellsWithSpellTarget(this); - } - -} diff --git a/Mage.Sets/src/mage/cards/l/LurkingInformant.java b/Mage.Sets/src/mage/cards/l/LurkingInformant.java index 3b979295172..d112253f106 100644 --- a/Mage.Sets/src/mage/cards/l/LurkingInformant.java +++ b/Mage.Sets/src/mage/cards/l/LurkingInformant.java @@ -33,18 +33,11 @@ import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.GenericManaCost; -import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.LookLibraryTopCardTargetPlayerEffect; -import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.cards.Cards; -import mage.cards.CardsImpl; import mage.constants.CardType; -import mage.constants.Outcome; import mage.constants.Zone; -import mage.game.Game; -import mage.players.Player; import mage.target.TargetPlayer; /** diff --git a/Mage.Sets/src/mage/cards/m/MaulfistRevolutionary.java b/Mage.Sets/src/mage/cards/m/MaulfistRevolutionary.java index 297648cca55..499006c4b23 100644 --- a/Mage.Sets/src/mage/cards/m/MaulfistRevolutionary.java +++ b/Mage.Sets/src/mage/cards/m/MaulfistRevolutionary.java @@ -39,6 +39,8 @@ import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.counters.Counter; +import mage.counters.CounterType; +import mage.counters.Counters; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; @@ -95,14 +97,31 @@ class MaulfistRevolutionaryEffect extends OneShotEffect { if (controller != null) { Player player = game.getPlayer(getTargetPointer().getFirst(game, source)); if (player != null) { - for (Counter counter : player.getCounters().values()) { - counter.increase(); + Counters counters = player.getCounters().copy(); + for (Counter counter : counters.values()) { + CounterType counterType = CounterType.findByName(counter.getName()); + Counter counterToAdd; + if (counterType != null) { + counterToAdd = counterType.createInstance(); + } else { + counterToAdd = new Counter(counter.getName()); + } + player.addCounters(counterToAdd, game); } + return true; } Permanent permanent = game.getPermanent(getTargetPointer().getFirst(game, source)); if (permanent != null) { - for (Counter counter : permanent.getCounters(game).values()) { - counter.increase(); + Counters counters = permanent.getCounters(game).copy(); + for (Counter counter : counters.values()) { + CounterType counterType = CounterType.findByName(counter.getName()); + Counter counterToAdd; + if (counterType != null) { + counterToAdd = counterType.createInstance(); + } else { + counterToAdd = new Counter(counter.getName()); + } + permanent.addCounters(counterToAdd, source, game); } } return true; diff --git a/Mage.Sets/src/mage/cards/m/MetallicMimic.java b/Mage.Sets/src/mage/cards/m/MetallicMimic.java index db9227580fb..b837e2e3b46 100644 --- a/Mage.Sets/src/mage/cards/m/MetallicMimic.java +++ b/Mage.Sets/src/mage/cards/m/MetallicMimic.java @@ -1,160 +1,135 @@ -/* - * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of BetaSteward_at_googlemail.com. - */ -package mage.cards.m; - -import java.util.UUID; -import mage.MageInt; -import mage.abilities.Ability; -import mage.abilities.common.AsEntersBattlefieldAbility; -import mage.abilities.common.SimpleStaticAbility; -import mage.abilities.effects.ContinuousEffectImpl; -import mage.abilities.effects.ReplacementEffectImpl; -import mage.abilities.effects.common.ChooseCreatureTypeEffect; -import mage.cards.CardImpl; -import mage.cards.CardSetInfo; -import mage.constants.CardType; -import mage.constants.Duration; -import mage.constants.Layer; -import mage.constants.Outcome; -import mage.constants.SubLayer; -import mage.constants.Zone; -import mage.counters.CounterType; -import mage.game.Game; -import mage.game.events.EntersTheBattlefieldEvent; -import mage.game.events.GameEvent; -import mage.game.permanent.Permanent; - -/** - * - * @author Styxo - */ -public class MetallicMimic extends CardImpl { - - public MetallicMimic(UUID ownerId, CardSetInfo setInfo) { - super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{2}"); - - this.subtype.add("Shapeshifter"); - this.power = new MageInt(2); - this.toughness = new MageInt(1); - - // As Metallic Mimic enters the battlefield, choose a creature type. - this.addAbility(new AsEntersBattlefieldAbility(new ChooseCreatureTypeEffect(Outcome.BoostCreature))); - - // Metallic Mimic is the chosen type in addition to its other types. - this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new MetallicMimicEffect())); - - // Each other creature you control of the chosen type enters the battlefield with an additional +1/+1 counter on it. - this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new MetallicMimicReplacementEffect())); - - } - - public MetallicMimic(final MetallicMimic card) { - super(card); - } - - @Override - public MetallicMimic copy() { - return new MetallicMimic(this); - } - - class MetallicMimicEffect extends ContinuousEffectImpl { - - public MetallicMimicEffect() { - super(Duration.WhileOnBattlefield, Layer.TypeChangingEffects_4, SubLayer.NA, Outcome.Benefit); - staticText = "{this} is the chosen type in addition to its other types"; - } - - public MetallicMimicEffect(final MetallicMimicEffect effect) { - super(effect); - } - - @Override - public boolean apply(Game game, Ability source) { - Permanent permanent = game.getPermanent(source.getSourceId()); - if (permanent != null) { - String subtype = (String) game.getState().getValue(permanent.getId() + "_type"); - if (subtype != null && !permanent.getSubtype(game).contains(subtype)) { - permanent.getSubtype(game).add(subtype); - } - } - return true; - } - - @Override - public MetallicMimicEffect copy() { - return new MetallicMimicEffect(this); - } - } -} - -class MetallicMimicReplacementEffect extends ReplacementEffectImpl { - - MetallicMimicReplacementEffect() { - super(Duration.WhileOnBattlefield, Outcome.BoostCreature); - staticText = "Each other creature you control of the chosen type enters the battlefield with an additional +1/+1 counter on it"; - } - - MetallicMimicReplacementEffect(MetallicMimicReplacementEffect effect) { - super(effect); - } - - @Override - public boolean checksEventType(GameEvent event, Game game) { - return event.getType() == GameEvent.EventType.ENTERS_THE_BATTLEFIELD; - } - - @Override - public boolean applies(GameEvent event, Ability source, Game game) { - Permanent sourcePermanent = game.getPermanent(source.getSourceId()); - Permanent enteringCreature = ((EntersTheBattlefieldEvent) event).getTarget(); - return enteringCreature != null && sourcePermanent != null - && enteringCreature.getControllerId().equals(source.getControllerId()) - && enteringCreature.getCardType().contains(CardType.CREATURE) - && enteringCreature.getSubtype(game).contains((String) game.getState().getValue(sourcePermanent.getId() + "_type")) - && !event.getTargetId().equals(source.getSourceId()); - } - - @Override - public boolean apply(Game game, Ability source) { - return false; - } - - @Override - public boolean replaceEvent(GameEvent event, Ability source, Game game) { - Permanent creature = ((EntersTheBattlefieldEvent) event).getTarget(); - if (creature != null) { - creature.addCounters(CounterType.P1P1.createInstance(), source, game); - } - return false; - } - - @Override - public MetallicMimicReplacementEffect copy() { - return new MetallicMimicReplacementEffect(this); - } -} +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.m; + +import java.util.UUID; +import mage.MageInt; +import mage.abilities.Ability; +import mage.abilities.common.AsEntersBattlefieldAbility; +import mage.abilities.common.SimpleStaticAbility; +import mage.abilities.effects.ReplacementEffectImpl; +import mage.abilities.effects.common.ChooseCreatureTypeEffect; +import mage.abilities.effects.common.enterAttribute.EnterAttributeAddChosenSubtypeEffect; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.constants.Duration; +import mage.constants.EnterEventType; +import mage.constants.Outcome; +import mage.constants.Zone; +import mage.counters.CounterType; +import mage.game.Game; +import mage.game.events.EntersTheBattlefieldEvent; +import mage.game.events.GameEvent; +import mage.game.permanent.Permanent; + +/** + * + * @author Styxo + */ +public class MetallicMimic extends CardImpl { + + public MetallicMimic(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{2}"); + + this.subtype.add("Shapeshifter"); + this.power = new MageInt(2); + this.toughness = new MageInt(1); + + // As Metallic Mimic enters the battlefield, choose a creature type. + AsEntersBattlefieldAbility ability = new AsEntersBattlefieldAbility(new ChooseCreatureTypeEffect(Outcome.BoostCreature), null, EnterEventType.SELF); + // Metallic Mimic is the chosen type in addition to its other types. + ability.addEffect(new EnterAttributeAddChosenSubtypeEffect()); + this.addAbility(ability); + + // Each other creature you control of the chosen type enters the battlefield with an additional +1/+1 counter on it. + this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new MetallicMimicReplacementEffect())); + + } + + public MetallicMimic(final MetallicMimic card) { + super(card); + } + + @Override + public MetallicMimic copy() { + return new MetallicMimic(this); + } + +} + +class MetallicMimicReplacementEffect extends ReplacementEffectImpl { + + MetallicMimicReplacementEffect() { + super(Duration.WhileOnBattlefield, Outcome.BoostCreature); + staticText = "Each other creature you control of the chosen type enters the battlefield with an additional +1/+1 counter on it"; + setCharacterDefining(true); + } + + MetallicMimicReplacementEffect(MetallicMimicReplacementEffect effect) { + super(effect); + } + + @Override + public boolean checksEventType(GameEvent event, Game game) { + return event.getType() == GameEvent.EventType.ENTERS_THE_BATTLEFIELD; + } + + @Override + public boolean applies(GameEvent event, Ability source, Game game) { + Permanent sourcePermanent = game.getPermanent(source.getSourceId()); + Permanent enteringCreature = ((EntersTheBattlefieldEvent) event).getTarget(); + if (enteringCreature != null && sourcePermanent != null + && enteringCreature.getControllerId().equals(source.getControllerId()) + && enteringCreature.getCardType().contains(CardType.CREATURE) + && !event.getTargetId().equals(source.getSourceId())) { + String subtype = (String) game.getState().getValue(sourcePermanent.getId() + "_type"); + return subtype != null && enteringCreature.getSubtype(game).contains(subtype); + } + return false; + } + + @Override + public boolean apply(Game game, Ability source) { + return false; + } + + @Override + public boolean replaceEvent(GameEvent event, Ability source, Game game) { + Permanent creature = ((EntersTheBattlefieldEvent) event).getTarget(); + if (creature != null) { + creature.addCounters(CounterType.P1P1.createInstance(), source, game); + } + return false; + } + + @Override + public MetallicMimicReplacementEffect copy() { + return new MetallicMimicReplacementEffect(this); + } +} diff --git a/Mage.Sets/src/mage/cards/m/MinamosMeddling.java b/Mage.Sets/src/mage/cards/m/MinamosMeddling.java index d14d9728496..565026bc112 100644 --- a/Mage.Sets/src/mage/cards/m/MinamosMeddling.java +++ b/Mage.Sets/src/mage/cards/m/MinamosMeddling.java @@ -27,7 +27,6 @@ */ package mage.cards.m; -import java.util.UUID; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.SpellAbility; diff --git a/Mage.Sets/src/mage/cards/m/Mindreaver.java b/Mage.Sets/src/mage/cards/m/Mindreaver.java index 653f7a71f4c..6de80efc193 100644 --- a/Mage.Sets/src/mage/cards/m/Mindreaver.java +++ b/Mage.Sets/src/mage/cards/m/Mindreaver.java @@ -42,7 +42,6 @@ import mage.abilities.keyword.HeroicAbility; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.cards.CardSetInfo; import mage.cards.SplitCard; import mage.constants.CardType; import mage.constants.Outcome; diff --git a/Mage.Sets/src/mage/cards/m/MoldgrafMonstrosity.java b/Mage.Sets/src/mage/cards/m/MoldgrafMonstrosity.java index 65e94c25865..73a5b10e7b6 100644 --- a/Mage.Sets/src/mage/cards/m/MoldgrafMonstrosity.java +++ b/Mage.Sets/src/mage/cards/m/MoldgrafMonstrosity.java @@ -27,7 +27,6 @@ */ package mage.cards.m; -import java.util.Random; import java.util.Set; import java.util.UUID; import mage.constants.CardType; diff --git a/Mage.Sets/src/mage/cards/m/MoltenBirth.java b/Mage.Sets/src/mage/cards/m/MoltenBirth.java index 92a41be61e2..1e91c9a2f2f 100644 --- a/Mage.Sets/src/mage/cards/m/MoltenBirth.java +++ b/Mage.Sets/src/mage/cards/m/MoltenBirth.java @@ -27,7 +27,6 @@ */ package mage.cards.m; -import java.util.Random; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; diff --git a/Mage.Sets/src/mage/cards/m/MonstrousOnslaught.java b/Mage.Sets/src/mage/cards/m/MonstrousOnslaught.java index 71c1332ec0f..4e8b0908ede 100644 --- a/Mage.Sets/src/mage/cards/m/MonstrousOnslaught.java +++ b/Mage.Sets/src/mage/cards/m/MonstrousOnslaught.java @@ -1,65 +1,65 @@ -/* - * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of BetaSteward_at_googlemail.com. - */ -package mage.cards.m; - -import java.util.UUID; -import mage.abilities.dynamicvalue.DynamicValue; -import mage.abilities.dynamicvalue.common.GreatestPowerAmongControlledCreaturesValue; -import mage.abilities.effects.Effect; -import mage.abilities.effects.common.DamageMultiEffect; -import mage.cards.CardImpl; -import mage.cards.CardSetInfo; -import mage.constants.CardType; -import mage.target.common.TargetCreaturePermanentAmount; - -/** - * - * @author Styxo - */ -public class MonstrousOnslaught extends CardImpl { - - public MonstrousOnslaught(UUID ownerId, CardSetInfo setInfo) { - super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{G}{G}"); - - // Monstrous Onslaught deals X damage divided as you choose among any number of target creatures, where X is the greater power among creatures you control as you cast Monstrous Onslaught. - DynamicValue xValue = new GreatestPowerAmongControlledCreaturesValue(); - Effect effect = new DamageMultiEffect(xValue); - effect.setText("{this} deals X damage divided as you choose among any number of target creatures, where X is the greatest amount of damage dealt by a source to a permanent or player this turn"); - this.getSpellAbility().addEffect(effect); - this.getSpellAbility().addTarget(new TargetCreaturePermanentAmount(xValue)); - } - - public MonstrousOnslaught(final MonstrousOnslaught card) { - super(card); - } - - @Override - public MonstrousOnslaught copy() { - return new MonstrousOnslaught(this); - } -} +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.m; + +import java.util.UUID; +import mage.abilities.dynamicvalue.DynamicValue; +import mage.abilities.dynamicvalue.common.GreatestPowerAmongControlledCreaturesValue; +import mage.abilities.effects.Effect; +import mage.abilities.effects.common.DamageMultiEffect; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.target.common.TargetCreaturePermanentAmount; + +/** + * + * @author Styxo + */ +public class MonstrousOnslaught extends CardImpl { + + public MonstrousOnslaught(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{G}{G}"); + + // Monstrous Onslaught deals X damage divided as you choose among any number of target creatures, where X is the greatest power among creatures you control as you cast Monstrous Onslaught. + DynamicValue xValue = new GreatestPowerAmongControlledCreaturesValue(); + Effect effect = new DamageMultiEffect(xValue); + effect.setText("{this} deals X damage divided as you choose among any number of target creatures, where X is the greatest power among creatures you control as you cast {this}"); + this.getSpellAbility().addEffect(effect); + this.getSpellAbility().addTarget(new TargetCreaturePermanentAmount(xValue)); + } + + public MonstrousOnslaught(final MonstrousOnslaught card) { + super(card); + } + + @Override + public MonstrousOnslaught copy() { + return new MonstrousOnslaught(this); + } +} diff --git a/Mage.Sets/src/mage/cards/m/MurderousSpoils.java b/Mage.Sets/src/mage/cards/m/MurderousSpoils.java index 46546608f63..e2a7f29e7a4 100644 --- a/Mage.Sets/src/mage/cards/m/MurderousSpoils.java +++ b/Mage.Sets/src/mage/cards/m/MurderousSpoils.java @@ -34,7 +34,6 @@ import mage.ObjectColor; import mage.abilities.Ability; import mage.abilities.effects.ContinuousEffect; import mage.abilities.effects.OneShotEffect; -import mage.abilities.effects.common.DestroyTargetEffect; import mage.abilities.effects.common.continuous.GainControlTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; @@ -43,7 +42,6 @@ import mage.constants.Duration; import mage.constants.Outcome; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicates; -import mage.filter.predicate.mageobject.CardTypePredicate; import mage.filter.predicate.mageobject.ColorPredicate; import mage.game.Game; import mage.game.permanent.Permanent; diff --git a/Mage.Sets/src/mage/cards/n/NoxiousGearhulk.java b/Mage.Sets/src/mage/cards/n/NoxiousGearhulk.java index 6e2145b911c..e035fd72a75 100644 --- a/Mage.Sets/src/mage/cards/n/NoxiousGearhulk.java +++ b/Mage.Sets/src/mage/cards/n/NoxiousGearhulk.java @@ -37,7 +37,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; -import mage.constants.Rarity; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.permanent.AnotherPredicate; import mage.game.Game; diff --git a/Mage.Sets/src/mage/cards/o/OathOfAjani.java b/Mage.Sets/src/mage/cards/o/OathOfAjani.java index 460abcceb3e..096a6b1a0cb 100644 --- a/Mage.Sets/src/mage/cards/o/OathOfAjani.java +++ b/Mage.Sets/src/mage/cards/o/OathOfAjani.java @@ -46,19 +46,16 @@ import java.util.UUID; */ public class OathOfAjani extends CardImpl { - private static final FilterControlledCreaturePermanent creatureFilter = new FilterControlledCreaturePermanent(); - private static final FilterPlaneswalkerCard planeswalkerFilter = new FilterPlaneswalkerCard("Planeswalker spells"); - public OathOfAjani(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{G}{W}"); this.supertype.add("Legendary"); // When Oath of Ajani enters the battlefield, put a +1/+1 counter on each creature you control. - this.addAbility(new EntersBattlefieldTriggeredAbility(new AddCountersAllEffect(CounterType.P1P1.createInstance(), creatureFilter))); + this.addAbility(new EntersBattlefieldTriggeredAbility(new AddCountersAllEffect(CounterType.P1P1.createInstance(), new FilterControlledCreaturePermanent()))); // Planeswalker spells you cast cost {1} less to cast. - this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new SpellsCostReductionControllerEffect(planeswalkerFilter, 1))); + this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new SpellsCostReductionControllerEffect(new FilterPlaneswalkerCard("Planeswalker spells"), 1))); } public OathOfAjani(final OathOfAjani card) { diff --git a/Mage.Sets/src/mage/cards/p/PanopticMirror.java b/Mage.Sets/src/mage/cards/p/PanopticMirror.java index cb206ed2706..aea3ef21da8 100644 --- a/Mage.Sets/src/mage/cards/p/PanopticMirror.java +++ b/Mage.Sets/src/mage/cards/p/PanopticMirror.java @@ -36,7 +36,6 @@ import mage.abilities.costs.mana.VariableManaCost; import mage.abilities.effects.OneShotEffect; import mage.cards.Card; import mage.cards.CardImpl; -import mage.cards.CardSetInfo; import mage.cards.CardsImpl; import mage.cards.CardSetInfo; import mage.cards.SplitCard; diff --git a/Mage.Sets/src/mage/cards/p/ParadoxEngine.java b/Mage.Sets/src/mage/cards/p/ParadoxEngine.java index 68adfa37b68..617624391a9 100644 --- a/Mage.Sets/src/mage/cards/p/ParadoxEngine.java +++ b/Mage.Sets/src/mage/cards/p/ParadoxEngine.java @@ -28,9 +28,7 @@ package mage.cards.p; import java.util.UUID; -import mage.abilities.Ability; import mage.abilities.common.SpellCastControllerTriggeredAbility; -import mage.abilities.effects.Effect; import mage.abilities.effects.common.UntapAllControllerEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; @@ -49,10 +47,7 @@ public class ParadoxEngine extends CardImpl { this.supertype.add("Legendary"); // Whenever you cast a spell, untap all nonland permanents you control. - Effect effect = new UntapAllControllerEffect(new FilterNonlandPermanent()); - Ability ability = new SpellCastControllerTriggeredAbility(effect, false); - ability.addEffect(effect); - this.addAbility(ability); + this.addAbility(new SpellCastControllerTriggeredAbility(new UntapAllControllerEffect(new FilterNonlandPermanent()), false)); } public ParadoxEngine(final ParadoxEngine card) { diff --git a/Mage.Sets/src/mage/cards/p/ParallelEvolution.java b/Mage.Sets/src/mage/cards/p/ParallelEvolution.java index 9923541227c..9d086f02094 100644 --- a/Mage.Sets/src/mage/cards/p/ParallelEvolution.java +++ b/Mage.Sets/src/mage/cards/p/ParallelEvolution.java @@ -28,7 +28,7 @@ package mage.cards.p; import java.util.UUID; -import mage.MageInt; + import mage.abilities.Ability; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.OneShotEffect; @@ -44,7 +44,6 @@ import mage.filter.predicate.mageobject.CardTypePredicate; import mage.filter.predicate.permanent.TokenPredicate; import mage.game.Game; import mage.game.permanent.Permanent; -import mage.game.permanent.token.Token; import mage.target.targetpointer.FixedTarget; /** diff --git a/Mage.Sets/src/mage/cards/p/PlanarBridge.java b/Mage.Sets/src/mage/cards/p/PlanarBridge.java index 978d11165f2..f50d69d6ab1 100644 --- a/Mage.Sets/src/mage/cards/p/PlanarBridge.java +++ b/Mage.Sets/src/mage/cards/p/PlanarBridge.java @@ -52,8 +52,11 @@ public class PlanarBridge extends CardImpl { this.supertype.add("Legendary"); // {8}, {T}: Search your library for a permanent card, put it onto the battlefield, then shuffle your library. - TargetCardInLibrary target = new TargetCardInLibrary(new FilterPermanentCard()); - Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new SearchLibraryPutInPlayEffect(target), new GenericManaCost(8)); + Ability ability = new SimpleActivatedAbility( + Zone.BATTLEFIELD, + new SearchLibraryPutInPlayEffect(new TargetCardInLibrary(new FilterPermanentCard())), + new GenericManaCost(8) + ); ability.addCost(new TapSourceCost()); this.addAbility(ability); } diff --git a/Mage.Sets/src/mage/cards/p/PriestOfYawgmoth.java b/Mage.Sets/src/mage/cards/p/PriestOfYawgmoth.java index d1d142459f7..6d87fed7300 100644 --- a/Mage.Sets/src/mage/cards/p/PriestOfYawgmoth.java +++ b/Mage.Sets/src/mage/cards/p/PriestOfYawgmoth.java @@ -32,7 +32,6 @@ import mage.MageInt; import mage.Mana; import mage.abilities.Ability; import mage.abilities.costs.common.SacrificeTargetCost; -import mage.abilities.costs.common.TapSourceCost; import mage.abilities.dynamicvalue.common.SacrificeCostConvertedMana; import mage.abilities.mana.DynamicManaAbility; import mage.cards.CardImpl; diff --git a/Mage.Sets/src/mage/cards/p/PsychicPossession.java b/Mage.Sets/src/mage/cards/p/PsychicPossession.java index 41d889c27d9..adfefd8af85 100644 --- a/Mage.Sets/src/mage/cards/p/PsychicPossession.java +++ b/Mage.Sets/src/mage/cards/p/PsychicPossession.java @@ -46,7 +46,6 @@ import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.TargetPlayer; import mage.target.common.TargetOpponent; -import mage.target.targetpointer.FixedTarget; /** * diff --git a/Mage.Sets/src/mage/cards/p/PulseOfTheTangle.java b/Mage.Sets/src/mage/cards/p/PulseOfTheTangle.java index 7345c5a9e21..01aa908d507 100644 --- a/Mage.Sets/src/mage/cards/p/PulseOfTheTangle.java +++ b/Mage.Sets/src/mage/cards/p/PulseOfTheTangle.java @@ -44,8 +44,6 @@ import mage.filter.predicate.permanent.ControllerIdPredicate; import mage.game.Game; import mage.game.permanent.token.BeastToken; import mage.players.Player; -import mage.target.TargetPlayer; -import mage.target.common.TargetOpponent; /** * diff --git a/Mage.Sets/src/mage/cards/q/QuicksilverElemental.java b/Mage.Sets/src/mage/cards/q/QuicksilverElemental.java new file mode 100644 index 00000000000..6841bbbfe5b --- /dev/null +++ b/Mage.Sets/src/mage/cards/q/QuicksilverElemental.java @@ -0,0 +1,162 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.q; + +import java.util.UUID; +import mage.MageInt; +import mage.abilities.Ability; +import mage.abilities.ActivatedAbility; +import mage.abilities.common.SimpleActivatedAbility; +import mage.abilities.common.SimpleStaticAbility; +import mage.abilities.costs.mana.ManaCostsImpl; +import mage.abilities.effects.AsThoughEffectImpl; +import mage.abilities.effects.AsThoughManaEffect; +import mage.abilities.effects.ContinuousEffectImpl; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.AbilityType; +import mage.constants.AsThoughEffectType; +import mage.constants.CardType; +import mage.constants.Duration; +import mage.constants.Layer; +import mage.constants.ManaType; +import mage.constants.Outcome; +import mage.constants.SubLayer; +import mage.constants.Zone; +import mage.game.Game; +import mage.game.permanent.Permanent; +import mage.game.stack.StackObject; +import mage.players.ManaPoolItem; +import mage.target.common.TargetCreaturePermanent; +import mage.target.targetpointer.FixedTarget; + +/** + * + * @author spjspj + */ +public class QuicksilverElemental extends CardImpl { + + public QuicksilverElemental(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{U}{U}"); + + this.subtype.add("Elemental"); + this.power = new MageInt(3); + this.toughness = new MageInt(4); + + // {U}: Quicksilver Elemental gains all activated abilities of target creature until end of turn. + Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new QuicksilverElementalEffect(), new ManaCostsImpl("{U}")); + ability.addTarget(new TargetCreaturePermanent()); + this.addAbility(ability); + + // You may spend blue mana as though it were mana of any color to pay the activation costs of Quicksilver Elemental's abilities. + QuickSilverElementalBlueManaEffect effect2 = new QuickSilverElementalBlueManaEffect(); + effect2.setTargetPointer(new FixedTarget(this.getId())); + Ability ability2 = new SimpleStaticAbility(Zone.BATTLEFIELD, effect2); + this.addAbility(ability2); + } + + public QuicksilverElemental(final QuicksilverElemental card) { + super(card); + } + + @Override + public QuicksilverElemental copy() { + return new QuicksilverElemental(this); + } +} + +class QuicksilverElementalEffect extends ContinuousEffectImpl { + + public QuicksilverElementalEffect() { + super(Duration.EndOfTurn, Layer.AbilityAddingRemovingEffects_6, SubLayer.NA, Outcome.AddAbility); + staticText = "{this} gains all activated abilities of target creature until end of turn"; + } + + public QuicksilverElementalEffect(final QuicksilverElementalEffect effect) { + super(effect); + } + + @Override + public QuicksilverElementalEffect copy() { + return new QuicksilverElementalEffect(this); + } + + @Override + public boolean apply(Game game, Ability source) { + Permanent permanent = game.getPermanent(source.getSourceId()); + Permanent creature = game.getPermanent(source.getTargets().getFirstTarget()); + + if (permanent != null && creature != null) { + for (ActivatedAbility ability : creature.getAbilities().getActivatedAbilities(Zone.BATTLEFIELD)) { + permanent.addAbility(ability, source.getSourceId(), game); + } + } + return false; + } +} + +class QuickSilverElementalBlueManaEffect extends AsThoughEffectImpl implements AsThoughManaEffect { + + public QuickSilverElementalBlueManaEffect() { + super(AsThoughEffectType.SPEND_OTHER_MANA, Duration.Custom, Outcome.Benefit); + staticText = "You may spend blue mana as though it were mana of any color to pay the activation costs of {this}'s abilities"; + } + + public QuickSilverElementalBlueManaEffect(final QuickSilverElementalBlueManaEffect effect) { + super(effect); + } + + @Override + public boolean apply(Game game, Ability source) { + return true; + } + + @Override + public QuickSilverElementalBlueManaEffect copy() { + return new QuickSilverElementalBlueManaEffect(this); + } + + @Override + public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) { + if (objectId.equals(getTargetPointer().getFirst(game, source))) { + if (affectedControllerId.equals(source.getControllerId())) { + return true; + } + } + + return false; + } + + @Override + public ManaType getAsThoughManaType(ManaType manaType, ManaPoolItem mana, UUID affectedControllerId, Ability source, Game game) { + if (mana.getBlue() > 0) { + return ManaType.BLUE; + } + return null; + } +} diff --git a/Mage.Sets/src/mage/cards/r/RavingDead.java b/Mage.Sets/src/mage/cards/r/RavingDead.java index 072681badcd..31cbab970bf 100644 --- a/Mage.Sets/src/mage/cards/r/RavingDead.java +++ b/Mage.Sets/src/mage/cards/r/RavingDead.java @@ -27,30 +27,21 @@ */ package mage.cards.r; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.BeginningOfCombatTriggeredAbility; import mage.abilities.common.DealsCombatDamageToAPlayerTriggeredAbility; -import mage.abilities.effects.ContinuousEffect; import mage.abilities.effects.OneShotEffect; -import mage.abilities.effects.RequirementEffect; import mage.abilities.effects.common.combat.AttackIfAbleTargetRandomOpponentSourceEffect; import mage.abilities.keyword.DeathtouchAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.TargetController; import mage.game.Game; -import mage.game.permanent.Permanent; import mage.players.Player; -import mage.target.targetpointer.FixedTarget; -import mage.util.RandomUtil; /** * diff --git a/Mage.Sets/src/mage/cards/r/RaziasPurification.java b/Mage.Sets/src/mage/cards/r/RaziasPurification.java new file mode 100644 index 00000000000..1ec8465bfbe --- /dev/null +++ b/Mage.Sets/src/mage/cards/r/RaziasPurification.java @@ -0,0 +1,118 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.r; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import mage.abilities.Ability; +import mage.abilities.effects.OneShotEffect; +import mage.cards.Card; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.constants.Outcome; +import mage.filter.common.FilterControlledPermanent; +import mage.game.Game; +import mage.game.permanent.Permanent; +import mage.players.Player; +import mage.target.Target; +import mage.target.common.TargetControlledPermanent; + +/** + * + * @author spjspj + */ +public class RaziasPurification extends CardImpl { + + public RaziasPurification(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{4}{R}{W}"); + + // Each player chooses three permanents he or she controls, then sacrifices the rest. + this.getSpellAbility().addEffect(new RaziasPurificationEffect()); + } + + public RaziasPurification(final RaziasPurification card) { + super(card); + } + + @Override + public RaziasPurification copy() { + return new RaziasPurification(this); + } +} + +class RaziasPurificationEffect extends OneShotEffect { + + public RaziasPurificationEffect() { + super(Outcome.DestroyPermanent); + staticText = "Each player chooses three permanents he or she controls, then sacrifices the rest"; + } + + public RaziasPurificationEffect(RaziasPurificationEffect effect) { + super(effect); + } + + @Override + public boolean apply(Game game, Ability source) { + List chosen = new ArrayList<>(); + + for (UUID playerId : game.getState().getPlayersInRange(source.getControllerId(), game)) { + Player player = game.getPlayer(playerId); + + Target target1 = new TargetControlledPermanent(1, 1, new FilterControlledPermanent(), true); + + if (target1.canChoose(player.getId(), game)) { + int chosenPermanents = 0; + while (player.canRespond() && !target1.isChosen() && target1.canChoose(player.getId(), game) && chosenPermanents < 3) { + player.chooseTarget(Outcome.Benefit, target1, source, game); + for (UUID targetId : target1.getTargets()) { + Permanent p = game.getPermanent(targetId); + if (p != null) { + chosen.add(p); + chosenPermanents++; + } + } + target1.clearChosen(); + } + } + } + + for (Permanent permanent : game.getBattlefield().getAllActivePermanents()) { + if (!chosen.contains(permanent)) { + permanent.sacrifice(source.getSourceId(), game); + } + } + return true; + } + + @Override + public RaziasPurificationEffect copy() { + return new RaziasPurificationEffect(this); + } +} diff --git a/Mage.Sets/src/mage/cards/r/ReachOfBranches.java b/Mage.Sets/src/mage/cards/r/ReachOfBranches.java index eaa25b81ce4..ea73a8d792e 100644 --- a/Mage.Sets/src/mage/cards/r/ReachOfBranches.java +++ b/Mage.Sets/src/mage/cards/r/ReachOfBranches.java @@ -48,21 +48,21 @@ import mage.game.permanent.token.Token; */ public class ReachOfBranches extends CardImpl { - private static final FilterLandPermanent filter = new FilterLandPermanent("Forest"); + private static final FilterLandPermanent filter = new FilterLandPermanent("a Forest"); + static { filter.add(new ControllerPredicate(TargetController.YOU)); filter.add(new SubtypePredicate("Forest")); } public ReachOfBranches(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.TRIBAL,CardType.INSTANT},"{4}{G}"); + super(ownerId, setInfo, new CardType[]{CardType.TRIBAL, CardType.INSTANT}, "{4}{G}"); this.subtype.add("Treefolk"); - // Create a 2/5 green Treefolk Shaman creature token. this.getSpellAbility().addEffect(new CreateTokenEffect(new TreefolkShamanToken())); // Whenever a Forest enters the battlefield under your control, you may return Reach of Branches from your graveyard to your hand. - this.addAbility(new EntersBattlefieldAllTriggeredAbility(Zone.GRAVEYARD, new ReturnSourceFromGraveyardToHandEffect(),filter, true, "", true)); + this.addAbility(new EntersBattlefieldAllTriggeredAbility(Zone.GRAVEYARD, new ReturnSourceFromGraveyardToHandEffect(), filter, true, "", true)); } public ReachOfBranches(final ReachOfBranches card) { @@ -76,6 +76,7 @@ public class ReachOfBranches extends CardImpl { } class TreefolkShamanToken extends Token { + TreefolkShamanToken() { super("Treefolk Shaman", "2/5 green Treefolk Shaman creature token"); cardType.add(CardType.CREATURE); @@ -85,4 +86,4 @@ class TreefolkShamanToken extends Token { power = new MageInt(2); toughness = new MageInt(5); } -} \ No newline at end of file +} diff --git a/Mage.Sets/src/mage/cards/r/ReleaseTheGremlins.java b/Mage.Sets/src/mage/cards/r/ReleaseTheGremlins.java index 237c39760e5..88b53d08992 100644 --- a/Mage.Sets/src/mage/cards/r/ReleaseTheGremlins.java +++ b/Mage.Sets/src/mage/cards/r/ReleaseTheGremlins.java @@ -28,7 +28,6 @@ package mage.cards.r; import java.util.UUID; -import mage.MageInt; import mage.abilities.Ability; import mage.abilities.SpellAbility; import mage.abilities.dynamicvalue.common.ManacostVariableValue; @@ -38,7 +37,7 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.game.Game; -import mage.game.permanent.token.Token; +import mage.game.permanent.token.GremlinToken; import mage.target.common.TargetArtifactPermanent; /** @@ -77,15 +76,3 @@ public class ReleaseTheGremlins extends CardImpl { return new ReleaseTheGremlins(this); } } - -class GremlinToken extends Token { - - public GremlinToken() { - super("Gremlin", "2/2 red Gremlin creature token"); - cardType.add(CardType.CREATURE); - subtype.add("Gremlin"); - color.setRed(true); - power = new MageInt(2); - toughness = new MageInt(2); - } -} diff --git a/Mage.Sets/src/mage/cards/r/RenegadeMap.java b/Mage.Sets/src/mage/cards/r/RenegadeMap.java index b93996d9368..adec1866f88 100644 --- a/Mage.Sets/src/mage/cards/r/RenegadeMap.java +++ b/Mage.Sets/src/mage/cards/r/RenegadeMap.java @@ -50,13 +50,15 @@ public class RenegadeMap extends CardImpl { public RenegadeMap(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{1}"); - // Renegade Map enters the battlefield tapped. this.addAbility(new EntersBattlefieldTappedAbility()); // {T}, Sacrifice Renegade Map: Search your library for a basic land card, reveal it, put it into your hand, then shuffle your library. - TargetCardInLibrary target = new TargetCardInLibrary(new FilterBasicLandCard()); - Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new SearchLibraryPutInHandEffect(target, true), new TapSourceCost()); + Ability ability = new SimpleActivatedAbility( + Zone.BATTLEFIELD, + new SearchLibraryPutInHandEffect(new TargetCardInLibrary(new FilterBasicLandCard()), true), + new TapSourceCost() + ); ability.addCost(new SacrificeSourceCost()); this.addAbility(ability); } diff --git a/Mage.Sets/src/mage/cards/r/RenegadeRallier.java b/Mage.Sets/src/mage/cards/r/RenegadeRallier.java index 6d72e819084..d36dda229aa 100644 --- a/Mage.Sets/src/mage/cards/r/RenegadeRallier.java +++ b/Mage.Sets/src/mage/cards/r/RenegadeRallier.java @@ -32,10 +32,11 @@ import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.RevoltCondition; -import mage.abilities.decorator.ConditionalOneShotEffect; +import mage.abilities.decorator.ConditionalTriggeredAbility; import mage.abilities.effects.common.ReturnFromGraveyardToBattlefieldTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.AbilityWord; import mage.constants.CardType; import mage.filter.Filter; import mage.filter.common.FilterPermanentCard; @@ -65,9 +66,11 @@ public class RenegadeRallier extends CardImpl { // Revolt — When Renegade Rallier enters the battlefield, if a permanent you controlled left the battlefield this turn, // return target permanent card with converted mana cost 2 or less from your graveyard to your battlefield. - Ability ability = new EntersBattlefieldTriggeredAbility( - new ConditionalOneShotEffect(new ReturnFromGraveyardToBattlefieldTargetEffect(), RevoltCondition.getInstance()), - false, "Revolt — "); + Ability ability = new ConditionalTriggeredAbility(new EntersBattlefieldTriggeredAbility( + new ReturnFromGraveyardToBattlefieldTargetEffect(), false), RevoltCondition.getInstance(), + "Revolt — When {this} enters the battlefield, if a permanent you controlled left" + + " the battlefield this turn, return target permanent card with converted mana cost 2 or less from your graveyard to your battlefield."); + ability.setAbilityWord(AbilityWord.REVOLT); ability.addTarget(new TargetCardInYourGraveyard(filter)); ability.addWatcher(new RevoltWatcher()); this.addAbility(ability); diff --git a/Mage.Sets/src/mage/cards/r/Reshape.java b/Mage.Sets/src/mage/cards/r/Reshape.java index c6c51cddd17..e056d49df0d 100644 --- a/Mage.Sets/src/mage/cards/r/Reshape.java +++ b/Mage.Sets/src/mage/cards/r/Reshape.java @@ -28,23 +28,13 @@ package mage.cards.r; import java.util.UUID; -import mage.abilities.Ability; import mage.abilities.costs.common.SacrificeTargetCost; -import mage.abilities.effects.OneShotEffect; -import mage.cards.Card; +import mage.abilities.effects.common.search.SearchLibraryWithLessCMCPutInPlayEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Outcome; -import mage.constants.Zone; -import mage.filter.Filter; -import mage.filter.FilterCard; -import mage.filter.common.FilterControlledPermanent; -import mage.filter.predicate.mageobject.CardTypePredicate; -import mage.filter.predicate.mageobject.ConvertedManaCostPredicate; -import mage.game.Game; -import mage.players.Player; -import mage.target.common.TargetCardInLibrary; +import mage.filter.common.FilterArtifactCard; +import mage.filter.common.FilterControlledArtifactPermanent; import mage.target.common.TargetControlledPermanent; /** @@ -53,19 +43,14 @@ import mage.target.common.TargetControlledPermanent; */ public class Reshape extends CardImpl { - private static final FilterControlledPermanent filter = new FilterControlledPermanent("an artifact"); - - static { - filter.add(new CardTypePredicate(CardType.ARTIFACT)); - } - public Reshape(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{X}{U}{U}"); + super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{X}{U}{U}"); // As an additional cost to cast Reshape, sacrifice an artifact. - this.getSpellAbility().addCost(new SacrificeTargetCost(new TargetControlledPermanent(1, 1, filter, false))); + this.getSpellAbility().addCost(new SacrificeTargetCost(new TargetControlledPermanent(1, 1, new FilterControlledArtifactPermanent("an artifact"), false))); + // Search your library for an artifact card with converted mana cost X or less and put it onto the battlefield. Then shuffle your library. - this.getSpellAbility().addEffect(new ReshapeSearchEffect()); + this.getSpellAbility().addEffect(new SearchLibraryWithLessCMCPutInPlayEffect(new FilterArtifactCard())); } public Reshape(final Reshape card) { @@ -77,46 +62,3 @@ public class Reshape extends CardImpl { return new Reshape(this); } } - -class ReshapeSearchEffect extends OneShotEffect { - - ReshapeSearchEffect() { - super(Outcome.PutCardInPlay); - staticText = "Search your library for an artifact card with converted mana cost X or less and put it onto the battlefield. Then shuffle your library"; - } - - ReshapeSearchEffect(final ReshapeSearchEffect effect) { - super(effect); - } - - @Override - public boolean apply(Game game, Ability source) { - Player controller = game.getPlayer(source.getControllerId()); - if (controller == null) { - return false; - } - //Set the mana cost one higher to 'emulate' a less than or equal to comparison. - int xValue = source.getManaCostsToPay().getX() + 1; - FilterCard filter = new FilterCard("artifact card with converted mana cost " + xValue + " or less"); - filter.add(new CardTypePredicate(CardType.ARTIFACT)); - filter.add(new ConvertedManaCostPredicate(Filter.ComparisonType.LessThan, xValue)); - TargetCardInLibrary target = new TargetCardInLibrary(filter); - if (controller.searchLibrary(target, game)) { - if (target.getTargets().size() > 0) { - Card card = controller.getLibrary().getCard(target.getFirstTarget(), game); - if (card != null) { - controller.moveCards(card, Zone.BATTLEFIELD, source, game); - } - } - controller.shuffleLibrary(source, game); - return true; - } - controller.shuffleLibrary(source, game); - return false; - } - - @Override - public ReshapeSearchEffect copy() { - return new ReshapeSearchEffect(this); - } -} diff --git a/Mage.Sets/src/mage/cards/r/RestorationSpecialist.java b/Mage.Sets/src/mage/cards/r/RestorationSpecialist.java index 0fc7bf501fd..6f9db5e0f26 100644 --- a/Mage.Sets/src/mage/cards/r/RestorationSpecialist.java +++ b/Mage.Sets/src/mage/cards/r/RestorationSpecialist.java @@ -34,7 +34,6 @@ import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.SacrificeSourceCost; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.Effect; -import mage.abilities.effects.common.ReturnFromGraveyardToHandTargetEffect; import mage.abilities.effects.common.ReturnToHandTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/r/RevolutionaryRebuff.java b/Mage.Sets/src/mage/cards/r/RevolutionaryRebuff.java index d2f6b0fd840..8fc0d6f6cfa 100644 --- a/Mage.Sets/src/mage/cards/r/RevolutionaryRebuff.java +++ b/Mage.Sets/src/mage/cards/r/RevolutionaryRebuff.java @@ -45,10 +45,10 @@ import mage.target.TargetSpell; public class RevolutionaryRebuff extends CardImpl { public RevolutionaryRebuff(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{1}{U}"); + super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{1}{U}"); // Counter target nonartifact spell unless its controller pays 2. - FilterSpell filter = new FilterSpell(); + FilterSpell filter = new FilterSpell("nonartifact spell"); filter.add(Predicates.not(new CardTypePredicate(CardType.ARTIFACT))); this.getSpellAbility().addTarget(new TargetSpell(filter)); this.getSpellAbility().addEffect(new CounterUnlessPaysEffect(new GenericManaCost(2))); diff --git a/Mage.Sets/src/mage/cards/r/RingsOfBrighthearth.java b/Mage.Sets/src/mage/cards/r/RingsOfBrighthearth.java index 53b26ae4336..cef4a6d91c9 100644 --- a/Mage.Sets/src/mage/cards/r/RingsOfBrighthearth.java +++ b/Mage.Sets/src/mage/cards/r/RingsOfBrighthearth.java @@ -53,7 +53,7 @@ import mage.players.Player; public class RingsOfBrighthearth extends CardImpl { public RingsOfBrighthearth(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT},"{3}"); + super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{3}"); // Whenever you activate an ability, if it isn't a mana ability, you may pay {2}. If you do, copy that ability. You may choose new targets for the copy. this.addAbility(new RingsOfBrighthearthTriggeredAbility()); @@ -133,10 +133,10 @@ class RingsOfBrighthearthEffect extends OneShotEffect { if (cost.pay(source, game, source.getSourceId(), source.getControllerId(), false, null)) { StackAbility ability = (StackAbility) getValue("stackAbility"); Player controller = game.getPlayer(source.getControllerId()); - Permanent sourcePermanent = game.getPermanent(source.getSourceId()); - if (ability != null && controller != null) { + Permanent sourcePermanent = game.getPermanentOrLKIBattlefield(source.getSourceId()); + if (ability != null && controller != null && sourcePermanent != null) { ability.createCopyOnStack(game, source, source.getControllerId(), true); - game.informPlayers(new StringBuilder(sourcePermanent.getName()).append(": ").append(controller.getLogName()).append(" copied activated ability").toString()); + game.informPlayers(sourcePermanent.getIdName() + ": " + controller.getLogName() + " copied activated ability"); return true; } return false; diff --git a/Mage.Sets/src/mage/cards/r/RishkarPeemaRenegade.java b/Mage.Sets/src/mage/cards/r/RishkarPeemaRenegade.java index 7c15888396e..e29cb783c35 100644 --- a/Mage.Sets/src/mage/cards/r/RishkarPeemaRenegade.java +++ b/Mage.Sets/src/mage/cards/r/RishkarPeemaRenegade.java @@ -33,7 +33,7 @@ import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.Effect; -import mage.abilities.effects.common.continuous.GainAbilityAllEffect; +import mage.abilities.effects.common.continuous.GainAbilityControlledEffect; import mage.abilities.effects.common.counter.AddCountersTargetEffect; import mage.abilities.mana.GreenManaAbility; import mage.cards.CardImpl; @@ -52,7 +52,7 @@ import mage.target.common.TargetCreaturePermanent; */ public class RishkarPeemaRenegade extends CardImpl { - private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("Each creature with a counter on it"); + private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("Each creature you control with a counter on it"); static { filter.add(new CounterAnyPredicate()); @@ -77,7 +77,7 @@ public class RishkarPeemaRenegade extends CardImpl { // Each creature you control with a counter on it has "T: Add G to your mana pool." this.addAbility(new SimpleStaticAbility( Zone.BATTLEFIELD, - new GainAbilityAllEffect( + new GainAbilityControlledEffect( new GreenManaAbility(), Duration.WhileOnBattlefield, filter))); diff --git a/Mage.Sets/src/mage/cards/r/RunnersBane.java b/Mage.Sets/src/mage/cards/r/RunnersBane.java index da95240dc90..12fea6114ea 100644 --- a/Mage.Sets/src/mage/cards/r/RunnersBane.java +++ b/Mage.Sets/src/mage/cards/r/RunnersBane.java @@ -35,7 +35,6 @@ import mage.constants.Zone; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; -import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.DontUntapInControllersUntapStepEnchantedEffect; import mage.abilities.keyword.EnchantAbility; @@ -45,8 +44,6 @@ import mage.constants.Outcome; import mage.filter.Filter; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.PowerPredicate; -import mage.game.Game; -import mage.game.permanent.Permanent; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; diff --git a/Mage.Sets/src/mage/cards/r/RushingRiver.java b/Mage.Sets/src/mage/cards/r/RushingRiver.java index 8125908332b..2fe97fb671c 100644 --- a/Mage.Sets/src/mage/cards/r/RushingRiver.java +++ b/Mage.Sets/src/mage/cards/r/RushingRiver.java @@ -40,7 +40,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.common.FilterControlledLandPermanent; -import mage.filter.common.FilterNonlandPermanent; import mage.game.Game; import mage.target.common.TargetControlledPermanent; import mage.target.common.TargetNonlandPermanent; diff --git a/Mage.Sets/src/mage/cards/s/SagesRowDenizen.java b/Mage.Sets/src/mage/cards/s/SagesRowDenizen.java index caa3ffd71d6..ce0d9a83eec 100644 --- a/Mage.Sets/src/mage/cards/s/SagesRowDenizen.java +++ b/Mage.Sets/src/mage/cards/s/SagesRowDenizen.java @@ -28,9 +28,6 @@ package mage.cards.s; import java.util.UUID; -import mage.constants.CardType; -import mage.constants.TargetController; -import mage.constants.Zone; import mage.MageInt; import mage.ObjectColor; import mage.abilities.Ability; @@ -38,6 +35,9 @@ import mage.abilities.common.EntersBattlefieldAllTriggeredAbility; import mage.abilities.effects.common.PutLibraryIntoGraveTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.constants.TargetController; +import mage.constants.Zone; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.ColorPredicate; import mage.filter.predicate.permanent.AnotherPredicate; @@ -51,13 +51,15 @@ import mage.target.TargetPlayer; public class SagesRowDenizen extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("another blue creature"); + static { filter.add(new ColorPredicate(ObjectColor.BLUE)); filter.add(new AnotherPredicate()); filter.add(new ControllerPredicate(TargetController.YOU)); } + public SagesRowDenizen(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{U}"); + super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}"); this.subtype.add("Vedalken"); this.subtype.add("Wizard"); diff --git a/Mage.Sets/src/mage/cards/s/SalvageScuttler.java b/Mage.Sets/src/mage/cards/s/SalvageScuttler.java index dde96b7e14b..457416c9add 100644 --- a/Mage.Sets/src/mage/cards/s/SalvageScuttler.java +++ b/Mage.Sets/src/mage/cards/s/SalvageScuttler.java @@ -29,16 +29,13 @@ package mage.cards.s; import java.util.UUID; import mage.MageInt; -import mage.abilities.TriggeredAbilityImpl; +import mage.abilities.Ability; +import mage.abilities.common.AttacksTriggeredAbility; import mage.abilities.effects.common.ReturnToHandTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Zone; import mage.filter.common.FilterControlledArtifactPermanent; -import mage.game.Game; -import mage.game.events.GameEvent; -import mage.game.events.GameEvent.EventType; import mage.target.common.TargetControlledPermanent; /** @@ -55,7 +52,9 @@ public class SalvageScuttler extends CardImpl { this.toughness = new MageInt(4); // Whenever Salvage Scuttler attacks, return an artifact you control to its owner's hand. - this.addAbility(new SalvageScuttlerAbility()); + Ability ability = new AttacksTriggeredAbility(new ReturnToHandTargetEffect(), false); + ability.addTarget(new TargetControlledPermanent(new FilterControlledArtifactPermanent("an artifact you control"))); + this.addAbility(ability); } public SalvageScuttler(final SalvageScuttler card) { @@ -67,39 +66,3 @@ public class SalvageScuttler extends CardImpl { return new SalvageScuttler(this); } } - -class SalvageScuttlerAbility extends TriggeredAbilityImpl { - - public SalvageScuttlerAbility() { - super(Zone.BATTLEFIELD, new ReturnToHandTargetEffect()); - } - - public SalvageScuttlerAbility(final SalvageScuttlerAbility ability) { - super(ability); - } - - @Override - public boolean checkEventType(GameEvent event, Game game) { - return event.getType() == EventType.ATTACKER_DECLARED; - } - - @Override - public boolean checkTrigger(GameEvent event, Game game) { - if (event.getSourceId().equals(this.getSourceId())) { - TargetControlledPermanent target = new TargetControlledPermanent(1, 1, new FilterControlledArtifactPermanent("artifact you control"), false); - this.addTarget(target); - return true; - } - return false; - } - - @Override - public String getRule() { - return "Whenever {this} attacks, return an artifact you control to its owner's hand."; - } - - @Override - public SalvageScuttlerAbility copy() { - return new SalvageScuttlerAbility(this); - } -} diff --git a/Mage.Sets/src/mage/cards/s/SalvageTitan.java b/Mage.Sets/src/mage/cards/s/SalvageTitan.java index 8ff401cd3ef..569865e9ee2 100644 --- a/Mage.Sets/src/mage/cards/s/SalvageTitan.java +++ b/Mage.Sets/src/mage/cards/s/SalvageTitan.java @@ -40,8 +40,6 @@ import mage.constants.CardType; import mage.constants.Zone; import mage.filter.common.FilterArtifactCard; import mage.filter.common.FilterControlledArtifactPermanent; -import mage.filter.common.FilterControlledPermanent; -import mage.filter.predicate.mageobject.CardTypePredicate; import mage.target.common.TargetCardInYourGraveyard; import mage.target.common.TargetControlledPermanent; diff --git a/Mage.Sets/src/mage/cards/s/SanctumPrelate.java b/Mage.Sets/src/mage/cards/s/SanctumPrelate.java index e015da5b0aa..b79ecd0e4ec 100644 --- a/Mage.Sets/src/mage/cards/s/SanctumPrelate.java +++ b/Mage.Sets/src/mage/cards/s/SanctumPrelate.java @@ -27,7 +27,6 @@ */ package mage.cards.s; -import java.util.HashSet; import java.util.UUID; import mage.MageInt; import mage.MageObject; @@ -36,18 +35,14 @@ import mage.abilities.common.AsEntersBattlefieldAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.ContinuousRuleModifyingEffectImpl; import mage.abilities.effects.OneShotEffect; -import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.choices.Choice; -import mage.choices.ChoiceImpl; import mage.constants.*; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; import mage.game.stack.Spell; import mage.players.Player; -import org.apache.log4j.Logger; /** * diff --git a/Mage.Sets/src/mage/cards/s/SatyrHedonist.java b/Mage.Sets/src/mage/cards/s/SatyrHedonist.java index f8427000673..9c7f479d6ca 100644 --- a/Mage.Sets/src/mage/cards/s/SatyrHedonist.java +++ b/Mage.Sets/src/mage/cards/s/SatyrHedonist.java @@ -30,11 +30,8 @@ package mage.cards.s; import java.util.UUID; import mage.MageInt; import mage.Mana; -import mage.abilities.Ability; -import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.SacrificeSourceCost; import mage.abilities.costs.mana.ManaCostsImpl; -import mage.abilities.effects.common.BasicManaEffect; import mage.abilities.mana.SimpleManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/s/Scrambleverse.java b/Mage.Sets/src/mage/cards/s/Scrambleverse.java index 1c7c0fe8446..27f7a7bf2a5 100644 --- a/Mage.Sets/src/mage/cards/s/Scrambleverse.java +++ b/Mage.Sets/src/mage/cards/s/Scrambleverse.java @@ -27,7 +27,6 @@ */ package mage.cards.s; -import java.util.Random; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.effects.ContinuousEffect; diff --git a/Mage.Sets/src/mage/cards/s/SigardaHostOfHerons.java b/Mage.Sets/src/mage/cards/s/SigardaHostOfHerons.java index c80bd1d1ee6..3c262f6af9d 100644 --- a/Mage.Sets/src/mage/cards/s/SigardaHostOfHerons.java +++ b/Mage.Sets/src/mage/cards/s/SigardaHostOfHerons.java @@ -42,7 +42,6 @@ import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.Zone; -import mage.game.Controllable; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.permanent.PermanentCard; diff --git a/Mage.Sets/src/mage/cards/s/SilkweaverElite.java b/Mage.Sets/src/mage/cards/s/SilkweaverElite.java index 53f4cd304e8..f3696e1f723 100644 --- a/Mage.Sets/src/mage/cards/s/SilkweaverElite.java +++ b/Mage.Sets/src/mage/cards/s/SilkweaverElite.java @@ -25,23 +25,22 @@ * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. */ - package mage.cards.s; +import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.RevoltCondition; -import mage.abilities.decorator.ConditionalOneShotEffect; +import mage.abilities.decorator.ConditionalTriggeredAbility; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.keyword.ReachAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.AbilityWord; import mage.constants.CardType; import mage.watchers.common.RevoltWatcher; -import java.util.UUID; - /** * @author JRHerlehy */ @@ -59,11 +58,14 @@ public class SilkweaverElite extends CardImpl { this.addAbility(ReachAbility.getInstance()); // Revolt — When Silkweaver Elite enters the battlefield, if a permanent you controlled left the battlefield this turn, draw a card. - Ability ability = new EntersBattlefieldTriggeredAbility( - new ConditionalOneShotEffect(new DrawCardSourceControllerEffect(1), RevoltCondition.getInstance()), - false, "Revolt — "); + Ability ability = new ConditionalTriggeredAbility(new EntersBattlefieldTriggeredAbility( + new DrawCardSourceControllerEffect(1), false), RevoltCondition.getInstance(), + "Revolt — When {this} enters the battlefield, if a permanent you controlled left" + + " the battlefield this turn, draw a card."); + ability.setAbilityWord(AbilityWord.REVOLT); ability.addWatcher(new RevoltWatcher()); this.addAbility(ability); + } public SilkweaverElite(final SilkweaverElite card) { diff --git a/Mage.Sets/src/mage/cards/s/SithMindseer.java b/Mage.Sets/src/mage/cards/s/SithMindseer.java index 9728c33c105..dca94015943 100644 --- a/Mage.Sets/src/mage/cards/s/SithMindseer.java +++ b/Mage.Sets/src/mage/cards/s/SithMindseer.java @@ -33,7 +33,6 @@ import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.HateCondition; import mage.abilities.decorator.ConditionalTriggeredAbility; -import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.effects.common.continuous.GainControlTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/s/SkyshipPlunderer.java b/Mage.Sets/src/mage/cards/s/SkyshipPlunderer.java index 731ccc333d6..0d9dc6828e0 100644 --- a/Mage.Sets/src/mage/cards/s/SkyshipPlunderer.java +++ b/Mage.Sets/src/mage/cards/s/SkyshipPlunderer.java @@ -39,6 +39,8 @@ import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.counters.Counter; +import mage.counters.CounterType; +import mage.counters.Counters; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; @@ -94,17 +96,35 @@ class SkyshipPlundererEffect extends OneShotEffect { if (controller != null) { Player player = game.getPlayer(getTargetPointer().getFirst(game, source)); if (player != null) { - for (Counter counter : player.getCounters().values()) { - counter.increase(); + Counters counters = player.getCounters().copy(); + for (Counter counter : counters.values()) { + CounterType counterType = CounterType.findByName(counter.getName()); + Counter counterToAdd; + if (counterType != null) { + counterToAdd = counterType.createInstance(); + } else { + counterToAdd = new Counter(counter.getName()); + } + player.addCounters(counterToAdd, game); } + return true; } Permanent permanent = game.getPermanent(getTargetPointer().getFirst(game, source)); if (permanent != null) { - for (Counter counter : permanent.getCounters(game).values()) { - counter.increase(); + Counters counters = permanent.getCounters(game).copy(); + for (Counter counter : counters.values()) { + CounterType counterType = CounterType.findByName(counter.getName()); + Counter counterToAdd; + if (counterType != null) { + counterToAdd = counterType.createInstance(); + } else { + counterToAdd = new Counter(counter.getName()); + } + permanent.addCounters(counterToAdd, source, game); } } return true; + } return false; } diff --git a/Mage.Sets/src/mage/cards/s/SkyshroudRanger.java b/Mage.Sets/src/mage/cards/s/SkyshroudRanger.java index 338f5174500..826d43ccf74 100644 --- a/Mage.Sets/src/mage/cards/s/SkyshroudRanger.java +++ b/Mage.Sets/src/mage/cards/s/SkyshroudRanger.java @@ -29,7 +29,6 @@ package mage.cards.s; import java.util.UUID; import mage.MageInt; -import mage.abilities.Ability; import mage.abilities.common.ActivateAsSorceryActivatedAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.effects.common.PutLandFromHandOntoBattlefieldEffect; @@ -37,8 +36,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Zone; -import mage.filter.common.FilterLandCard; -import mage.target.common.TargetCardInHand; /** * diff --git a/Mage.Sets/src/mage/cards/s/SlyRequisitioner.java b/Mage.Sets/src/mage/cards/s/SlyRequisitioner.java index 32f8ac27b4b..401ef21fb60 100644 --- a/Mage.Sets/src/mage/cards/s/SlyRequisitioner.java +++ b/Mage.Sets/src/mage/cards/s/SlyRequisitioner.java @@ -46,6 +46,12 @@ import mage.game.permanent.token.ServoToken; */ public class SlyRequisitioner extends CardImpl { + private static final FilterControlledArtifactPermanent filter = new FilterControlledArtifactPermanent("a nontoken artifact you control"); + + static { + filter.add(Predicates.not(new TokenPredicate())); + } + public SlyRequisitioner(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{B}"); @@ -56,9 +62,8 @@ public class SlyRequisitioner extends CardImpl { // Improvise this.addAbility(new ImproviseAbility()); + // Whenever a nontoken artifact you control is put into a graveyard from the battlefield, create a 1/1 colorless Servo artifact creature token. - FilterControlledArtifactPermanent filter = new FilterControlledArtifactPermanent("a nontoken artifact you control"); - filter.add(Predicates.not(new TokenPredicate())); this.addAbility(new PutIntoGraveFromBattlefieldAllTriggeredAbility(new CreateTokenEffect(new ServoToken()), false, filter, false)); } diff --git a/Mage.Sets/src/mage/cards/s/SoldeviAdnate.java b/Mage.Sets/src/mage/cards/s/SoldeviAdnate.java index b4bf165e04d..0b725032f9b 100644 --- a/Mage.Sets/src/mage/cards/s/SoldeviAdnate.java +++ b/Mage.Sets/src/mage/cards/s/SoldeviAdnate.java @@ -33,7 +33,6 @@ import mage.Mana; import mage.ObjectColor; import mage.abilities.Ability; import mage.abilities.costs.common.SacrificeTargetCost; -import mage.abilities.costs.common.TapSourceCost; import mage.abilities.dynamicvalue.common.SacrificeCostConvertedMana; import mage.abilities.mana.DynamicManaAbility; import mage.cards.CardImpl; diff --git a/Mage.Sets/src/mage/cards/s/SolemnRecruit.java b/Mage.Sets/src/mage/cards/s/SolemnRecruit.java index f386813c24b..6f01ced58b3 100644 --- a/Mage.Sets/src/mage/cards/s/SolemnRecruit.java +++ b/Mage.Sets/src/mage/cards/s/SolemnRecruit.java @@ -29,7 +29,6 @@ package mage.cards.s; import java.util.UUID; import mage.MageInt; -import mage.abilities.TriggeredAbility; import mage.abilities.common.BeginningOfYourEndStepTriggeredAbility; import mage.abilities.condition.common.RevoltCondition; import mage.abilities.decorator.ConditionalTriggeredAbility; @@ -47,9 +46,6 @@ import mage.watchers.common.RevoltWatcher; */ public class SolemnRecruit extends CardImpl { - private static final String ruleText = "Revolt — At the beginning of your end step, if a permanent you controlled left the battlefield this turn, " - + "put a +1/+1 counter on {this}."; - public SolemnRecruit(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}{W}"); @@ -62,8 +58,14 @@ public class SolemnRecruit extends CardImpl { this.addAbility(DoubleStrikeAbility.getInstance()); // Revolt — At the beginning of your end step, if a permanent you controlled left the battlefield this turn, put a +1/+1 counter on Solemn Recruit. - TriggeredAbility ability = new BeginningOfYourEndStepTriggeredAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance()), false); - this.addAbility(new ConditionalTriggeredAbility(ability, RevoltCondition.getInstance(), ruleText), new RevoltWatcher()); + this.addAbility(new ConditionalTriggeredAbility( + new BeginningOfYourEndStepTriggeredAbility( + new AddCountersSourceEffect(CounterType.P1P1.createInstance()), + false + ), + RevoltCondition.getInstance(), + "Revolt — At the beginning of your end step, if a permanent you controlled left the battlefield this turn, put a +1/+1 counter on {this}." + ), new RevoltWatcher()); } public SolemnRecruit(final SolemnRecruit card) { diff --git a/Mage.Sets/src/mage/cards/s/SoulChanneling.java b/Mage.Sets/src/mage/cards/s/SoulChanneling.java index fa8af93a404..94d2a476c03 100644 --- a/Mage.Sets/src/mage/cards/s/SoulChanneling.java +++ b/Mage.Sets/src/mage/cards/s/SoulChanneling.java @@ -35,8 +35,6 @@ import mage.abilities.effects.common.AttachEffect; import mage.abilities.keyword.EnchantAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.constants.CardType; -import mage.constants.Outcome; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; import mage.abilities.common.SimpleActivatedAbility; diff --git a/Mage.Sets/src/mage/cards/s/SoulExchange.java b/Mage.Sets/src/mage/cards/s/SoulExchange.java index fcb574390c6..5544de14447 100644 --- a/Mage.Sets/src/mage/cards/s/SoulExchange.java +++ b/Mage.Sets/src/mage/cards/s/SoulExchange.java @@ -33,7 +33,6 @@ import mage.abilities.costs.Cost; import mage.abilities.costs.common.ExileTargetCost; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.ReturnFromGraveyardToBattlefieldTargetEffect; -import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; diff --git a/Mage.Sets/src/mage/cards/s/SpectralSearchlight.java b/Mage.Sets/src/mage/cards/s/SpectralSearchlight.java new file mode 100644 index 00000000000..8acd4b732ed --- /dev/null +++ b/Mage.Sets/src/mage/cards/s/SpectralSearchlight.java @@ -0,0 +1,69 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.s; + +import java.util.UUID; +import mage.abilities.Ability; +import mage.abilities.costs.common.TapSourceCost; +import mage.abilities.effects.common.AddManaOfAnyColorToManaPoolTargetPlayerEffect; +import mage.abilities.effects.common.ChoosePlayerEffect; +import mage.abilities.effects.common.ManaEffect; +import mage.abilities.mana.SimpleManaAbility; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.constants.Outcome; +import mage.constants.Zone; + +/** + * + * @author Galatolol + */ +public class SpectralSearchlight extends CardImpl { + + public SpectralSearchlight(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{3}"); + + // {T}: Choose a player. That player adds one mana of any color he or she chooses to his or her mana pool. + ManaEffect effect = new AddManaOfAnyColorToManaPoolTargetPlayerEffect("chosen player"); + effect.setText("That player adds one mana of any color he or she chooses to his or her mana pool"); + Ability ability = new SimpleManaAbility(Zone.BATTLEFIELD, effect, new TapSourceCost()); + // choosing player as first effect, before adding mana effect + ability.getEffects().add(0, new ChoosePlayerEffect(Outcome.PutManaInPool)); + this.addAbility(ability); + } + + public SpectralSearchlight(final SpectralSearchlight card) { + super(card); + } + + @Override + public SpectralSearchlight copy() { + return new SpectralSearchlight(this); + } +} diff --git a/Mage.Sets/src/mage/cards/s/SphereOfTheSuns.java b/Mage.Sets/src/mage/cards/s/SphereOfTheSuns.java index a45157cfd63..f98a1421b10 100644 --- a/Mage.Sets/src/mage/cards/s/SphereOfTheSuns.java +++ b/Mage.Sets/src/mage/cards/s/SphereOfTheSuns.java @@ -27,7 +27,7 @@ */ package mage.cards.s; -import mage.constants.CardType; +import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTappedAbility; import mage.abilities.costs.common.RemoveCountersSourceCost; @@ -36,24 +36,23 @@ import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.abilities.mana.AnyColorManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.constants.CardType; import mage.counters.CounterType; -import java.util.UUID; - /** * * @author North, Loki, noxx */ public class SphereOfTheSuns extends CardImpl { - private static final String ruleText = "Sphere of the Suns enters the battlefield tapped and with three charge counters on it."; - + private static final String ruleText = "{this} enters the battlefield tapped and with three charge counters on it."; + public SphereOfTheSuns(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT},"{2}"); + super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{2}"); // Sphere of the Suns enters the battlefield tapped and with three charge counters on it. Ability ability = new EntersBattlefieldTappedAbility(ruleText); - ((EntersBattlefieldEffect)ability.getEffects().get(0)).addEffect(new AddCountersSourceEffect(CounterType.CHARGE.createInstance(3))); + ((EntersBattlefieldEffect) ability.getEffects().get(0)).addEffect(new AddCountersSourceEffect(CounterType.CHARGE.createInstance(3))); this.addAbility(ability); RemoveCountersSourceCost removeCounterCost = new RemoveCountersSourceCost(CounterType.CHARGE.createInstance()); diff --git a/Mage.Sets/src/mage/cards/s/StasisSnare.java b/Mage.Sets/src/mage/cards/s/StasisSnare.java index 7e7bd31f7f9..a0272ed4c29 100644 --- a/Mage.Sets/src/mage/cards/s/StasisSnare.java +++ b/Mage.Sets/src/mage/cards/s/StasisSnare.java @@ -31,22 +31,16 @@ import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.delayed.OnLeaveReturnExiledToBattlefieldAbility; -import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.CreateDelayedTriggeredAbilityEffect; -import mage.abilities.effects.common.ExileTargetEffect; import mage.abilities.effects.common.ExileUntilSourceLeavesEffect; import mage.abilities.keyword.FlashAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Outcome; import mage.constants.TargetController; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.permanent.ControllerPredicate; -import mage.game.Game; -import mage.game.permanent.Permanent; import mage.target.common.TargetCreaturePermanent; -import mage.util.CardUtil; /** * diff --git a/Mage.Sets/src/mage/cards/s/StrikeTeamCommando.java b/Mage.Sets/src/mage/cards/s/StrikeTeamCommando.java index d08d7c262b0..f3d05847f45 100644 --- a/Mage.Sets/src/mage/cards/s/StrikeTeamCommando.java +++ b/Mage.Sets/src/mage/cards/s/StrikeTeamCommando.java @@ -37,7 +37,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.common.FilterArtifactPermanent; -import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.AbilityPredicate; import mage.target.common.TargetArtifactPermanent; diff --git a/Mage.Sets/src/mage/cards/s/SunClasp.java b/Mage.Sets/src/mage/cards/s/SunClasp.java new file mode 100644 index 00000000000..7438cfb9830 --- /dev/null +++ b/Mage.Sets/src/mage/cards/s/SunClasp.java @@ -0,0 +1,112 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.s; + +import java.util.UUID; + +import mage.abilities.common.SimpleActivatedAbility; +import mage.abilities.common.SimpleStaticAbility; +import mage.abilities.costs.mana.ColoredManaCost; +import mage.abilities.effects.OneShotEffect; +import mage.abilities.effects.common.continuous.BoostEnchantedEffect; +import mage.constants.*; +import mage.game.Game; +import mage.game.permanent.Permanent; +import mage.players.Player; +import mage.target.common.TargetCreaturePermanent; +import mage.abilities.Ability; +import mage.abilities.effects.common.AttachEffect; +import mage.target.TargetPermanent; +import mage.abilities.keyword.EnchantAbility; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; + +/** + * + * @author Galatolol + */ +public class SunClasp extends CardImpl { + + public SunClasp(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{W}"); + + this.subtype.add("Aura"); + + // Enchant creature + TargetPermanent auraTarget = new TargetCreaturePermanent(); + this.getSpellAbility().addTarget(auraTarget); + this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature)); + Ability ability = new EnchantAbility(auraTarget.getTargetName()); + this.addAbility(ability); + + // Enchanted creature gets +1/+3. + this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostEnchantedEffect(1, 3, Duration.WhileOnBattlefield))); + // {W}: Return enchanted creature to its owner's hand. + this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new SunClaspReturnEffect(), new ColoredManaCost(ColoredManaSymbol.W))); + } + + public SunClasp(final SunClasp card) { + super(card); + } + + @Override + public SunClasp copy() { + return new SunClasp(this); + } +} + +class SunClaspReturnEffect extends OneShotEffect { + + public SunClaspReturnEffect() { + super(Outcome.ReturnToHand); + staticText = "Return enchanted creature to its owner's hand"; + } + + public SunClaspReturnEffect(final mage.cards.s.SunClaspReturnEffect effect) { + super(effect); + } + + @Override + public mage.cards.s.SunClaspReturnEffect copy() { + return new mage.cards.s.SunClaspReturnEffect(this); + } + + @Override + public boolean apply(Game game, Ability source) { + Permanent permanent = (Permanent) game.getPermanentOrLKIBattlefield(source.getSourceId()); + Player controller = game.getPlayer(source.getControllerId()); + if (controller != null && permanent != null && permanent.getAttachedTo() != null) { + Permanent enchantedCreature = game.getPermanent(permanent.getAttachedTo()); + if (enchantedCreature != null) { + controller.moveCards(enchantedCreature, Zone.HAND, source, game); + } + return true; + } + return false; + } +} \ No newline at end of file diff --git a/Mage.Sets/src/mage/cards/s/SurrealMemoir.java b/Mage.Sets/src/mage/cards/s/SurrealMemoir.java index a6d3de96a0a..f2139852864 100644 --- a/Mage.Sets/src/mage/cards/s/SurrealMemoir.java +++ b/Mage.Sets/src/mage/cards/s/SurrealMemoir.java @@ -27,7 +27,6 @@ */ package mage.cards.s; -import java.util.Random; import java.util.UUID; import mage.constants.CardType; import mage.constants.Outcome; diff --git a/Mage.Sets/src/mage/cards/s/SwordsToPlowshares.java b/Mage.Sets/src/mage/cards/s/SwordsToPlowshares.java index d821b122739..447ddf7995b 100644 --- a/Mage.Sets/src/mage/cards/s/SwordsToPlowshares.java +++ b/Mage.Sets/src/mage/cards/s/SwordsToPlowshares.java @@ -27,7 +27,6 @@ */ package mage.cards.s; -import mage.abilities.effects.common.ExileTargetEffect; import mage.abilities.effects.common.SwordsToPlowsharesEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; @@ -43,13 +42,10 @@ import java.util.UUID; public class SwordsToPlowshares extends CardImpl { public SwordsToPlowshares(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{W}"); + super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{W}"); - - // Exile target creature. + // Exile target creature. Its controller gains life equal to its power. this.getSpellAbility().addTarget(new TargetCreaturePermanent()); - this.getSpellAbility().addEffect(new ExileTargetEffect()); - // Its controller gains life equal to its power. this.getSpellAbility().addEffect(new SwordsToPlowsharesEffect()); } diff --git a/Mage.Sets/src/mage/cards/t/Tatterkite.java b/Mage.Sets/src/mage/cards/t/Tatterkite.java index f1e2935353a..b5f27404e71 100644 --- a/Mage.Sets/src/mage/cards/t/Tatterkite.java +++ b/Mage.Sets/src/mage/cards/t/Tatterkite.java @@ -35,7 +35,6 @@ import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Duration; import mage.constants.Zone; /** diff --git a/Mage.Sets/src/mage/cards/t/TerrainGenerator.java b/Mage.Sets/src/mage/cards/t/TerrainGenerator.java index 69084a04be6..0b8e9dfa61d 100644 --- a/Mage.Sets/src/mage/cards/t/TerrainGenerator.java +++ b/Mage.Sets/src/mage/cards/t/TerrainGenerator.java @@ -32,24 +32,13 @@ import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.ManaCostsImpl; -import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.PutLandFromHandOntoBattlefieldEffect; import mage.abilities.mana.ColorlessManaAbility; -import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Outcome; import mage.constants.Zone; -import mage.filter.FilterCard; import mage.filter.common.FilterLandCard; -import mage.filter.predicate.Predicates; -import mage.filter.predicate.mageobject.CardTypePredicate; -import mage.filter.predicate.mageobject.SupertypePredicate; -import mage.game.Game; -import mage.game.permanent.Permanent; -import mage.players.Player; -import mage.target.common.TargetCardInHand; /** * diff --git a/Mage.Sets/src/mage/cards/t/TezzeretMasterOfMetal.java b/Mage.Sets/src/mage/cards/t/TezzeretMasterOfMetal.java index 07c43f7f38b..80d0c6f8f2d 100644 --- a/Mage.Sets/src/mage/cards/t/TezzeretMasterOfMetal.java +++ b/Mage.Sets/src/mage/cards/t/TezzeretMasterOfMetal.java @@ -1,156 +1,156 @@ -/* - * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of BetaSteward_at_googlemail.com. - */ -package mage.cards.t; - -import java.util.List; -import java.util.UUID; -import mage.abilities.Ability; -import mage.abilities.LoyaltyAbility; -import mage.abilities.common.PlanswalkerEntersWithLoyalityCountersAbility; -import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; -import mage.abilities.effects.ContinuousEffect; -import mage.abilities.effects.ContinuousEffectImpl; -import mage.abilities.effects.OneShotEffect; -import mage.abilities.effects.common.LoseLifeTargetEffect; -import mage.abilities.effects.common.RevealCardsFromLibraryUntilEffect; -import mage.cards.CardImpl; -import mage.cards.CardSetInfo; -import mage.constants.CardType; -import mage.constants.Duration; -import mage.constants.Layer; -import mage.constants.Outcome; -import mage.constants.SubLayer; -import mage.constants.Zone; -import mage.filter.FilterPermanent; -import mage.filter.common.FilterArtifactCard; -import mage.filter.common.FilterControlledArtifactPermanent; -import mage.filter.predicate.Predicates; -import mage.filter.predicate.mageobject.CardTypePredicate; -import mage.game.Game; -import mage.game.permanent.Permanent; -import mage.target.common.TargetOpponent; -import mage.target.targetpointer.FixedTarget; - -/** - * - * @author Styxo - */ -public class TezzeretMasterOfMetal extends CardImpl { - - public TezzeretMasterOfMetal(UUID ownerId, CardSetInfo setInfo) { - super(ownerId, setInfo, new CardType[]{CardType.PLANESWALKER}, "{4}{U}{B}"); - this.subtype.add("Tezzeret"); - - this.addAbility(new PlanswalkerEntersWithLoyalityCountersAbility(5)); - - // +1: Reveal cards from the top of your library until you reveal an artifact card. Put that card into your hand and the rest on the bottom of your library in a random order. - this.addAbility(new LoyaltyAbility(new RevealCardsFromLibraryUntilEffect(new FilterArtifactCard(), Zone.HAND, Zone.LIBRARY), 1)); - - // -3: Target opponent loses life equal to the number of artifacts you control. - Ability ability = new LoyaltyAbility(new LoseLifeTargetEffect(new PermanentsOnBattlefieldCount(new FilterControlledArtifactPermanent())), -3); - ability.addTarget(new TargetOpponent()); - this.addAbility(ability); - - // -8: Gain control of all artifacts and creatures target opponent controls. - ability = new LoyaltyAbility(new TezzeretMasterOfMetalEffect(), -8); - ability.addTarget(new TargetOpponent()); - this.addAbility(ability); - } - - public TezzeretMasterOfMetal(final TezzeretMasterOfMetal card) { - super(card); - } - - @Override - public TezzeretMasterOfMetal copy() { - return new TezzeretMasterOfMetal(this); - } -} - -class TezzeretMasterOfMetalEffect extends OneShotEffect { - - private static final FilterPermanent filter = new FilterPermanent("artifacts and creatures"); - - static { - filter.add(Predicates.or(new CardTypePredicate(CardType.CREATURE), new CardTypePredicate(CardType.ARTIFACT))); - } - - public TezzeretMasterOfMetalEffect() { - super(Outcome.GainControl); - this.staticText = "Gain control of all artifacts and creatures target opponent controls"; - } - - public TezzeretMasterOfMetalEffect(final TezzeretMasterOfMetalEffect effect) { - super(effect); - } - - @Override - public TezzeretMasterOfMetalEffect copy() { - return new TezzeretMasterOfMetalEffect(this); - } - - @Override - public boolean apply(Game game, Ability source) { - List permanents = game.getBattlefield().getAllActivePermanents(filter, targetPointer.getFirst(game, source), game); - for (Permanent permanent : permanents) { - ContinuousEffect effect = new TibaltTheFiendBloodedControlEffect(source.getControllerId()); - effect.setTargetPointer(new FixedTarget(permanent.getId())); - game.addEffect(effect, source); - } - return true; - } -} - -class TezzeretMasterOfMetalControlEffect extends ContinuousEffectImpl { - - private final UUID controllerId; - - public TezzeretMasterOfMetalControlEffect(UUID controllerId) { - super(Duration.EndOfGame, Layer.ControlChangingEffects_2, SubLayer.NA, Outcome.GainControl); - this.controllerId = controllerId; - } - - public TezzeretMasterOfMetalControlEffect(final TezzeretMasterOfMetalControlEffect effect) { - super(effect); - this.controllerId = effect.controllerId; - } - - @Override - public TezzeretMasterOfMetalControlEffect copy() { - return new TezzeretMasterOfMetalControlEffect(this); - } - - @Override - public boolean apply(Game game, Ability source) { - Permanent permanent = game.getPermanent(targetPointer.getFirst(game, source)); - if (permanent != null && controllerId != null) { - return permanent.changeControllerId(controllerId, game); - } - return false; - } -} +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.cards.t; + +import java.util.List; +import java.util.UUID; +import mage.abilities.Ability; +import mage.abilities.LoyaltyAbility; +import mage.abilities.common.PlanswalkerEntersWithLoyalityCountersAbility; +import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; +import mage.abilities.effects.ContinuousEffect; +import mage.abilities.effects.ContinuousEffectImpl; +import mage.abilities.effects.OneShotEffect; +import mage.abilities.effects.common.LoseLifeTargetEffect; +import mage.abilities.effects.common.RevealCardsFromLibraryUntilEffect; +import mage.cards.CardImpl; +import mage.cards.CardSetInfo; +import mage.constants.CardType; +import mage.constants.Duration; +import mage.constants.Layer; +import mage.constants.Outcome; +import mage.constants.SubLayer; +import mage.constants.Zone; +import mage.filter.FilterPermanent; +import mage.filter.common.FilterArtifactCard; +import mage.filter.common.FilterControlledArtifactPermanent; +import mage.filter.predicate.Predicates; +import mage.filter.predicate.mageobject.CardTypePredicate; +import mage.game.Game; +import mage.game.permanent.Permanent; +import mage.target.common.TargetOpponent; +import mage.target.targetpointer.FixedTarget; + +/** + * + * @author Styxo + */ +public class TezzeretMasterOfMetal extends CardImpl { + + public TezzeretMasterOfMetal(UUID ownerId, CardSetInfo setInfo) { + super(ownerId, setInfo, new CardType[]{CardType.PLANESWALKER}, "{4}{U}{B}"); + this.subtype.add("Tezzeret"); + + this.addAbility(new PlanswalkerEntersWithLoyalityCountersAbility(5)); + + // +1: Reveal cards from the top of your library until you reveal an artifact card. Put that card into your hand and the rest on the bottom of your library in a random order. + this.addAbility(new LoyaltyAbility(new RevealCardsFromLibraryUntilEffect(new FilterArtifactCard(), Zone.HAND, Zone.LIBRARY), 1)); + + // -3: Target opponent loses life equal to the number of artifacts you control. + Ability ability = new LoyaltyAbility(new LoseLifeTargetEffect(new PermanentsOnBattlefieldCount(new FilterControlledArtifactPermanent())), -3); + ability.addTarget(new TargetOpponent()); + this.addAbility(ability); + + // -8: Gain control of all artifacts and creatures target opponent controls. + ability = new LoyaltyAbility(new TezzeretMasterOfMetalEffect(), -8); + ability.addTarget(new TargetOpponent()); + this.addAbility(ability); + } + + public TezzeretMasterOfMetal(final TezzeretMasterOfMetal card) { + super(card); + } + + @Override + public TezzeretMasterOfMetal copy() { + return new TezzeretMasterOfMetal(this); + } +} + +class TezzeretMasterOfMetalEffect extends OneShotEffect { + + private static final FilterPermanent filter = new FilterPermanent("artifacts and creatures"); + + static { + filter.add(Predicates.or(new CardTypePredicate(CardType.CREATURE), new CardTypePredicate(CardType.ARTIFACT))); + } + + public TezzeretMasterOfMetalEffect() { + super(Outcome.GainControl); + this.staticText = "Gain control of all artifacts and creatures target opponent controls"; + } + + public TezzeretMasterOfMetalEffect(final TezzeretMasterOfMetalEffect effect) { + super(effect); + } + + @Override + public TezzeretMasterOfMetalEffect copy() { + return new TezzeretMasterOfMetalEffect(this); + } + + @Override + public boolean apply(Game game, Ability source) { + List permanents = game.getBattlefield().getAllActivePermanents(filter, targetPointer.getFirst(game, source), game); + for (Permanent permanent : permanents) { + ContinuousEffect effect = new TezzeretMasterOfMetalControlEffect(source.getControllerId()); + effect.setTargetPointer(new FixedTarget(permanent.getId())); + game.addEffect(effect, source); + } + return true; + } +} + +class TezzeretMasterOfMetalControlEffect extends ContinuousEffectImpl { + + private final UUID controllerId; + + public TezzeretMasterOfMetalControlEffect(UUID controllerId) { + super(Duration.EndOfGame, Layer.ControlChangingEffects_2, SubLayer.NA, Outcome.GainControl); + this.controllerId = controllerId; + } + + public TezzeretMasterOfMetalControlEffect(final TezzeretMasterOfMetalControlEffect effect) { + super(effect); + this.controllerId = effect.controllerId; + } + + @Override + public TezzeretMasterOfMetalControlEffect copy() { + return new TezzeretMasterOfMetalControlEffect(this); + } + + @Override + public boolean apply(Game game, Ability source) { + Permanent permanent = game.getPermanent(targetPointer.getFirst(game, source)); + if (permanent != null && controllerId != null) { + return permanent.changeControllerId(controllerId, game); + } + return false; + } +} diff --git a/Mage.Sets/src/mage/cards/t/TezzeretsBetrayal.java b/Mage.Sets/src/mage/cards/t/TezzeretsBetrayal.java index b8ac1a5fe67..cf01e06620b 100644 --- a/Mage.Sets/src/mage/cards/t/TezzeretsBetrayal.java +++ b/Mage.Sets/src/mage/cards/t/TezzeretsBetrayal.java @@ -28,23 +28,13 @@ package mage.cards.t; import java.util.UUID; -import mage.MageObject; -import mage.abilities.Ability; -import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.DestroyTargetEffect; -import mage.cards.Card; +import mage.abilities.effects.common.search.SearchLibraryGraveyardPutInHandEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.cards.Cards; -import mage.cards.CardsImpl; import mage.constants.CardType; -import mage.constants.Outcome; -import mage.constants.Zone; import mage.filter.FilterCard; import mage.filter.predicate.mageobject.NamePredicate; -import mage.game.Game; -import mage.players.Player; -import mage.target.TargetCard; import mage.target.common.TargetCreaturePermanent; /** @@ -53,14 +43,22 @@ import mage.target.common.TargetCreaturePermanent; */ public class TezzeretsBetrayal extends CardImpl { + private final static FilterCard filter = new FilterCard("Tezzeret, Master of Metal"); + + static { + filter.add(new NamePredicate("Tezzeret, Master of Metal")); + } + public TezzeretsBetrayal(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{U}{B}"); - // Destroy target creature. You may search your library and/or graveyard for a card named Tezzeret, Master of Metal, reveal it, and put it into your hand. - // If you search your library this way, shuffle it. + // Destroy target creature. getSpellAbility().addEffect(new DestroyTargetEffect()); getSpellAbility().addTarget(new TargetCreaturePermanent()); - getSpellAbility().addEffect(new TezzeretsBetrayalEffect()); + + // You may search your library and/or graveyard for a card named Tezzeret, Master of Metal, reveal it, and put it into your hand. + // If you search your library this way, shuffle it. + getSpellAbility().addEffect(new SearchLibraryGraveyardPutInHandEffect(filter)); } public TezzeretsBetrayal(final TezzeretsBetrayal card) { @@ -72,52 +70,3 @@ public class TezzeretsBetrayal extends CardImpl { return new TezzeretsBetrayal(this); } } - -class TezzeretsBetrayalEffect extends OneShotEffect { - - public TezzeretsBetrayalEffect() { - super(Outcome.Benefit); - staticText = "You may search your library and/or graveyard for a card named Tezzeret, Master of Metal, reveal it, and put it into your hand. " - + "If you search your library this way, shuffle it"; - } - - public TezzeretsBetrayalEffect(final TezzeretsBetrayalEffect effect) { - super(effect); - } - - @Override - public TezzeretsBetrayalEffect copy() { - return new TezzeretsBetrayalEffect(this); - } - - @Override - public boolean apply(Game game, Ability source) { - Player controller = game.getPlayer(source.getControllerId()); - MageObject sourceObject = source.getSourceObject(game); - if (controller != null && sourceObject != null && controller.chooseUse(outcome, "Search your library and/or graveyard for a card named Tezzeret, Master of Metal?", source, game)) { - //Search your library and graveyard - Cards allCards = new CardsImpl(); - boolean librarySearched = false; - if (controller.chooseUse(outcome, "Search also your library?", source, game)) { - librarySearched = true; - allCards.addAll(controller.getLibrary().getCardList()); - } - allCards.addAll(controller.getGraveyard()); - FilterCard filter = new FilterCard("a card named Tezzeret, Master of Metal"); - filter.add(new NamePredicate("Tezzeret, Master of Metal")); - TargetCard target = new TargetCard(0, 1, Zone.ALL, new FilterCard()); - if (controller.choose(outcome, allCards, target, game)) { - Card cardFound = game.getCard(target.getFirstTarget()); - if (cardFound != null) { - controller.revealCards(sourceObject.getIdName(), new CardsImpl(cardFound), game); - controller.moveCards(cardFound, Zone.HAND, source, game); - } - } - if (librarySearched) { - controller.shuffleLibrary(source, game); - } - return true; - } - return false; - } -} diff --git a/Mage.Sets/src/mage/cards/t/TimberpackWolf.java b/Mage.Sets/src/mage/cards/t/TimberpackWolf.java index 2fc39158191..a8f7ca7e8c7 100644 --- a/Mage.Sets/src/mage/cards/t/TimberpackWolf.java +++ b/Mage.Sets/src/mage/cards/t/TimberpackWolf.java @@ -29,7 +29,6 @@ package mage.cards.t; import java.util.UUID; -import mage.constants.CardType; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; diff --git a/Mage.Sets/src/mage/cards/t/TrophyMage.java b/Mage.Sets/src/mage/cards/t/TrophyMage.java index 6345d5c5d22..b313fd0894f 100644 --- a/Mage.Sets/src/mage/cards/t/TrophyMage.java +++ b/Mage.Sets/src/mage/cards/t/TrophyMage.java @@ -30,7 +30,6 @@ package mage.cards.t; import java.util.UUID; import mage.MageInt; import mage.abilities.common.EntersBattlefieldTriggeredAbility; -import mage.abilities.effects.SearchEffect; import mage.abilities.effects.common.search.SearchLibraryPutInHandEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; @@ -63,9 +62,7 @@ public class TrophyMage extends CardImpl { this.toughness = new MageInt(2); // When Trophy Mage enters the battlefield, you may search your library for an artifact card with converted mana cost 3, reveal it, put it into your hand, then shuffle your library. - TargetCardInLibrary target = new TargetCardInLibrary(0, 1, filter); - SearchEffect effect = new SearchLibraryPutInHandEffect(target, true, true); - this.addAbility(new EntersBattlefieldTriggeredAbility(effect, true)); + this.addAbility(new EntersBattlefieldTriggeredAbility(new SearchLibraryPutInHandEffect(new TargetCardInLibrary(0, 1, filter), true, true), true)); } public TrophyMage(final TrophyMage card) { diff --git a/Mage.Sets/src/mage/cards/u/UlvenwaldTracker.java b/Mage.Sets/src/mage/cards/u/UlvenwaldTracker.java index 0ceae40e3bd..414c3bf6d58 100644 --- a/Mage.Sets/src/mage/cards/u/UlvenwaldTracker.java +++ b/Mage.Sets/src/mage/cards/u/UlvenwaldTracker.java @@ -40,7 +40,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.AnotherTargetPredicate; -import mage.game.Game; import mage.target.Target; import mage.target.common.TargetControlledCreaturePermanent; import mage.target.common.TargetCreaturePermanent; diff --git a/Mage.Sets/src/mage/cards/v/VanishIntoMemory.java b/Mage.Sets/src/mage/cards/v/VanishIntoMemory.java index 67542662129..7a15df5e003 100644 --- a/Mage.Sets/src/mage/cards/v/VanishIntoMemory.java +++ b/Mage.Sets/src/mage/cards/v/VanishIntoMemory.java @@ -27,16 +27,21 @@ */ package mage.cards.v; +import java.util.HashSet; +import java.util.Set; import java.util.UUID; import mage.MageObject; -import mage.MageObjectReference; import mage.abilities.Ability; import mage.abilities.common.delayed.AtTheBeginOfYourNextUpkeepDelayedTriggeredAbility; +import mage.abilities.effects.ContinuousEffect; +import mage.abilities.effects.Effect; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.ReplacementEffectImpl; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; +import mage.cards.Cards; +import mage.cards.CardsImpl; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; @@ -49,6 +54,7 @@ import mage.game.events.GameEvent.EventType; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.common.TargetCreaturePermanent; +import mage.target.targetpointer.FixedTargets; /** * @@ -57,7 +63,7 @@ import mage.target.common.TargetCreaturePermanent; public class VanishIntoMemory extends CardImpl { public VanishIntoMemory(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{2}{W}{U}"); + super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{2}{W}{U}"); // Exile target creature. You draw cards equal to that creature's power. // At the beginning of your next upkeep, return that card to the battlefield under its owner's control. If you do, discard cards equal to that creature's toughness. @@ -79,7 +85,7 @@ class VanishIntoMemoryEffect extends OneShotEffect { public VanishIntoMemoryEffect() { super(Outcome.Detriment); - staticText = "Exile target creature. You draw cards equal to that creature's power. At the beginning of your next upkeep, return that card to the battlefield under its owner's control. If you do, discard cards equal to that creature's toughness."; + staticText = "Exile target creature. You draw cards equal to that creature's power. At the beginning of your next upkeep, return that card to the battlefield under its owner's control. If you do, discard cards equal to that creature's toughness"; } public VanishIntoMemoryEffect(final VanishIntoMemoryEffect effect) { @@ -89,20 +95,18 @@ class VanishIntoMemoryEffect extends OneShotEffect { @Override public boolean apply(Game game, Ability source) { Permanent permanent = game.getPermanent(source.getFirstTarget()); - Player you = game.getPlayer(source.getControllerId()); + Player controller = game.getPlayer(source.getControllerId()); MageObject sourceObject = game.getObject(source.getSourceId()); - if (permanent != null && sourceObject != null) { - if (permanent.moveToExile(source.getSourceId(), sourceObject.getIdName(), source.getSourceId(), game)) { - you.drawCards(permanent.getPower().getValue(), game); + if (controller != null && permanent != null && sourceObject != null) { + if (controller.moveCardsToExile(permanent, source, game, true, source.getSourceId(), sourceObject.getIdName())) { + controller.drawCards(permanent.getPower().getValue(), game); ExileZone exile = game.getExile().getExileZone(source.getSourceId()); // only if permanent is in exile (tokens would be stop to exist) if (exile != null && !exile.isEmpty()) { - Card card = game.getCard(permanent.getId()); - if (card != null) { - //create delayed triggered ability - game.addDelayedTriggeredAbility(new AtTheBeginOfYourNextUpkeepDelayedTriggeredAbility( - new VanishIntoMemoryReturnFromExileEffect(new MageObjectReference(card, game))), source); - } + //create delayed triggered ability + Effect effect = new VanishIntoMemoryReturnFromExileEffect(); + effect.setTargetPointer(new FixedTargets(exile, game)); + game.addDelayedTriggeredAbility(new AtTheBeginOfYourNextUpkeepDelayedTriggeredAbility(effect), source); } return true; } @@ -118,17 +122,13 @@ class VanishIntoMemoryEffect extends OneShotEffect { class VanishIntoMemoryReturnFromExileEffect extends OneShotEffect { - MageObjectReference objectToReturn; - - public VanishIntoMemoryReturnFromExileEffect(MageObjectReference objectToReturn) { + public VanishIntoMemoryReturnFromExileEffect() { super(Outcome.PutCardInPlay); - this.objectToReturn = objectToReturn; staticText = "return that card to the battlefield under its owner's control"; } public VanishIntoMemoryReturnFromExileEffect(final VanishIntoMemoryReturnFromExileEffect effect) { super(effect); - this.objectToReturn = effect.objectToReturn; } @Override @@ -138,31 +138,30 @@ class VanishIntoMemoryReturnFromExileEffect extends OneShotEffect { @Override public boolean apply(Game game, Ability source) { - Card card = game.getCard(objectToReturn.getSourceId()); - if (card != null && objectToReturn.refersTo(card, game)) { - Player owner = game.getPlayer(card.getOwnerId()); - if (owner != null) { - game.addEffect(new VanishIntoMemoryEntersBattlefieldEffect(objectToReturn), source); - owner.moveCards(card, Zone.BATTLEFIELD, source, game, false, false, true, null); - } + Cards cards = new CardsImpl(getTargetPointer().getTargets(game, source)); + Player controller = game.getPlayer(source.getControllerId()); + if (controller != null) { + Set cardsToBattlefield = new HashSet<>(); + cardsToBattlefield.addAll(cards.getCards(game)); + ContinuousEffect effect = new VanishIntoMemoryEntersBattlefieldEffect(); + effect.setTargetPointer(new FixedTargets(cards, game)); + game.addEffect(effect, source); + controller.moveCards(cardsToBattlefield, Zone.BATTLEFIELD, source, game, false, false, true, null); } + return true; } } class VanishIntoMemoryEntersBattlefieldEffect extends ReplacementEffectImpl { - MageObjectReference objectToReturn; - - public VanishIntoMemoryEntersBattlefieldEffect(MageObjectReference objectToReturn) { - super(Duration.Custom, Outcome.BoostCreature); - this.objectToReturn = objectToReturn; + public VanishIntoMemoryEntersBattlefieldEffect() { + super(Duration.EndOfTurn, Outcome.Discard); staticText = "discard cards equal to that creature's toughness."; } public VanishIntoMemoryEntersBattlefieldEffect(VanishIntoMemoryEntersBattlefieldEffect effect) { super(effect); - this.objectToReturn = effect.objectToReturn; } @Override @@ -172,10 +171,7 @@ class VanishIntoMemoryEntersBattlefieldEffect extends ReplacementEffectImpl { @Override public boolean applies(GameEvent event, Ability source, Game game) { - if (event.getType() == EventType.ENTERS_THE_BATTLEFIELD) { - return event.getTargetId().equals(objectToReturn.getSourceId()); - } - return false; + return getTargetPointer().getTargets(game, source).contains(event.getTargetId()); } @Override @@ -186,7 +182,6 @@ class VanishIntoMemoryEntersBattlefieldEffect extends ReplacementEffectImpl { if (you != null) { you.discard(permanent.getToughness().getValue(), false, source, game); } - discard(); // use only once } return false; } diff --git a/Mage.Sets/src/mage/cards/v/VengefulRebel.java b/Mage.Sets/src/mage/cards/v/VengefulRebel.java index 81f292df2f4..e92da1cd1fa 100644 --- a/Mage.Sets/src/mage/cards/v/VengefulRebel.java +++ b/Mage.Sets/src/mage/cards/v/VengefulRebel.java @@ -39,10 +39,7 @@ import mage.cards.CardSetInfo; import mage.constants.AbilityWord; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.TargetController; -import mage.filter.common.FilterCreaturePermanent; -import mage.filter.predicate.permanent.ControllerPredicate; -import mage.target.common.TargetCreaturePermanent; +import mage.target.common.TargetOpponentsCreaturePermanent; import mage.watchers.common.RevoltWatcher; /** @@ -51,12 +48,6 @@ import mage.watchers.common.RevoltWatcher; */ public class VengefulRebel extends CardImpl { - private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("creature an opponent controls"); - - static { - filter.add(new ControllerPredicate(TargetController.OPPONENT)); - } - public VengefulRebel(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{B}"); @@ -71,8 +62,9 @@ public class VengefulRebel extends CardImpl { new EntersBattlefieldTriggeredAbility(new BoostTargetEffect(-3, -3, Duration.EndOfTurn), false), RevoltCondition.getInstance(), "When {this} enters the battlefield, if a permanent you controlled left the battlefield this turn, " - + "target creature an opponent controls gets -3/-3 until end of turn"); - ability.addTarget(new TargetCreaturePermanent(filter)); + + "target creature an opponent controls gets -3/-3 until end of turn" + ); + ability.addTarget(new TargetOpponentsCreaturePermanent()); ability.setAbilityWord(AbilityWord.REVOLT); this.addAbility(ability, new RevoltWatcher()); } diff --git a/Mage.Sets/src/mage/cards/v/VerdantCrescendo.java b/Mage.Sets/src/mage/cards/v/VerdantCrescendo.java index 358a27529d4..2fe165a593d 100644 --- a/Mage.Sets/src/mage/cards/v/VerdantCrescendo.java +++ b/Mage.Sets/src/mage/cards/v/VerdantCrescendo.java @@ -28,23 +28,14 @@ package mage.cards.v; import java.util.UUID; -import mage.MageObject; -import mage.abilities.Ability; -import mage.abilities.effects.OneShotEffect; +import mage.abilities.effects.common.search.SearchLibraryGraveyardPutInHandEffect; import mage.abilities.effects.common.search.SearchLibraryPutInPlayEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; -import mage.cards.Cards; -import mage.cards.CardsImpl; import mage.constants.CardType; -import mage.constants.Outcome; -import mage.constants.Zone; import mage.filter.FilterCard; import mage.filter.common.FilterBasicLandCard; import mage.filter.predicate.mageobject.NamePredicate; -import mage.game.Game; -import mage.players.Player; -import mage.target.TargetCard; import mage.target.common.TargetCardInLibrary; /** @@ -53,14 +44,20 @@ import mage.target.common.TargetCardInLibrary; */ public class VerdantCrescendo extends CardImpl { + private final static FilterCard filter = new FilterCard("Nissa, Nature's Artisan"); + + static { + filter.add(new NamePredicate("Nissa, Nature's Artisan")); + } + public VerdantCrescendo(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{3}{G}"); + super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{G}"); // Search your library for a basic land card and put it onto the battlefield tapped. this.getSpellAbility().addEffect(new SearchLibraryPutInPlayEffect(new TargetCardInLibrary(new FilterBasicLandCard()), true, false)); // Search your library and graveyard for a card named Nissa, Nature's Artisan, reveal it, and put it into your hand. Then shuffle your library. - this.getSpellAbility().addEffect(new VerdantCrescendoEffect()); + this.getSpellAbility().addEffect(new SearchLibraryGraveyardPutInHandEffect(filter, true)); } public VerdantCrescendo(final VerdantCrescendo card) { @@ -72,45 +69,3 @@ public class VerdantCrescendo extends CardImpl { return new VerdantCrescendo(this); } } - -class VerdantCrescendoEffect extends OneShotEffect { - - public VerdantCrescendoEffect() { - super(Outcome.Benefit); - staticText = "Search your library and graveyard for a card named Nissa, Nature's Artisan, reveal it, and put it into your hand. Then shuffle your library"; - } - - public VerdantCrescendoEffect(final VerdantCrescendoEffect effect) { - super(effect); - } - - @Override - public VerdantCrescendoEffect copy() { - return new VerdantCrescendoEffect(this); - } - - @Override - public boolean apply(Game game, Ability source) { - Player controller = game.getPlayer(source.getControllerId()); - MageObject sourceObject = source.getSourceObject(game); - if (controller != null && sourceObject != null) { - //Search your library and graveyard - Cards allCards = new CardsImpl(); - allCards.addAll(controller.getLibrary().getCardList()); - allCards.addAll(controller.getGraveyard()); - FilterCard filter = new FilterCard("a card named Nissa, Nature's Artisan"); - filter.add(new NamePredicate("Nissa, Nature's Artisan")); - TargetCard target = new TargetCard(0, 1, Zone.ALL, filter); - if (controller.choose(outcome, allCards, target, game)) { - Cards cardFound = new CardsImpl(target.getTargets()); - if (!cardFound.isEmpty()) { - controller.revealCards(sourceObject.getIdName(), cardFound, game); - controller.moveCards(cardFound, Zone.HAND, source, game); - } - } - controller.shuffleLibrary(source, game); - return true; - } - return false; - } -} diff --git a/Mage.Sets/src/mage/cards/v/VesselOfVolatility.java b/Mage.Sets/src/mage/cards/v/VesselOfVolatility.java index d8bae15eac7..e94f41448de 100644 --- a/Mage.Sets/src/mage/cards/v/VesselOfVolatility.java +++ b/Mage.Sets/src/mage/cards/v/VesselOfVolatility.java @@ -30,10 +30,8 @@ package mage.cards.v; import java.util.UUID; import mage.Mana; import mage.abilities.Ability; -import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.SacrificeSourceCost; import mage.abilities.costs.mana.ManaCostsImpl; -import mage.abilities.effects.common.BasicManaEffect; import mage.abilities.mana.SimpleManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/v/VeteranMotorist.java b/Mage.Sets/src/mage/cards/v/VeteranMotorist.java index cae062aebd3..2f5cc2275b2 100644 --- a/Mage.Sets/src/mage/cards/v/VeteranMotorist.java +++ b/Mage.Sets/src/mage/cards/v/VeteranMotorist.java @@ -29,7 +29,6 @@ package mage.cards.v; import java.util.UUID; import mage.MageInt; -import mage.abilities.TriggeredAbilityImpl; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.effects.Effect; import mage.abilities.effects.common.CrewsVehicleSourceTriggeredAbility; @@ -39,10 +38,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.Zone; -import mage.game.Game; -import mage.game.events.GameEvent; -import mage.target.targetpointer.FixedTarget; /** * diff --git a/Mage.Sets/src/mage/cards/v/Vex.java b/Mage.Sets/src/mage/cards/v/Vex.java index fe99a6347cf..633ff381561 100644 --- a/Mage.Sets/src/mage/cards/v/Vex.java +++ b/Mage.Sets/src/mage/cards/v/Vex.java @@ -30,17 +30,12 @@ package mage.cards.v; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.effects.OneShotEffect; -import mage.abilities.effects.common.CounterTargetEffect; -import mage.abilities.effects.common.DrawCardSourceControllerEffect; -import mage.abilities.effects.common.DrawCardTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.game.Game; -import mage.game.stack.Spell; import mage.players.Player; -import mage.target.Target; import mage.target.TargetSpell; /** diff --git a/Mage.Sets/src/mage/cards/w/WalkingAtlas.java b/Mage.Sets/src/mage/cards/w/WalkingAtlas.java index 8e24c7fd032..39aeb0ed3be 100644 --- a/Mage.Sets/src/mage/cards/w/WalkingAtlas.java +++ b/Mage.Sets/src/mage/cards/w/WalkingAtlas.java @@ -30,7 +30,6 @@ package mage.cards.w; import java.util.UUID; import mage.MageInt; -import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.effects.common.PutLandFromHandOntoBattlefieldEffect; @@ -38,8 +37,6 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Zone; -import mage.filter.common.FilterLandCard; -import mage.target.common.TargetCardInHand; /** * diff --git a/Mage.Sets/src/mage/cards/w/Wargate.java b/Mage.Sets/src/mage/cards/w/Wargate.java index 2d1a8d406b7..c3b7b95d105 100644 --- a/Mage.Sets/src/mage/cards/w/Wargate.java +++ b/Mage.Sets/src/mage/cards/w/Wargate.java @@ -28,20 +28,11 @@ package mage.cards.w; import java.util.UUID; -import mage.abilities.Ability; -import mage.abilities.effects.OneShotEffect; -import mage.cards.Card; +import mage.abilities.effects.common.search.SearchLibraryWithLessCMCPutInPlayEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Outcome; -import mage.constants.Zone; -import mage.filter.Filter; import mage.filter.common.FilterPermanentCard; -import mage.filter.predicate.mageobject.ConvertedManaCostPredicate; -import mage.game.Game; -import mage.players.Player; -import mage.target.common.TargetCardInLibrary; /** * @@ -50,10 +41,10 @@ import mage.target.common.TargetCardInLibrary; public class Wargate extends CardImpl { public Wargate(UUID ownerId, CardSetInfo setInfo) { - super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{X}{G}{W}{U}"); + super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{X}{G}{W}{U}"); // Search your library for a permanent card with converted mana cost X or less, put it onto the battlefield, then shuffle your library. - this.getSpellAbility().addEffect(new WargateEffect()); + this.getSpellAbility().addEffect(new SearchLibraryWithLessCMCPutInPlayEffect(new FilterPermanentCard())); } public Wargate(final Wargate card) { @@ -65,43 +56,3 @@ public class Wargate extends CardImpl { return new Wargate(this); } } - -class WargateEffect extends OneShotEffect { - - WargateEffect() { - super(Outcome.PutCreatureInPlay); - staticText = "Search your library for a permanent card with converted mana cost X or less, put it onto the battlefield, then shuffle your library"; - } - - WargateEffect(final WargateEffect effect) { - super(effect); - } - - @Override - public boolean apply(Game game, Ability source) { - Player controller = game.getPlayer(source.getControllerId()); - if (controller == null) { - return false; - } - FilterPermanentCard filter = new FilterPermanentCard("permanent card with converted mana cost X or less"); - //Set the mana cost one higher to 'emulate' a less than or equal to comparison. - filter.add(new ConvertedManaCostPredicate(Filter.ComparisonType.LessThan, source.getManaCostsToPay().getX() + 1)); - TargetCardInLibrary target = new TargetCardInLibrary(filter); - if (controller.searchLibrary(target, game)) { - if (target.getTargets().size() > 0) { - Card card = controller.getLibrary().getCard(target.getFirstTarget(), game); - if (card != null) { - controller.moveCards(card, Zone.BATTLEFIELD, source, game); - } - } - } - controller.shuffleLibrary(source, game); - return false; - } - - @Override - public WargateEffect copy() { - return new WargateEffect(this); - } - -} diff --git a/Mage.Sets/src/mage/cards/w/WeldfastEngineer.java b/Mage.Sets/src/mage/cards/w/WeldfastEngineer.java index dcee8b309ec..6a02f410c8b 100644 --- a/Mage.Sets/src/mage/cards/w/WeldfastEngineer.java +++ b/Mage.Sets/src/mage/cards/w/WeldfastEngineer.java @@ -47,6 +47,12 @@ import mage.target.common.TargetControlledPermanent; */ public class WeldfastEngineer extends CardImpl { + private static final FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("artifact creature you control"); + + static { + filter.add(new CardTypePredicate(CardType.ARTIFACT)); + } + public WeldfastEngineer(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}{R}"); @@ -57,8 +63,6 @@ public class WeldfastEngineer extends CardImpl { // At the beginning of combat on your turn, target artifact creature you control gets +2/+0 until end of turn. Ability ability = new BeginningOfCombatTriggeredAbility(new BoostTargetEffect(2, 0, Duration.EndOfTurn), TargetController.YOU, false); - FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("artifact creature you control"); - filter.add(new CardTypePredicate(CardType.ARTIFACT)); ability.addTarget(new TargetControlledPermanent(filter)); this.addAbility(ability); } diff --git a/Mage.Sets/src/mage/cards/w/WharfInfiltrator.java b/Mage.Sets/src/mage/cards/w/WharfInfiltrator.java index 954cb405ad0..aca4497450c 100644 --- a/Mage.Sets/src/mage/cards/w/WharfInfiltrator.java +++ b/Mage.Sets/src/mage/cards/w/WharfInfiltrator.java @@ -46,7 +46,6 @@ import mage.game.Game; import mage.game.events.GameEvent; import mage.game.events.GameEvent.EventType; import mage.game.permanent.token.EldraziHorrorToken; -import mage.game.permanent.token.Token; /** * diff --git a/Mage.Sets/src/mage/cards/w/WhimsOfTheFates.java b/Mage.Sets/src/mage/cards/w/WhimsOfTheFates.java index 519463a1551..30f70be1adc 100644 --- a/Mage.Sets/src/mage/cards/w/WhimsOfTheFates.java +++ b/Mage.Sets/src/mage/cards/w/WhimsOfTheFates.java @@ -31,7 +31,6 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; -import java.util.Random; import java.util.Set; import java.util.UUID; import mage.abilities.Ability; diff --git a/Mage.Sets/src/mage/cards/w/WhirOfInvention.java b/Mage.Sets/src/mage/cards/w/WhirOfInvention.java index 632922dc5b9..bd06a0b67d3 100644 --- a/Mage.Sets/src/mage/cards/w/WhirOfInvention.java +++ b/Mage.Sets/src/mage/cards/w/WhirOfInvention.java @@ -28,22 +28,12 @@ package mage.cards.w; import java.util.UUID; -import mage.abilities.Ability; -import mage.abilities.effects.OneShotEffect; +import mage.abilities.effects.common.search.SearchLibraryWithLessCMCPutInPlayEffect; import mage.abilities.keyword.ImproviseAbility; -import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.Outcome; -import mage.constants.Zone; -import mage.filter.Filter; -import mage.filter.FilterCard; -import mage.filter.predicate.mageobject.CardTypePredicate; -import mage.filter.predicate.mageobject.ConvertedManaCostPredicate; -import mage.game.Game; -import mage.players.Player; -import mage.target.common.TargetCardInLibrary; +import mage.filter.common.FilterArtifactCard; /** * @@ -52,14 +42,13 @@ import mage.target.common.TargetCardInLibrary; public class WhirOfInvention extends CardImpl { public WhirOfInvention(UUID ownerId, CardSetInfo setInfo) { - super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{X}{U}{U}{U}"); - + super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{X}{U}{U}{U}"); // Improvise (Your artifacts can help cast this spell. Each artifact you tap after you're done activating mana abilities pays for {1}.) addAbility(new ImproviseAbility()); // Search your library for an artifact card with converted mana cost X or less, put it onto the battlefield, then shuffle your library. - this.getSpellAbility().addEffect(new WhirOfInventionSearchEffect()); + this.getSpellAbility().addEffect(new SearchLibraryWithLessCMCPutInPlayEffect(new FilterArtifactCard())); } public WhirOfInvention(final WhirOfInvention card) { @@ -71,48 +60,3 @@ public class WhirOfInvention extends CardImpl { return new WhirOfInvention(this); } } - -class WhirOfInventionSearchEffect extends OneShotEffect { - - WhirOfInventionSearchEffect() { - super(Outcome.PutCardInPlay); - staticText = "Search your library for an artifact card with converted mana cost X or less, put it onto the battlefield, then shuffle your library"; - } - - WhirOfInventionSearchEffect(final WhirOfInventionSearchEffect effect) { - super(effect); - } - - @Override - public boolean apply(Game game, Ability source) { - Player player = game.getPlayer(source.getControllerId()); - Card sourceCard = game.getCard(source.getSourceId()); - if (player == null || sourceCard == null) { - return false; - } - int xCost = source.getManaCostsToPay().getX(); - FilterCard filter = new FilterCard(new StringBuilder("artifact card with converted mana cost ").append(xCost).append(" or less").toString()); - filter.add(new CardTypePredicate(CardType.ARTIFACT)); - //Set the mana cost one higher to 'emulate' a less than or equal to comparison. - filter.add(new ConvertedManaCostPredicate(Filter.ComparisonType.LessThan, xCost + 1)); - TargetCardInLibrary target = new TargetCardInLibrary(0, 1, filter); - if (player.searchLibrary(target, game)) { - if (target.getTargets().size() > 0) { - Card card = player.getLibrary().getCard(target.getFirstTarget(), game); - if (card != null) { - game.informPlayers(new StringBuilder(sourceCard.getName()).append(": Put ").append(card.getName()).append(" onto the battlefield").toString()); - card.putOntoBattlefield(game, Zone.LIBRARY, source.getSourceId(), source.getControllerId()); - } - } - player.shuffleLibrary(source, game); - return true; - } - player.shuffleLibrary(source, game); - return false; - } - - @Override - public WhirOfInventionSearchEffect copy() { - return new WhirOfInventionSearchEffect(this); - } -} diff --git a/Mage.Sets/src/mage/cards/w/WildSwing.java b/Mage.Sets/src/mage/cards/w/WildSwing.java index 2698324a39c..7127ad03a34 100644 --- a/Mage.Sets/src/mage/cards/w/WildSwing.java +++ b/Mage.Sets/src/mage/cards/w/WildSwing.java @@ -27,7 +27,6 @@ */ package mage.cards.w; -import java.util.Random; import java.util.UUID; import mage.MageObject; import mage.abilities.Ability; diff --git a/Mage.Sets/src/mage/cards/w/WindingConstrictor.java b/Mage.Sets/src/mage/cards/w/WindingConstrictor.java index a8d5f015610..5d649a3cca6 100644 --- a/Mage.Sets/src/mage/cards/w/WindingConstrictor.java +++ b/Mage.Sets/src/mage/cards/w/WindingConstrictor.java @@ -56,9 +56,10 @@ public class WindingConstrictor extends CardImpl { this.power = new MageInt(2); this.toughness = new MageInt(3); - // If one or more counters would be placed on an artifact or creature you control, that many of those counters plus one are placed on that permanent instead. + // If one or more counters would be placed on an artifact or creature you control, that many plus one of each of those kinds of counters are placed on that permanent instead. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new WindingConstrictorPermanentEffect())); - // If you would get one or more counters, you get that many of those counters plus one instead. + + // If you would get one or more counters, you get that many plus one of each of those kinds of counters instead. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new WindingConstrictorPlayerEffect())); } @@ -76,7 +77,8 @@ class WindingConstrictorPermanentEffect extends ReplacementEffectImpl { WindingConstrictorPermanentEffect() { super(Duration.WhileOnBattlefield, Outcome.BoostCreature, false); - staticText = "If one or more counters would be placed on an artifact or creature you control, that many of those counters plus one are placed on that permanent instead"; + staticText = "If one or more counters would be placed on an artifact or creature you control, " + + "that many plus one of each of those kinds of counters are placed on that permanent instead"; } WindingConstrictorPermanentEffect(final WindingConstrictorPermanentEffect effect) { @@ -120,7 +122,7 @@ class WindingConstrictorPlayerEffect extends ReplacementEffectImpl { WindingConstrictorPlayerEffect() { super(Duration.WhileOnBattlefield, Outcome.BoostCreature, false); - staticText = "If you would get one or more counters, you get that many of those counters plus one instead"; + staticText = "If you would get one or more counters, you get that many plus one of each of those kinds of counters instead"; } WindingConstrictorPlayerEffect(final WindingConstrictorPlayerEffect effect) { diff --git a/Mage.Sets/src/mage/cards/w/WispweaverAngel.java b/Mage.Sets/src/mage/cards/w/WispweaverAngel.java index d2136081efc..780763cf90f 100644 --- a/Mage.Sets/src/mage/cards/w/WispweaverAngel.java +++ b/Mage.Sets/src/mage/cards/w/WispweaverAngel.java @@ -37,7 +37,6 @@ import mage.abilities.effects.common.ExileTargetForSourceEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.Card; import mage.cards.CardImpl; -import mage.cards.CardSetInfo; import mage.cards.Cards; import mage.cards.CardsImpl; import mage.cards.CardSetInfo; diff --git a/Mage.Sets/src/mage/cards/w/WoodlandSleuth.java b/Mage.Sets/src/mage/cards/w/WoodlandSleuth.java index c53f5874555..c2f58a76bee 100644 --- a/Mage.Sets/src/mage/cards/w/WoodlandSleuth.java +++ b/Mage.Sets/src/mage/cards/w/WoodlandSleuth.java @@ -27,7 +27,6 @@ */ package mage.cards.w; -import java.util.Random; import java.util.UUID; import mage.constants.CardType; import mage.constants.Outcome; diff --git a/Mage.Sets/src/mage/cards/w/Wrangle.java b/Mage.Sets/src/mage/cards/w/Wrangle.java index 81c3499cfa1..9837a6c5153 100644 --- a/Mage.Sets/src/mage/cards/w/Wrangle.java +++ b/Mage.Sets/src/mage/cards/w/Wrangle.java @@ -51,7 +51,7 @@ public class Wrangle extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("creature with power 4 or less"); static { - filter.add(new PowerPredicate(ComparisonType.LessThan, 4)); + filter.add(new PowerPredicate(ComparisonType.LessThan, 5)); } public Wrangle(UUID ownerId, CardSetInfo setInfo) { diff --git a/Mage.Sets/src/mage/cards/y/YWing.java b/Mage.Sets/src/mage/cards/y/YWing.java index b1474a3e3d0..16fb13ac866 100644 --- a/Mage.Sets/src/mage/cards/y/YWing.java +++ b/Mage.Sets/src/mage/cards/y/YWing.java @@ -38,10 +38,6 @@ import mage.abilities.keyword.SpaceflightAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; -import mage.constants.TargetController; -import mage.filter.common.FilterCreaturePermanent; -import mage.filter.predicate.permanent.ControllerPredicate; -import mage.target.common.TargetCreaturePermanent; import mage.target.common.TargetOpponentsCreaturePermanent; /** diff --git a/Mage.Sets/src/mage/cards/y/YahenniUndyingPartisan.java b/Mage.Sets/src/mage/cards/y/YahenniUndyingPartisan.java index a5075b0f952..f1a38f4a96e 100644 --- a/Mage.Sets/src/mage/cards/y/YahenniUndyingPartisan.java +++ b/Mage.Sets/src/mage/cards/y/YahenniUndyingPartisan.java @@ -40,13 +40,11 @@ import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; -import mage.constants.TargetController; import mage.constants.Zone; import mage.counters.CounterType; import mage.filter.common.FilterControlledCreaturePermanent; -import mage.filter.common.FilterCreaturePermanent; +import mage.filter.common.FilterOpponentsCreaturePermanent; import mage.filter.predicate.permanent.AnotherPredicate; -import mage.filter.predicate.permanent.ControllerPredicate; import mage.target.common.TargetControlledPermanent; /** @@ -55,15 +53,12 @@ import mage.target.common.TargetControlledPermanent; */ public class YahenniUndyingPartisan extends CardImpl { - private static final FilterCreaturePermanent opponentFilter = new FilterCreaturePermanent("a creature an opponent controls"); - private static final FilterControlledCreaturePermanent ownFilter = new FilterControlledCreaturePermanent("another creature"); + private static final FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("another creature"); static { - opponentFilter.add(new ControllerPredicate(TargetController.OPPONENT)); - ownFilter.add(new AnotherPredicate()); + filter.add(new AnotherPredicate()); } - public YahenniUndyingPartisan(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{B}"); @@ -77,11 +72,14 @@ public class YahenniUndyingPartisan extends CardImpl { this.addAbility(HasteAbility.getInstance()); // Whenever a creature an opponent controls dies, put a +1/+1 counter on Yahenni, Undying Partisan. - this.addAbility(new DiesCreatureTriggeredAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance()), false, opponentFilter)); + this.addAbility(new DiesCreatureTriggeredAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance()), false, new FilterOpponentsCreaturePermanent())); // Sacrifice another creature: Yahenni gains indestructible until end of turn. - this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new GainAbilitySourceEffect(IndestructibleAbility.getInstance(), Duration.EndOfTurn), - new SacrificeTargetCost(new TargetControlledPermanent(ownFilter)))); + this.addAbility(new SimpleActivatedAbility( + Zone.BATTLEFIELD, + new GainAbilitySourceEffect(IndestructibleAbility.getInstance(), Duration.EndOfTurn), + new SacrificeTargetCost(new TargetControlledPermanent(filter))) + ); } public YahenniUndyingPartisan(final YahenniUndyingPartisan card) { diff --git a/Mage.Sets/src/mage/sets/AetherRevolt.java b/Mage.Sets/src/mage/sets/AetherRevolt.java index d1d810f1701..d811d902cb0 100644 --- a/Mage.Sets/src/mage/sets/AetherRevolt.java +++ b/Mage.Sets/src/mage/sets/AetherRevolt.java @@ -53,6 +53,7 @@ public class AetherRevolt extends ExpansionSet { private AetherRevolt() { super("Aether Revolt", "AER", ExpansionSet.buildDate(2017, 1, 20), SetType.EXPANSION); this.blockName = "Kaladesh"; + this.parentSet = Kaladesh.getInstance(); this.hasBoosters = true; this.hasBasicLands = false; this.numBoosterLands = 1; @@ -62,7 +63,6 @@ public class AetherRevolt extends ExpansionSet { this.ratioBoosterMythic = 8; this.maxCardNumberInBooster = 184; this.ratioBoosterSpecialLand = 144; - this.parentSet = Kaladesh.getInstance(); cards.add(new SetCardInfo("Aegis Automaton", 141, Rarity.COMMON, mage.cards.a.AegisAutomaton.class)); cards.add(new SetCardInfo("Aerial Modification", 1, Rarity.UNCOMMON, mage.cards.a.AerialModification.class)); cards.add(new SetCardInfo("Aeronaut Admiral", 2, Rarity.UNCOMMON, mage.cards.a.AeronautAdmiral.class)); diff --git a/Mage.Sets/src/mage/sets/Conspiracy.java b/Mage.Sets/src/mage/sets/Conspiracy.java index c52166602cc..316e0f57c7a 100644 --- a/Mage.Sets/src/mage/sets/Conspiracy.java +++ b/Mage.Sets/src/mage/sets/Conspiracy.java @@ -194,6 +194,7 @@ public class Conspiracy extends ExpansionSet { cards.add(new SetCardInfo("Sky Spirit", 192, Rarity.UNCOMMON, mage.cards.s.SkySpirit.class)); cards.add(new SetCardInfo("Smallpox", 125, Rarity.UNCOMMON, mage.cards.s.Smallpox.class)); cards.add(new SetCardInfo("Soulcatcher", 82, Rarity.UNCOMMON, mage.cards.s.Soulcatcher.class)); + cards.add(new SetCardInfo("Spectral Searchlight", 205, Rarity.UNCOMMON, mage.cards.s.SpectralSearchlight.class)); cards.add(new SetCardInfo("Spiritmonger", 193, Rarity.RARE, mage.cards.s.Spiritmonger.class)); cards.add(new SetCardInfo("Split Decision", 25, Rarity.UNCOMMON, mage.cards.s.SplitDecision.class)); cards.add(new SetCardInfo("Spontaneous Combustion", 194, Rarity.UNCOMMON, mage.cards.s.SpontaneousCombustion.class)); diff --git a/Mage.Sets/src/mage/sets/EldritchMoon.java b/Mage.Sets/src/mage/sets/EldritchMoon.java index c7a39754b24..7c6fee0dcb0 100644 --- a/Mage.Sets/src/mage/sets/EldritchMoon.java +++ b/Mage.Sets/src/mage/sets/EldritchMoon.java @@ -46,14 +46,15 @@ public class EldritchMoon extends ExpansionSet { private EldritchMoon() { super("Eldritch Moon", "EMN", ExpansionSet.buildDate(2016, 7, 22), SetType.EXPANSION); this.blockName = "Shadows over Innistrad"; + this.parentSet = ShadowsOverInnistrad.getInstance(); this.hasBoosters = true; + this.hasBasicLands = false; this.numBoosterLands = 1; this.numBoosterCommon = 9; this.numBoosterUncommon = 3; this.numBoosterRare = 1; this.ratioBoosterMythic = 8; this.numBoosterDoubleFaced = 1; - this.parentSet = ShadowsOverInnistrad.getInstance(); cards.add(new SetCardInfo("Abandon Reason", 115, Rarity.UNCOMMON, mage.cards.a.AbandonReason.class)); cards.add(new SetCardInfo("Abolisher of Bloodlines", 111, Rarity.RARE, mage.cards.a.AbolisherOfBloodlines.class)); cards.add(new SetCardInfo("Abundant Maw", 1, Rarity.UNCOMMON, mage.cards.a.AbundantMaw.class)); diff --git a/Mage.Sets/src/mage/sets/Invasion.java b/Mage.Sets/src/mage/sets/Invasion.java index ab3764fa8e4..2b3fd5476c9 100644 --- a/Mage.Sets/src/mage/sets/Invasion.java +++ b/Mage.Sets/src/mage/sets/Invasion.java @@ -71,6 +71,7 @@ public class Invasion extends ExpansionSet { cards.add(new SetCardInfo("Armored Guardian", 230, Rarity.RARE, mage.cards.a.ArmoredGuardian.class)); cards.add(new SetCardInfo("Artifact Mutation", 231, Rarity.RARE, mage.cards.a.ArtifactMutation.class)); cards.add(new SetCardInfo("Assault // Battery", 295, Rarity.UNCOMMON, mage.cards.a.AssaultBattery.class)); + cards.add(new SetCardInfo("Atalya, Samite Master", 4, Rarity.RARE, mage.cards.a.AtalyaSamiteMaster.class)); cards.add(new SetCardInfo("Aura Mutation", 232, Rarity.RARE, mage.cards.a.AuraMutation.class)); cards.add(new SetCardInfo("Aura Shards", 233, Rarity.UNCOMMON, mage.cards.a.AuraShards.class)); cards.add(new SetCardInfo("Backlash", 234, Rarity.UNCOMMON, mage.cards.b.Backlash.class)); diff --git a/Mage.Sets/src/mage/sets/Mirrodin.java b/Mage.Sets/src/mage/sets/Mirrodin.java index 99596573564..4536953e917 100644 --- a/Mage.Sets/src/mage/sets/Mirrodin.java +++ b/Mage.Sets/src/mage/sets/Mirrodin.java @@ -205,6 +205,7 @@ public class Mirrodin extends ExpansionSet { cards.add(new SetCardInfo("Psychic Membrane", 46, Rarity.UNCOMMON, mage.cards.p.PsychicMembrane.class)); cards.add(new SetCardInfo("Psychogenic Probe", 231, Rarity.RARE, mage.cards.p.PsychogenicProbe.class)); cards.add(new SetCardInfo("Pyrite Spellbomb", 232, Rarity.COMMON, mage.cards.p.PyriteSpellbomb.class)); + cards.add(new SetCardInfo("Quicksilver Elemental", 47, Rarity.RARE, mage.cards.q.QuicksilverElemental.class)); cards.add(new SetCardInfo("Raise the Alarm", 16, Rarity.COMMON, mage.cards.r.RaiseTheAlarm.class)); cards.add(new SetCardInfo("Razor Barrier", 17, Rarity.COMMON, mage.cards.r.RazorBarrier.class)); cards.add(new SetCardInfo("Regress", 48, Rarity.COMMON, mage.cards.r.Regress.class)); diff --git a/Mage.Sets/src/mage/sets/PlanarChaos.java b/Mage.Sets/src/mage/sets/PlanarChaos.java index c3ecc9c0b16..1d02a8a859c 100644 --- a/Mage.Sets/src/mage/sets/PlanarChaos.java +++ b/Mage.Sets/src/mage/sets/PlanarChaos.java @@ -59,6 +59,7 @@ public class PlanarChaos extends ExpansionSet { cards.add(new SetCardInfo("Akroma, Angel of Fury", 94, Rarity.RARE, mage.cards.a.AkromaAngelOfFury.class)); cards.add(new SetCardInfo("Ana Battlemage", 124, Rarity.UNCOMMON, mage.cards.a.AnaBattlemage.class)); cards.add(new SetCardInfo("Aquamorph Entity", 33, Rarity.COMMON, mage.cards.a.AquamorphEntity.class)); + cards.add(new SetCardInfo("Auramancer's Guise", 34, Rarity.UNCOMMON, mage.cards.a.AuramancersGuise.class)); cards.add(new SetCardInfo("Aven Riftwatcher", 1, Rarity.COMMON, mage.cards.a.AvenRiftwatcher.class)); cards.add(new SetCardInfo("Battering Sliver", 95, Rarity.COMMON, mage.cards.b.BatteringSliver.class)); cards.add(new SetCardInfo("Benalish Commander", 2, Rarity.RARE, mage.cards.b.BenalishCommander.class)); diff --git a/Mage.Sets/src/mage/sets/RavnicaCityOfGuilds.java b/Mage.Sets/src/mage/sets/RavnicaCityOfGuilds.java index be6a1d1e98a..a731b42901c 100644 --- a/Mage.Sets/src/mage/sets/RavnicaCityOfGuilds.java +++ b/Mage.Sets/src/mage/sets/RavnicaCityOfGuilds.java @@ -240,6 +240,7 @@ public class RavnicaCityOfGuilds extends ExpansionSet { cards.add(new SetCardInfo("Putrefy", 221, Rarity.UNCOMMON, mage.cards.p.Putrefy.class)); cards.add(new SetCardInfo("Rain of Embers", 138, Rarity.COMMON, mage.cards.r.RainOfEmbers.class)); cards.add(new SetCardInfo("Rally the Righteous", 222, Rarity.COMMON, mage.cards.r.RallyTheRighteous.class)); + cards.add(new SetCardInfo("Razia's Purification", 224, Rarity.RARE, mage.cards.r.RaziasPurification.class)); cards.add(new SetCardInfo("Razia, Boros Archangel", 223, Rarity.RARE, mage.cards.r.RaziaBorosArchangel.class)); cards.add(new SetCardInfo("Recollect", 178, Rarity.UNCOMMON, mage.cards.r.Recollect.class)); cards.add(new SetCardInfo("Remand", 63, Rarity.UNCOMMON, mage.cards.r.Remand.class)); @@ -274,6 +275,7 @@ public class RavnicaCityOfGuilds extends ExpansionSet { cards.add(new SetCardInfo("Smash", 143, Rarity.COMMON, mage.cards.s.Smash.class)); cards.add(new SetCardInfo("Snapping Drake", 64, Rarity.COMMON, mage.cards.s.SnappingDrake.class)); cards.add(new SetCardInfo("Sparkmage Apprentice", 144, Rarity.COMMON, mage.cards.s.SparkmageApprentice.class)); + cards.add(new SetCardInfo("Spectral Searchlight", 271, Rarity.UNCOMMON, mage.cards.s.SpectralSearchlight.class)); cards.add(new SetCardInfo("Stasis Cell", 66, Rarity.COMMON, mage.cards.s.StasisCell.class)); cards.add(new SetCardInfo("Stinkweed Imp", 107, Rarity.COMMON, mage.cards.s.StinkweedImp.class)); cards.add(new SetCardInfo("Stone-Seeder Hierophant", 184, Rarity.COMMON, mage.cards.s.StoneSeederHierophant.class)); diff --git a/Mage.Sets/src/mage/sets/Scourge.java b/Mage.Sets/src/mage/sets/Scourge.java index f10ac9d07cd..2a9229ac2c7 100644 --- a/Mage.Sets/src/mage/sets/Scourge.java +++ b/Mage.Sets/src/mage/sets/Scourge.java @@ -86,6 +86,7 @@ public class Scourge extends ExpansionSet { cards.add(new SetCardInfo("Decree of Savagery", 115, Rarity.RARE, mage.cards.d.DecreeOfSavagery.class)); cards.add(new SetCardInfo("Decree of Silence", 32, Rarity.RARE, mage.cards.d.DecreeOfSilence.class)); cards.add(new SetCardInfo("Dispersal Shield", 33, Rarity.COMMON, mage.cards.d.DispersalShield.class)); + cards.add(new SetCardInfo("Divergent Growth", 116, Rarity.COMMON, mage.cards.d.DivergentGrowth.class)); cards.add(new SetCardInfo("Dragon Breath", 86, Rarity.COMMON, mage.cards.d.DragonBreath.class)); cards.add(new SetCardInfo("Dragon Fangs", 117, Rarity.COMMON, mage.cards.d.DragonFangs.class)); cards.add(new SetCardInfo("Dragon Mage", 87, Rarity.RARE, mage.cards.d.DragonMage.class)); diff --git a/Mage.Sets/src/mage/sets/ShadowsOverInnistrad.java b/Mage.Sets/src/mage/sets/ShadowsOverInnistrad.java index dfdd6d227ac..0e3b120ccaa 100644 --- a/Mage.Sets/src/mage/sets/ShadowsOverInnistrad.java +++ b/Mage.Sets/src/mage/sets/ShadowsOverInnistrad.java @@ -58,6 +58,7 @@ public class ShadowsOverInnistrad extends ExpansionSet { super("Shadows over Innistrad", "SOI", ExpansionSet.buildDate(2016, 4, 8), SetType.EXPANSION); this.blockName = "Shadows over Innistrad"; this.hasBoosters = true; + this.hasBasicLands = true; this.numBoosterLands = 1; this.numBoosterCommon = 9; this.numBoosterUncommon = 3; diff --git a/Mage.Sets/src/mage/sets/UrzasDestiny.java b/Mage.Sets/src/mage/sets/UrzasDestiny.java index 2c21fe1f1e4..6dffaae719f 100644 --- a/Mage.Sets/src/mage/sets/UrzasDestiny.java +++ b/Mage.Sets/src/mage/sets/UrzasDestiny.java @@ -57,6 +57,7 @@ public class UrzasDestiny extends ExpansionSet { cards.add(new SetCardInfo("Academy Rector", 1, Rarity.RARE, mage.cards.a.AcademyRector.class)); cards.add(new SetCardInfo("Aether Sting", 76, Rarity.UNCOMMON, mage.cards.a.AetherSting.class)); cards.add(new SetCardInfo("Ancient Silverback", 101, Rarity.RARE, mage.cards.a.AncientSilverback.class)); + cards.add(new SetCardInfo("Apprentice Necromancer", 51, Rarity.RARE, mage.cards.a.ApprenticeNecromancer.class)); cards.add(new SetCardInfo("Attrition", 52, Rarity.RARE, mage.cards.a.Attrition.class)); cards.add(new SetCardInfo("Aura Thief", 26, Rarity.RARE, mage.cards.a.AuraThief.class)); cards.add(new SetCardInfo("Blizzard Elemental", 27, Rarity.RARE, mage.cards.b.BlizzardElemental.class)); @@ -71,6 +72,7 @@ public class UrzasDestiny extends ExpansionSet { cards.add(new SetCardInfo("Capashen Knight", 3, Rarity.COMMON, mage.cards.c.CapashenKnight.class)); cards.add(new SetCardInfo("Capashen Standard", 4, Rarity.COMMON, mage.cards.c.CapashenStandard.class)); cards.add(new SetCardInfo("Capashen Templar", 5, Rarity.COMMON, mage.cards.c.CapashenTemplar.class)); + cards.add(new SetCardInfo("Carnival of Souls", 55, Rarity.RARE, mage.cards.c.CarnivalOfSouls.class)); cards.add(new SetCardInfo("Colos Yearling", 79, Rarity.COMMON, mage.cards.c.ColosYearling.class)); cards.add(new SetCardInfo("Compost", 102, Rarity.UNCOMMON, mage.cards.c.Compost.class)); cards.add(new SetCardInfo("Covetous Dragon", 80, Rarity.RARE, mage.cards.c.CovetousDragon.class)); diff --git a/Mage.Sets/src/mage/sets/Visions.java b/Mage.Sets/src/mage/sets/Visions.java index 6623bc8e772..868a648f504 100644 --- a/Mage.Sets/src/mage/sets/Visions.java +++ b/Mage.Sets/src/mage/sets/Visions.java @@ -145,6 +145,7 @@ public class Visions extends ExpansionSet { cards.add(new SetCardInfo("Squandered Resources", 137, Rarity.RARE, mage.cards.s.SquanderedResources.class)); cards.add(new SetCardInfo("Stampeding Wildebeests", 71, Rarity.UNCOMMON, mage.cards.s.StampedingWildebeests.class)); cards.add(new SetCardInfo("Summer Bloom", 72, Rarity.UNCOMMON, mage.cards.s.SummerBloom.class)); + cards.add(new SetCardInfo("Sun Clasp", 121, Rarity.COMMON, mage.cards.s.SunClasp.class)); cards.add(new SetCardInfo("Suq'Ata Assassin", 19, Rarity.UNCOMMON, mage.cards.s.SuqAtaAssassin.class)); cards.add(new SetCardInfo("Suq'Ata Lancer", 96, Rarity.COMMON, mage.cards.s.SuqAtaLancer.class)); cards.add(new SetCardInfo("Talruum Champion", 97, Rarity.COMMON, mage.cards.t.TalruumChampion.class)); diff --git a/Mage.Stats/pom.xml b/Mage.Stats/pom.xml index 12091c9ccd1..395490b6a91 100644 --- a/Mage.Stats/pom.xml +++ b/Mage.Stats/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 org.mage diff --git a/Mage.Tests/pom.xml b/Mage.Tests/pom.xml index 2ea14d0ee4e..f01a540b853 100644 --- a/Mage.Tests/pom.xml +++ b/Mage.Tests/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 mage-tests diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/CascadeTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/CascadeTest.java index 4fe810f5736..f5aa2e45108 100644 --- a/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/CascadeTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/CascadeTest.java @@ -174,8 +174,8 @@ public class CascadeTest extends CardTestPlayerBase { // Choose one - You draw five cards and you lose 5 life; // or put an X/X black Demon creature token with flying onto the battlefield, where X is the number of cards in your hand as the token enters the battlefield. // Entwine {4} (Choose both if you pay the entwine cost.) - //addCard(Zone.LIBRARY, playerA, "Promise of Power", 10); - addCard(Zone.LIBRARY, playerA, "Silvercoat Lion", 2); + addCard(Zone.LIBRARY, playerA, "Promise of Power", 1); + // addCard(Zone.LIBRARY, playerA, "Silvercoat Lion", 2); addCard(Zone.BATTLEFIELD, playerA, "Plains", 3); addCard(Zone.BATTLEFIELD, playerA, "Forest", 3); diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/MeldTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/MeldTest.java index 8a1c5be48a2..234b489a2e0 100644 --- a/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/MeldTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/MeldTest.java @@ -127,11 +127,11 @@ public class MeldTest extends CardTestPlayerBase { // When you cast Bruna, the Fading Light, you may return target Angel or Human creature card from your graveyard to the battlefield. // Flying, Vigilance // (Melds with Gisela, the Broken Blade.) - addCard(Zone.HAND, playerA, "Bruna, the Fading Light"); // {5}{W}{W} + addCard(Zone.HAND, playerA, "Bruna, the Fading Light"); // Creature {5}{W}{W} 5/7 // Flying, First strike, Lifelink // At the beginning of your end step, if you both own and control Gisela, the Broken Blade and a // creature named Bruna, the Fading Light, exile them, then meld them into Brisela, Voice of Nightmares. - addCard(Zone.HAND, playerA, "Gisela, the Broken Blade"); // {2}{W}{W} + addCard(Zone.HAND, playerA, "Gisela, the Broken Blade"); // Creature {2}{W}{W} 4/3 // Brisela, Voice of Nightmares 9/10 // Flying, First strike, Vigilance, Lifelink // Your opponents can't cast spells with converted mana cost 3 or less. @@ -160,7 +160,7 @@ public class MeldTest extends CardTestPlayerBase { assertGraveyardCount(playerB, "Vanish into Memory", 1); assertPermanentCount(playerB, "Silvercoat Lion", 2); - assertHandCount(playerB, 0); + assertHandCount(playerB, 1); // discard 10 upkeep turn 6 ==> 0 + draw 1 at draw phase turn 6 } diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/TransformTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/TransformTest.java index 0aec7dc3634..f44e232307b 100644 --- a/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/TransformTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/cards/abilities/keywords/TransformTest.java @@ -27,7 +27,6 @@ */ package org.mage.test.cards.abilities.keywords; -import mage.abilities.keyword.IndestructibleAbility; import mage.constants.CardType; import mage.constants.PhaseStep; import mage.constants.Zone; diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/continuous/MetallicMiminTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/continuous/MetallicMiminTest.java new file mode 100644 index 00000000000..67c74b94e06 --- /dev/null +++ b/Mage.Tests/src/test/java/org/mage/test/cards/continuous/MetallicMiminTest.java @@ -0,0 +1,128 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package org.mage.test.cards.continuous; + +import mage.constants.PhaseStep; +import mage.constants.Zone; +import org.junit.Test; +import org.mage.test.serverside.base.CardTestPlayerBase; + +/** + * + * @author LevelX2 + */ +public class MetallicMiminTest extends CardTestPlayerBase { + + /** + * Additionally, if you play a Mimic naming, for example, "Dwarf", then if + * you play a second Mimic also naming "Dwarf", the second Mimic won't enter + * with a counter. Going by 616.2 in the Comp Rules, the second one should + * be getting a counter as long as you name the same type as the first one. + * + * 611.3c Continuous effects that modify characteristics of permanents do so + * simultaneously with the permanent entering the battlefield. They don’t + * wait until the permanent is on the battlefield and then change it. + * Because such effects apply as the permanent enters the battlefield, they + * are applied before determining whether the permanent will cause an + * ability to trigger when it enters the battlefield. # + * + * Example: A permanent with the static ability “All white creatures get + * +1/+1” is on the battlefield. A creature spell that would normally create + * a 1/1 white creature instead creates a 2/2 white creature. The creature + * doesn’t enter the battlefield as 1/1 and then change to 2/2. + * + */ + @Test + public void testMetallicMimic() { + addCard(Zone.BATTLEFIELD, playerA, "Forest", 4); + + // As Metallic Mimic enters the battlefield, choose a creature type. + // Metallic Mimic is the chosen type in addition to its other types. + // Each other creature you control of the chosen type enters the battlefield with an additional +1/+1 counter on it. + addCard(Zone.HAND, playerA, "Metallic Mimic", 2); // Creature {2} + + castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Metallic Mimic"); + setChoice(playerA, "Dwarf"); + castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Metallic Mimic"); + setChoice(playerA, "Dwarf"); + + setStopAt(1, PhaseStep.END_TURN); + execute(); + + assertPermanentCount(playerA, "Metallic Mimic", 2); + assertPowerToughness(playerA, "Metallic Mimic", 2, 1); + assertPowerToughness(playerA, "Metallic Mimic", 3, 2); + } + + @Test + public void testMetallicMimicBramblewoodParagon() { + addCard(Zone.BATTLEFIELD, playerA, "Forest", 2); + + // As Metallic Mimic enters the battlefield, choose a creature type. + // Metallic Mimic is the chosen type in addition to its other types. + // Each other creature you control of the chosen type enters the battlefield with an additional +1/+1 counter on it. + addCard(Zone.HAND, playerA, "Metallic Mimic", 2); // Creature {2} + + // Each other Warrior creature you control enters the battlefield with an additional +1/+1 counter on it. + // Each creature you control with a +1/+1 counter on it has trample. + addCard(Zone.BATTLEFIELD, playerA, "Bramblewood Paragon", 1); + + castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Metallic Mimic"); + setChoice(playerA, "Warrior"); + + setStopAt(1, PhaseStep.BEGIN_COMBAT); + execute(); + + assertPermanentCount(playerA, "Metallic Mimic", 1); + assertPowerToughness(playerA, "Metallic Mimic", 3, 2); + } + + @Test + public void testMetallicLasts() { + addCard(Zone.BATTLEFIELD, playerA, "Forest", 2); + + // As Metallic Mimic enters the battlefield, choose a creature type. + // Metallic Mimic is the chosen type in addition to its other types. + // Each other creature you control of the chosen type enters the battlefield with an additional +1/+1 counter on it. + addCard(Zone.HAND, playerA, "Metallic Mimic", 2); // Creature {2} + + // Flash (You may cast this spell any time you could cast an instant.) + // Each creature you control that's a Wolf or a Werewolf gets +1/+1 and has trample. + addCard(Zone.BATTLEFIELD, playerA, "Howlpack Resurgence", 1); + + castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Metallic Mimic"); + setChoice(playerA, "Wolf"); + + setStopAt(1, PhaseStep.BEGIN_COMBAT); + execute(); + + assertPermanentCount(playerA, "Metallic Mimic", 1); + assertPowerToughness(playerA, "Metallic Mimic", 3, 2); + } + +} diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/control/DebtOfLoyaltyTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/control/DebtOfLoyaltyTest.java index 9e1072e6eb0..1f0e244f09f 100644 --- a/Mage.Tests/src/test/java/org/mage/test/cards/control/DebtOfLoyaltyTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/cards/control/DebtOfLoyaltyTest.java @@ -27,7 +27,6 @@ */ package org.mage.test.cards.control; -import org.mage.test.cards.prevention.*; import mage.constants.PhaseStep; import mage.constants.Zone; import mage.game.permanent.Permanent; diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/copy/PhantasmalImageTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/copy/PhantasmalImageTest.java index c04f1da5341..2439033d1b2 100644 --- a/Mage.Tests/src/test/java/org/mage/test/cards/copy/PhantasmalImageTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/cards/copy/PhantasmalImageTest.java @@ -6,29 +6,10 @@ import mage.constants.PhaseStep; import mage.constants.Zone; import mage.game.permanent.Permanent; import org.junit.Assert; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; + import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/filters/IvoryGuardiansTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/filters/IvoryGuardiansTest.java index f805e9ca83d..22a0dcc2285 100644 --- a/Mage.Tests/src/test/java/org/mage/test/cards/filters/IvoryGuardiansTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/cards/filters/IvoryGuardiansTest.java @@ -2,8 +2,6 @@ package org.mage.test.cards.filters; import mage.constants.PhaseStep; import mage.constants.Zone; -import mage.game.permanent.Permanent; -import org.junit.Assert; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/mana/HarvesterDruidTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/mana/HarvesterDruidTest.java new file mode 100644 index 00000000000..48ce51cda9a --- /dev/null +++ b/Mage.Tests/src/test/java/org/mage/test/cards/mana/HarvesterDruidTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package org.mage.test.cards.mana; + +import mage.abilities.mana.ManaOptions; +import mage.constants.PhaseStep; +import mage.constants.Zone; +import org.junit.Assert; +import org.junit.Test; +import org.mage.test.serverside.base.CardTestPlayerBase; + +/** + * + * @author LevelX2 + */ +public class HarvesterDruidTest extends CardTestPlayerBase { + + @Test + public void testOneInstance() { + addCard(Zone.BATTLEFIELD, playerA, "Island", 1); + addCard(Zone.BATTLEFIELD, playerA, "Mountain", 1); + + // {T}: Add to your mana pool one mana of any color that a land you control could produce. + addCard(Zone.BATTLEFIELD, playerA, "Harvester Druid", 1); + + setStopAt(1, PhaseStep.PRECOMBAT_MAIN); + execute(); + + ManaOptions options = playerA.getAvailableManaTest(currentGame); + Assert.assertEquals("Player should be able to create 2 red and 1 blue mana", "{R}{R}{U}", options.get(0).toString()); + Assert.assertEquals("Player should be able to create 1 red and 3 blue mana", "{R}{U}{U}", options.get(1).toString()); + } + + @Test + public void testTwoInstances() { + addCard(Zone.BATTLEFIELD, playerA, "Island", 1); + addCard(Zone.BATTLEFIELD, playerA, "Mountain", 1); + + // {T}: Add to your mana pool one mana of any color that a land you control could produce. + addCard(Zone.BATTLEFIELD, playerA, "Harvester Druid", 2); + + setStopAt(1, PhaseStep.PRECOMBAT_MAIN); + execute(); + + ManaOptions options = playerA.getAvailableManaTest(currentGame); + Assert.assertEquals("Player should be able to create 3 red and 1 blue mana", "{R}{R}{R}{U}", options.get(0).toString()); + Assert.assertEquals("Player should be able to create 2 red and 2 blue mana", "{R}{R}{U}{U}", options.get(1).toString()); + Assert.assertEquals("Player should be able to create 2 red and 2 blue mana", "{R}{R}{U}{U}", options.get(2).toString()); + Assert.assertEquals("Player should be able to create 1 red and 3 blue mana", "{R}{U}{U}{U}", options.get(3).toString()); + } +} diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/mana/SylvokExplorerTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/mana/SylvokExplorerTest.java new file mode 100644 index 00000000000..be7cc9427ca --- /dev/null +++ b/Mage.Tests/src/test/java/org/mage/test/cards/mana/SylvokExplorerTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package org.mage.test.cards.mana; + +import mage.abilities.mana.ManaOptions; +import mage.constants.PhaseStep; +import mage.constants.Zone; +import org.junit.Assert; +import org.junit.Test; +import org.mage.test.serverside.base.CardTestPlayerBase; + +/** + * + * @author LevelX2 + */ +public class SylvokExplorerTest extends CardTestPlayerBase { + + /** + * java.lang.StackOverflowError at + * mage.filter.predicate.Predicates.and(Predicates.java:68) at + * mage.filter.FilterImpl.match(FilterImpl.java:62) at + * mage.filter.FilterPermanent.match(FilterPermanent.java:74) at + * mage.game.permanent.Battlefield.getActivePermanents(Battlefield.java:362) + * at + * mage.abilities.mana.AnyColorLandsProduceManaEffect.getManaTypes(AnyColorLandsProduceManaAbility.java:164) + * at + * mage.abilities.mana.AnyColorLandsProduceManaEffect.getNetMana(AnyColorLandsProduceManaAbility.java:181) + * at + * mage.abilities.mana.AnyColorLandsProduceManaAbility.getNetMana(AnyColorLandsProduceManaAbility.java:70) + * at + * mage.abilities.mana.AnyColorLandsProduceManaEffect.getManaTypes(AnyColorLandsProduceManaAbility.java:170) + * at + * mage.abilities.mana.AnyColorLandsProduceManaEffect.getNetMana(AnyColorLandsProduceManaAbility.java:181) + */ + @Test + public void testOneInstance() { + addCard(Zone.BATTLEFIELD, playerB, "Island", 1); + addCard(Zone.BATTLEFIELD, playerB, "Mountain", 1); + + // {T}: Add to your mana pool one mana of any color that a land an opponent controls could produce. + addCard(Zone.BATTLEFIELD, playerA, "Sylvok Explorer", 1); + addCard(Zone.BATTLEFIELD, playerA, "Plains", 1); + + setStopAt(1, PhaseStep.PRECOMBAT_MAIN); + execute(); + + ManaOptions options = playerA.getAvailableManaTest(currentGame); + Assert.assertEquals("Player should be able to create 1 red and 1 white mana", "{R}{W}", options.get(0).toString()); + Assert.assertEquals("Player should be able to create 1 blue and 1 white mana", "{U}{W}", options.get(1).toString()); + } + + @Test + public void testTwoInstances() { + addCard(Zone.BATTLEFIELD, playerB, "Exotic Orchard", 2); + + // {T}: Add to your mana pool one mana of any color that a land an opponent controls could produce. + addCard(Zone.BATTLEFIELD, playerA, "Sylvok Explorer", 2); + addCard(Zone.BATTLEFIELD, playerA, "Plains", 1); + + setStopAt(1, PhaseStep.PRECOMBAT_MAIN); + execute(); + + ManaOptions options = playerA.getAvailableManaTest(currentGame); + Assert.assertEquals("Player should be able to create 3 white mana", "{W}{W}{W}", options.get(0).toString()); + } +} diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/mana/VorinclexVoiceOfHungerTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/mana/VorinclexVoiceOfHungerTest.java index ea569b05f43..8b78d5dccd7 100644 --- a/Mage.Tests/src/test/java/org/mage/test/cards/mana/VorinclexVoiceOfHungerTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/cards/mana/VorinclexVoiceOfHungerTest.java @@ -29,6 +29,7 @@ package org.mage.test.cards.mana; import mage.constants.PhaseStep; import mage.constants.Zone; +import mage.counters.CounterType; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; @@ -62,4 +63,59 @@ public class VorinclexVoiceOfHungerTest extends CardTestPlayerBase { } + /** + * Vorinclex glitches with Gemstone Cavern + */ + @Test + public void testGemstoneCavern() { + // Trample + // Whenever you tap a land for mana, add one mana to your mana pool of any type that land produced. + // Whenever an opponent taps a land for mana, that land doesn't untap during its controller's next untap step. + addCard(Zone.BATTLEFIELD, playerB, "Vorinclex, Voice of Hunger", 1); // {6}{G}{G} + + // If Gemstone Caverns is in your opening hand and you're not playing first, you may begin the game with Gemstone Caverns on the battlefield with a luck counter on it. If you do, exile a card from your hand. + // {T}: Add {C} to your mana pool. If Gemstone Caverns has a luck counter on it, instead add one mana of any color to your mana pool. + addCard(Zone.HAND, playerB, "Gemstone Caverns", 1); + + addCard(Zone.HAND, playerB, "Silvercoat Lion", 2); + + activateManaAbility(2, PhaseStep.PRECOMBAT_MAIN, playerB, "{T}: Add"); + setChoice(playerB, "White"); + castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Silvercoat Lion"); + setStopAt(2, PhaseStep.BEGIN_COMBAT); + execute(); + + assertPermanentCount(playerB, "Gemstone Caverns", 1); + assertPermanentCount(playerB, "Silvercoat Lion", 1); + assertExileCount("Silvercoat Lion", 1); + assertTapped("Gemstone Caverns", true); + + } + + @Test + public void testCastWithGemstoneCavern() { + // Trample + // Whenever you tap a land for mana, add one mana to your mana pool of any type that land produced. + // Whenever an opponent taps a land for mana, that land doesn't untap during its controller's next untap step. + addCard(Zone.HAND, playerB, "Vorinclex, Voice of Hunger", 1); // {6}{G}{G} + addCard(Zone.BATTLEFIELD, playerB, "Forest", 7); + + // If Gemstone Caverns is in your opening hand and you're not playing first, you may begin the game with Gemstone Caverns on the battlefield with a luck counter on it. If you do, exile a card from your hand. + // {T}: Add {C} to your mana pool. If Gemstone Caverns has a luck counter on it, instead add one mana of any color to your mana pool. + addCard(Zone.HAND, playerB, "Gemstone Caverns", 1); + + addCard(Zone.HAND, playerB, "Silvercoat Lion", 2); + + activateManaAbility(2, PhaseStep.PRECOMBAT_MAIN, playerB, "{T}: Add"); + setChoice(playerB, "White"); + castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Vorinclex, Voice of Hunger"); + setStopAt(2, PhaseStep.BEGIN_COMBAT); + execute(); + + assertPermanentCount(playerB, "Gemstone Caverns", 1); + assertCounterCount("Gemstone Caverns", CounterType.LUCK, 1); + assertPermanentCount(playerB, "Vorinclex, Voice of Hunger", 1); + assertTapped("Gemstone Caverns", true); + + } } diff --git a/Mage.Tests/src/test/java/org/mage/test/cards/single/FlailingDrakeTest.java b/Mage.Tests/src/test/java/org/mage/test/cards/single/FlailingDrakeTest.java index a51c58a2c16..551a348123f 100644 --- a/Mage.Tests/src/test/java/org/mage/test/cards/single/FlailingDrakeTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/cards/single/FlailingDrakeTest.java @@ -9,47 +9,52 @@ import org.mage.test.serverside.base.CardTestPlayerBase; * * @author anonymous * - * Whenever Flailing Drake blocks or becomes blocked by a creature, that creature gets +1/+1 until end of turn. + * Whenever Flailing Drake blocks or becomes blocked by a creature, that + * creature gets +1/+1 until end of turn. */ public class FlailingDrakeTest extends CardTestPlayerBase { @Test public void testIncreaseBlocker() { - addCard(Zone.BATTLEFIELD, playerA, "Forest", 3); - addCard(Zone.BATTLEFIELD, playerA, "Island", 1); - addCard(Zone.BATTLEFIELD, playerA, "Flailing Drake", 1); + addCard(Zone.BATTLEFIELD, playerA, "Forest", 4); + // Flying + // Whenever Flailing Drake blocks or becomes blocked by a creature, that creature gets +1/+1 until end of turn. + addCard(Zone.BATTLEFIELD, playerA, "Flailing Drake", 1); // Creature {3}{G} 2/3 + + addCard(Zone.BATTLEFIELD, playerB, "Island", 4); + addCard(Zone.BATTLEFIELD, playerB, "Snapping Drake", 1); // Creature {3}{U} 3/2 + + castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Flailing Drake"); + castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Snapping Drake"); - addCard(Zone.BATTLEFIELD, playerB, "Forest", 3); - addCard(Zone.BATTLEFIELD, playerB, "Island", 3); - addCard(Zone.BATTLEFIELD, playerB, "Snapping Drake", 1); - attack(3, playerA, "Flailing Drake"); block(3, playerB, "Snapping Drake", "Flailing Drake"); setStopAt(3, PhaseStep.POSTCOMBAT_MAIN); execute(); - + assertGraveyardCount(playerA, "Flailing Drake", 1); //Snapping Drake 4/3 assertPowerToughness(playerB, "Snapping Drake", 4, 3); } - + @Test public void testIncreaseBlocked() { - addCard(Zone.BATTLEFIELD, playerA, "Forest", 3); - addCard(Zone.BATTLEFIELD, playerA, "Island", 1); + addCard(Zone.BATTLEFIELD, playerA, "Forest", 4); addCard(Zone.BATTLEFIELD, playerA, "Flailing Drake", 1); - addCard(Zone.BATTLEFIELD, playerB, "Forest", 3); - addCard(Zone.BATTLEFIELD, playerB, "Island", 3); + addCard(Zone.BATTLEFIELD, playerB, "Island", 4); addCard(Zone.BATTLEFIELD, playerB, "Snapping Drake", 1); - + + castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Flailing Drake"); + castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Snapping Drake"); + attack(4, playerB, "Snapping Drake"); block(4, playerA, "Flailing Drake", "Snapping Drake"); setStopAt(4, PhaseStep.POSTCOMBAT_MAIN); execute(); - + assertGraveyardCount(playerA, "Flailing Drake", 1); //Snapping Drake 4/3 assertPowerToughness(playerB, "Snapping Drake", 4, 3); diff --git a/Mage.Tests/src/test/java/org/mage/test/serverside/base/impl/CardTestPlayerAPIImpl.java b/Mage.Tests/src/test/java/org/mage/test/serverside/base/impl/CardTestPlayerAPIImpl.java index 088da881677..c2b6e993c4e 100644 --- a/Mage.Tests/src/test/java/org/mage/test/serverside/base/impl/CardTestPlayerAPIImpl.java +++ b/Mage.Tests/src/test/java/org/mage/test/serverside/base/impl/CardTestPlayerAPIImpl.java @@ -285,7 +285,7 @@ public abstract class CardTestPlayerAPIImpl extends MageTestPlayerBase implement if (card == null) { throw new IllegalArgumentException("[TEST] Couldn't find a card: " + cardName); } - PermanentCard p = new PermanentCard(card, player.getId(), currentGame); + PermanentCard p = new PermanentCard(card.copy(), player.getId(), currentGame); p.setTapped(tapped); getBattlefieldCards(player).add(p); } @@ -466,7 +466,7 @@ public abstract class CardTestPlayerAPIImpl extends MageTestPlayerBase implement + ", cardName=" + cardName, count > 0); if (scope.equals(Filter.ComparisonScope.Any)) { - Assert.assertTrue("There is no such creature under player's control with specified power&toughness, player=" + player.getName() + Assert.assertTrue("There is no such creature under player's control with specified p/t of " + power + "/" + toughness + ", player=" + player.getName() + ", cardName=" + cardName + " (found similar: " + found + ", one of them: power=" + foundPower + " toughness=" + foundToughness + ")", fit > 0); } } diff --git a/Mage.Tests/src/test/java/org/mage/test/utils/DeckBuilderTest.java b/Mage.Tests/src/test/java/org/mage/test/utils/DeckBuilderTest.java index d5a81b73907..2f7cf076724 100644 --- a/Mage.Tests/src/test/java/org/mage/test/utils/DeckBuilderTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/utils/DeckBuilderTest.java @@ -5,8 +5,6 @@ import mage.cards.CardSetInfo; import mage.cards.basiclands.Island; import mage.cards.Card; import mage.cards.CardImpl; -import mage.cards.repository.CardInfo; -import mage.cards.repository.CardRepository; import mage.constants.CardType; import mage.constants.ColoredManaSymbol; import mage.constants.Rarity; diff --git a/Mage.Updater/pom.xml b/Mage.Updater/pom.xml index a32ecc03324..e96d35a3ae2 100644 --- a/Mage.Updater/pom.xml +++ b/Mage.Updater/pom.xml @@ -5,7 +5,7 @@ mage-root org.mage - 1.4.20 + 1.4.21 4.0.0 diff --git a/Mage.Verify/pom.xml b/Mage.Verify/pom.xml index 649f089e9f1..84da9888ae8 100644 --- a/Mage.Verify/pom.xml +++ b/Mage.Verify/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 mage-verify diff --git a/Mage/pom.xml b/Mage/pom.xml index 481427be7eb..06cde611e36 100644 --- a/Mage/pom.xml +++ b/Mage/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 mage diff --git a/Mage/src/main/java/mage/abilities/AbilityImpl.java b/Mage/src/main/java/mage/abilities/AbilityImpl.java index bb8b1497fdf..a259bee6679 100644 --- a/Mage/src/main/java/mage/abilities/AbilityImpl.java +++ b/Mage/src/main/java/mage/abilities/AbilityImpl.java @@ -30,6 +30,7 @@ package mage.abilities; import java.util.ArrayList; import java.util.List; import java.util.UUID; + import mage.MageObject; import mage.MageObjectReference; import mage.Mana; @@ -76,7 +77,6 @@ import mage.watchers.Watcher; import org.apache.log4j.Logger; /** - * * @author BetaSteward_at_googlemail.com */ public abstract class AbilityImpl implements Ability { @@ -197,7 +197,7 @@ public abstract class AbilityImpl implements Ability { boolean effectResult = effect.apply(game, this); result &= effectResult; if (logger.isDebugEnabled()) { - if (!this.getAbilityType().equals(AbilityType.MANA)) { + if (this.getAbilityType() != AbilityType.MANA) { if (!effectResult) { if (this.getSourceId() != null) { MageObject mageObject = game.getObject(this.getSourceId()); @@ -267,7 +267,7 @@ public abstract class AbilityImpl implements Ability { * If the player wishes to splice any cards onto the spell (see rule 702.45), he * or she reveals those cards in his or her hand. */ - if (this.abilityType.equals(AbilityType.SPELL)) { + if (this.abilityType == AbilityType.SPELL) { game.getContinuousEffects().applySpliceEffects(this, game); } @@ -290,8 +290,8 @@ public abstract class AbilityImpl implements Ability { // or her intentions to pay any or all of those costs (see rule 601.2e). // A player can't apply two alternative methods of casting or two alternative costs to a single spell. if (!activateAlternateOrAdditionalCosts(sourceObject, noMana, controller, game)) { - if (getAbilityType().equals(AbilityType.SPELL) - && ((SpellAbility) this).getSpellAbilityType().equals(SpellAbilityType.FACE_DOWN_CREATURE)) { + if (getAbilityType() == AbilityType.SPELL + && ((SpellAbility) this).getSpellAbilityType() == SpellAbilityType.FACE_DOWN_CREATURE) { return false; } } @@ -302,7 +302,7 @@ public abstract class AbilityImpl implements Ability { VariableManaCost variableManaCost = handleManaXCosts(game, noMana, controller); String announceString = handleOtherXCosts(game, controller); // For effects from cards like Void Winnower x costs have to be set - if (this.getAbilityType().equals(AbilityType.SPELL) + if (this.getAbilityType() == AbilityType.SPELL && game.replaceEvent(GameEvent.getEvent(GameEvent.EventType.CAST_SPELL_LATE, getId(), getSourceId(), getControllerId()), this)) { return false; } @@ -325,7 +325,7 @@ public abstract class AbilityImpl implements Ability { // and/or zones become the target of a spell trigger at this point; they'll wait to be put on // the stack until the spell has finished being cast.) - if (sourceObject != null && !this.getAbilityType().equals(AbilityType.TRIGGERED)) { // triggered abilities check this already in playerImpl.triggerAbility + if (sourceObject != null && this.getAbilityType() != AbilityType.TRIGGERED) { // triggered abilities check this already in playerImpl.triggerAbility sourceObject.adjustTargets(this, game); } // Flashback abilities haven't made the choices the underlying spell might need for targeting. @@ -408,7 +408,7 @@ public abstract class AbilityImpl implements Ability { } activated = true; // fire if tapped for mana (may only fire now because else costs of ability itself can be payed with mana of abilities that trigger for that event - if (this.getAbilityType().equals(AbilityType.MANA)) { + if (this.getAbilityType() == AbilityType.MANA) { for (Cost cost : costs) { if (cost instanceof TapSourceCost) { Mana mana = null; @@ -466,10 +466,10 @@ public abstract class AbilityImpl implements Ability { } // controller specific alternate spell costs if (!noMana && !alternativeCostisUsed) { - if (this.getAbilityType().equals(AbilityType.SPELL) + if (this.getAbilityType() == AbilityType.SPELL // 117.9a Only one alternative cost can be applied to any one spell as it’s being cast. // So an alternate spell ability can't be paid with Omniscience - && !((SpellAbility) this).getSpellAbilityType().equals(SpellAbilityType.BASE_ALTERNATE)) { + && ((SpellAbility) this).getSpellAbilityType() != SpellAbilityType.BASE_ALTERNATE) { for (AlternativeSourceCosts alternativeSourceCosts : controller.getAlternativeSourceCosts()) { if (alternativeSourceCosts.isAvailable(this, game)) { if (alternativeSourceCosts.askToActivateAlternativeCosts(this, game)) { @@ -489,10 +489,8 @@ public abstract class AbilityImpl implements Ability { * Handles the setting of non mana X costs * * @param controller - * * @param game * @return announce message - * */ protected String handleOtherXCosts(Game game, Player controller) { String announceString = null; @@ -873,7 +871,6 @@ public abstract class AbilityImpl implements Ability { } /** - * * @param game * @param source * @return @@ -883,7 +880,7 @@ public abstract class AbilityImpl implements Ability { if (!this.hasSourceObjectAbility(game, source, event)) { return false; } - if (zone.equals(Zone.COMMAND)) { + if (zone == Zone.COMMAND) { if (this.getSourceId() == null) { // commander effects return true; } @@ -1027,7 +1024,7 @@ public abstract class AbilityImpl implements Ability { sb.append("unknown"); } if (object instanceof Spell && ((Spell) object).getSpellAbilities().size() > 1) { - if (((Spell) object).getSpellAbility().getSpellAbilityType().equals(SpellAbilityType.SPLIT_FUSED)) { + if (((Spell) object).getSpellAbility().getSpellAbilityType() == SpellAbilityType.SPLIT_FUSED) { Spell spell = (Spell) object; int i = 0; for (SpellAbility spellAbility : spell.getSpellAbilities()) { diff --git a/Mage/src/main/java/mage/abilities/common/AsEntersBattlefieldAbility.java b/Mage/src/main/java/mage/abilities/common/AsEntersBattlefieldAbility.java index 7747a126d06..ca55f4a7260 100644 --- a/Mage/src/main/java/mage/abilities/common/AsEntersBattlefieldAbility.java +++ b/Mage/src/main/java/mage/abilities/common/AsEntersBattlefieldAbility.java @@ -30,6 +30,7 @@ package mage.abilities.common; import mage.abilities.StaticAbility; import mage.abilities.effects.Effect; import mage.abilities.effects.EntersBattlefieldEffect; +import mage.constants.EnterEventType; import mage.constants.Zone; /** @@ -39,14 +40,18 @@ import mage.constants.Zone; public class AsEntersBattlefieldAbility extends StaticAbility { public AsEntersBattlefieldAbility(Effect effect) { - super(Zone.ALL, new EntersBattlefieldEffect(effect)); + this(effect, null, EnterEventType.OTHER); } public AsEntersBattlefieldAbility(Effect effect, String text) { - super(Zone.ALL, new EntersBattlefieldEffect(effect, text)); + this(effect, text, EnterEventType.OTHER); } - public AsEntersBattlefieldAbility(AsEntersBattlefieldAbility ability) { + public AsEntersBattlefieldAbility(Effect effect, String text, EnterEventType enterEventType) { + super(Zone.ALL, new EntersBattlefieldEffect(effect, null, text, true, false, enterEventType)); + } + + public AsEntersBattlefieldAbility(final AsEntersBattlefieldAbility ability) { super(ability); } diff --git a/Mage/src/main/java/mage/abilities/common/DiesTriggeredAbility.java b/Mage/src/main/java/mage/abilities/common/DiesTriggeredAbility.java index 541ea59c6db..b587bbc7bba 100644 --- a/Mage/src/main/java/mage/abilities/common/DiesTriggeredAbility.java +++ b/Mage/src/main/java/mage/abilities/common/DiesTriggeredAbility.java @@ -37,7 +37,6 @@ import mage.game.permanent.Permanent; import mage.game.permanent.PermanentToken; /** - * * @author BetaSteward_at_googlemail.com */ public class DiesTriggeredAbility extends ZoneChangeTriggeredAbility { @@ -69,7 +68,7 @@ public class DiesTriggeredAbility extends ZoneChangeTriggeredAbility { @Override public boolean checkEventType(GameEvent event, Game game) { if (super.checkEventType(event, game)) { - return ((ZoneChangeEvent) event).getFromZone().equals(Zone.BATTLEFIELD) && ((ZoneChangeEvent) event).getToZone().equals(Zone.GRAVEYARD); + return ((ZoneChangeEvent) event).getFromZone() == Zone.BATTLEFIELD && ((ZoneChangeEvent) event).getToZone() == Zone.GRAVEYARD; } return false; } diff --git a/Mage/src/main/java/mage/abilities/common/EntersBattlefieldAllTriggeredAbility.java b/Mage/src/main/java/mage/abilities/common/EntersBattlefieldAllTriggeredAbility.java index e91b0fec3f5..400e81d107b 100644 --- a/Mage/src/main/java/mage/abilities/common/EntersBattlefieldAllTriggeredAbility.java +++ b/Mage/src/main/java/mage/abilities/common/EntersBattlefieldAllTriggeredAbility.java @@ -46,7 +46,7 @@ public class EntersBattlefieldAllTriggeredAbility extends TriggeredAbilityImpl { protected FilterPermanent filter; protected String rule; - protected boolean controlled; + protected boolean controlledText; protected SetTargetPointer setTargetPointer; /** @@ -71,19 +71,19 @@ public class EntersBattlefieldAllTriggeredAbility extends TriggeredAbilityImpl { this(zone, effect, filter, optional, rule, false); } - public EntersBattlefieldAllTriggeredAbility(Zone zone, Effect effect, FilterPermanent filter, boolean optional, String rule, boolean controlled) { - this(zone, effect, filter, optional, SetTargetPointer.NONE, rule, controlled); + public EntersBattlefieldAllTriggeredAbility(Zone zone, Effect effect, FilterPermanent filter, boolean optional, String rule, boolean controlledText) { + this(zone, effect, filter, optional, SetTargetPointer.NONE, rule, controlledText); } public EntersBattlefieldAllTriggeredAbility(Zone zone, Effect effect, FilterPermanent filter, boolean optional, SetTargetPointer setTargetPointer, String rule) { this(zone, effect, filter, optional, setTargetPointer, rule, false); } - public EntersBattlefieldAllTriggeredAbility(Zone zone, Effect effect, FilterPermanent filter, boolean optional, SetTargetPointer setTargetPointer, String rule, boolean controlled) { + public EntersBattlefieldAllTriggeredAbility(Zone zone, Effect effect, FilterPermanent filter, boolean optional, SetTargetPointer setTargetPointer, String rule, boolean controlledText) { super(zone, effect, optional); this.filter = filter; this.rule = rule; - this.controlled = controlled; + this.controlledText = controlledText; this.setTargetPointer = setTargetPointer; } @@ -91,7 +91,7 @@ public class EntersBattlefieldAllTriggeredAbility extends TriggeredAbilityImpl { super(ability); this.filter = ability.filter; this.rule = ability.rule; - this.controlled = ability.controlled; + this.controlledText = ability.controlledText; this.setTargetPointer = ability.setTargetPointer; } @@ -130,7 +130,7 @@ public class EntersBattlefieldAllTriggeredAbility extends TriggeredAbilityImpl { } StringBuilder sb = new StringBuilder("Whenever ").append(filter.getMessage()); sb.append(" enters the battlefield"); - if (controlled) { + if (controlledText) { sb.append(" under your control, "); } else { sb.append(", "); diff --git a/Mage/src/main/java/mage/abilities/common/EntersBattlefieldOrLeavesSourceTriggeredAbility.java b/Mage/src/main/java/mage/abilities/common/EntersBattlefieldOrLeavesSourceTriggeredAbility.java index 02a0a1e1fb0..2ed06b56360 100644 --- a/Mage/src/main/java/mage/abilities/common/EntersBattlefieldOrLeavesSourceTriggeredAbility.java +++ b/Mage/src/main/java/mage/abilities/common/EntersBattlefieldOrLeavesSourceTriggeredAbility.java @@ -36,7 +36,6 @@ import mage.game.events.GameEvent.EventType; import mage.game.events.ZoneChangeEvent; /** - * * @author LevelX2 */ public class EntersBattlefieldOrLeavesSourceTriggeredAbility extends TriggeredAbilityImpl { @@ -68,7 +67,7 @@ public class EntersBattlefieldOrLeavesSourceTriggeredAbility extends TriggeredAb } if (event.getType() == EventType.ZONE_CHANGE && event.getTargetId().equals(this.getSourceId())) { ZoneChangeEvent zEvent = (ZoneChangeEvent) event; - if (zEvent.getFromZone().equals(Zone.BATTLEFIELD)) { + if (zEvent.getFromZone() == Zone.BATTLEFIELD) { return true; } } diff --git a/Mage/src/main/java/mage/abilities/common/SpellCounteredControllerTriggeredAbility.java b/Mage/src/main/java/mage/abilities/common/SpellCounteredControllerTriggeredAbility.java new file mode 100644 index 00000000000..befb31d4452 --- /dev/null +++ b/Mage/src/main/java/mage/abilities/common/SpellCounteredControllerTriggeredAbility.java @@ -0,0 +1,62 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package mage.abilities.common; + +import mage.abilities.TriggeredAbilityImpl; +import mage.abilities.effects.Effect; +import mage.constants.Zone; +import mage.game.Game; +import mage.game.events.GameEvent; +import mage.game.events.GameEvent.EventType; +import mage.game.stack.Spell; +import mage.game.stack.StackObject; + +/** + * + * @author fireshoes + */ +public class SpellCounteredControllerTriggeredAbility extends TriggeredAbilityImpl { + + public SpellCounteredControllerTriggeredAbility(Effect effect) { + this(effect, false); + } + + public SpellCounteredControllerTriggeredAbility(Effect effect, boolean optional) { + super(Zone.BATTLEFIELD, effect, optional); + } + + public SpellCounteredControllerTriggeredAbility(final SpellCounteredControllerTriggeredAbility ability) { + super(ability); + } + + @Override + public SpellCounteredControllerTriggeredAbility copy() { + return new SpellCounteredControllerTriggeredAbility(this); + } + + @Override + public boolean checkEventType(GameEvent event, Game game) { + return event.getType() == EventType.COUNTERED; + } + + @Override + public boolean checkTrigger(GameEvent event, Game game) { + StackObject stackObjectThatCountered = (StackObject) game.getStack().getStackObject(event.getSourceId()); + if (stackObjectThatCountered == null) { + stackObjectThatCountered = (StackObject) game.getLastKnownInformation(event.getSourceId(), Zone.STACK); + } + if (stackObjectThatCountered != null && stackObjectThatCountered.getControllerId().equals(getControllerId())) { + StackObject counteredStackObject = (StackObject) game.getLastKnownInformation(event.getTargetId(), Zone.STACK); + return counteredStackObject != null && (counteredStackObject instanceof Spell); + } + return false; + } + + @Override + public String getRule() { + return "Whenever a spell or ability you control counters a spell, " + super.getRule(); + } +} diff --git a/Mage/src/main/java/mage/abilities/condition/common/MeldCondition.java b/Mage/src/main/java/mage/abilities/condition/common/MeldCondition.java index 1480a16c8a9..a757e16c27b 100644 --- a/Mage/src/main/java/mage/abilities/condition/common/MeldCondition.java +++ b/Mage/src/main/java/mage/abilities/condition/common/MeldCondition.java @@ -32,6 +32,7 @@ import mage.abilities.Ability; import mage.abilities.condition.Condition; import mage.filter.common.FilterControlledCreaturePermanent; import mage.filter.predicate.mageobject.NamePredicate; +import mage.filter.predicate.other.OwnerIdPredicate; import mage.game.Game; import mage.game.permanent.Permanent; @@ -39,7 +40,6 @@ import mage.game.permanent.Permanent; * * @author emerald000 */ - public class MeldCondition implements Condition { private final String meldWithName; @@ -57,11 +57,8 @@ public class MeldCondition implements Condition { && sourcePermanent.getOwnerId().equals(source.getControllerId())) { FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent(); filter.add(new NamePredicate(this.meldWithName)); - for (Permanent meldWithPermanent : game.getBattlefield().getActivePermanents(filter, source.getControllerId(), source.getSourceId(), game)) { - if (meldWithPermanent.getOwnerId().equals(source.getControllerId())) { - return true; - } - } + filter.add(new OwnerIdPredicate(source.getControllerId())); + return game.getBattlefield().count(filter, source.getSourceId(), source.getControllerId(), game) > 0; } } return false; diff --git a/Mage/src/main/java/mage/abilities/costs/common/SacrificeAllCost.java b/Mage/src/main/java/mage/abilities/costs/common/SacrificeAllCost.java index 58f767345e2..415692e7ced 100644 --- a/Mage/src/main/java/mage/abilities/costs/common/SacrificeAllCost.java +++ b/Mage/src/main/java/mage/abilities/costs/common/SacrificeAllCost.java @@ -38,7 +38,6 @@ import mage.constants.AbilityType; import mage.filter.FilterPermanent; import mage.game.Game; import mage.game.permanent.Permanent; -import mage.target.common.TargetControlledPermanent; /** * diff --git a/Mage/src/main/java/mage/abilities/decorator/ConditionalManaEffect.java b/Mage/src/main/java/mage/abilities/decorator/ConditionalManaEffect.java index 3f3ad495804..10857231df1 100644 --- a/Mage/src/main/java/mage/abilities/decorator/ConditionalManaEffect.java +++ b/Mage/src/main/java/mage/abilities/decorator/ConditionalManaEffect.java @@ -96,6 +96,7 @@ public class ConditionalManaEffect extends ManaEffect { } if (mana != null) { + checkToFirePossibleEvents(mana, game, source); controller.getManaPool().addMana(mana, game, source); } return true; @@ -114,9 +115,6 @@ public class ConditionalManaEffect extends ManaEffect { } else if (otherwiseEffect != null) { mana = otherwiseEffect.getMana(); } - if (mana != null) { - checkToFirePossibleEvents(mana, game, source); - } return mana; } } diff --git a/Mage/src/main/java/mage/abilities/effects/EntersBattlefieldEffect.java b/Mage/src/main/java/mage/abilities/effects/EntersBattlefieldEffect.java index 549863083a8..37589a698c7 100644 --- a/Mage/src/main/java/mage/abilities/effects/EntersBattlefieldEffect.java +++ b/Mage/src/main/java/mage/abilities/effects/EntersBattlefieldEffect.java @@ -32,6 +32,7 @@ import mage.abilities.Ability; import mage.abilities.Mode; import mage.abilities.condition.Condition; import mage.constants.Duration; +import mage.constants.EnterEventType; import mage.constants.Zone; import mage.game.Game; import mage.game.events.GameEvent; @@ -50,6 +51,7 @@ public class EntersBattlefieldEffect extends ReplacementEffectImpl { protected String text; protected Condition condition; protected boolean optional; + protected EnterEventType enterEventType; public static final String SOURCE_CAST_SPELL_ABILITY = "sourceCastSpellAbility"; @@ -66,19 +68,25 @@ public class EntersBattlefieldEffect extends ReplacementEffectImpl { } public EntersBattlefieldEffect(Effect baseEffect, Condition condition, String text, boolean selfScope, boolean optional) { + this(baseEffect, condition, text, selfScope, optional, EnterEventType.OTHER); + } + + public EntersBattlefieldEffect(Effect baseEffect, Condition condition, String text, boolean selfScope, boolean optional, EnterEventType enterEventType) { super(Duration.WhileOnBattlefield, baseEffect.getOutcome(), selfScope); this.baseEffects.add(baseEffect); + this.enterEventType = enterEventType; this.text = text; this.condition = condition; this.optional = optional; } - public EntersBattlefieldEffect(EntersBattlefieldEffect effect) { + public EntersBattlefieldEffect(final EntersBattlefieldEffect effect) { super(effect); this.baseEffects = effect.baseEffects.copy(); this.text = effect.text; this.condition = effect.condition; this.optional = effect.optional; + this.enterEventType = effect.enterEventType; } public void addEffect(Effect effect) { @@ -87,7 +95,17 @@ public class EntersBattlefieldEffect extends ReplacementEffectImpl { @Override public boolean checksEventType(GameEvent event, Game game) { - return EventType.ENTERS_THE_BATTLEFIELD.equals(event.getType()); + switch (enterEventType) { + case OTHER: + return EventType.ENTERS_THE_BATTLEFIELD.equals(event.getType()); + case SELF: + return EventType.ENTERS_THE_BATTLEFIELD_SELF.equals(event.getType()); + case CONTROL: + return EventType.ENTERS_THE_BATTLEFIELD_CONTROL.equals(event.getType()); + case COPY: + return EventType.ENTERS_THE_BATTLEFIELD_COPY.equals(event.getType()); + } + return false; } @Override diff --git a/Mage/src/main/java/mage/abilities/effects/common/AddManaOfAnyColorToManaPoolTargetPlayerEffect.java b/Mage/src/main/java/mage/abilities/effects/common/AddManaOfAnyColorToManaPoolTargetPlayerEffect.java new file mode 100644 index 00000000000..072484d19c0 --- /dev/null +++ b/Mage/src/main/java/mage/abilities/effects/common/AddManaOfAnyColorToManaPoolTargetPlayerEffect.java @@ -0,0 +1,58 @@ +package mage.abilities.effects.common; + +import mage.Mana; +import mage.abilities.Ability; +import mage.choices.ChoiceColor; +import mage.game.Game; +import mage.players.Player; + +import java.util.UUID; + +/** + * + * Created by Galatolol + */ +public class AddManaOfAnyColorToManaPoolTargetPlayerEffect extends ManaEffect { + + public AddManaOfAnyColorToManaPoolTargetPlayerEffect(String textManaPoolOwner) { + super(); + this.staticText = (textManaPoolOwner.equals("his or her")?"that player adds ":"add ") + "one mana of any color" + " to " + textManaPoolOwner + " mana pool"; + } + + public AddManaOfAnyColorToManaPoolTargetPlayerEffect(final AddManaOfAnyColorToManaPoolTargetPlayerEffect effect) { + super(effect); + } + + @Override + public boolean apply(Game game, Ability source) { + UUID playerId = (UUID) game.getState().getValue(source.getSourceId() + "_player"); + Player player = game.getPlayer(playerId); + if (player != null) { + ChoiceColor choice = new ChoiceColor(); + while (!player.choose(outcome, choice, game)) { + if (!player.canRespond()) { + return false; + } + } + Mana mana = choice.getMana(1); + if (mana != null) { + checkToFirePossibleEvents(mana, game, source); + player.getManaPool().addMana(mana, game, source); + return true; + } + } + return false; + } + + @Override + public AddManaOfAnyColorToManaPoolTargetPlayerEffect copy() { + return new AddManaOfAnyColorToManaPoolTargetPlayerEffect(this); + } + + @Override + public Mana getMana(Game game, Ability source) { + return null; + } + +} + diff --git a/Mage/src/main/java/mage/abilities/effects/common/CounterTargetWithReplacementEffect.java b/Mage/src/main/java/mage/abilities/effects/common/CounterTargetWithReplacementEffect.java index 74609d6216a..2726ccfb195 100644 --- a/Mage/src/main/java/mage/abilities/effects/common/CounterTargetWithReplacementEffect.java +++ b/Mage/src/main/java/mage/abilities/effects/common/CounterTargetWithReplacementEffect.java @@ -96,12 +96,16 @@ public class CounterTargetWithReplacementEffect extends OneShotEffect { switch (zoneDetail) { case BOTTOM: sb.append("the bottom"); + break; case TOP: sb.append("top"); + break; case CHOOSE: sb.append("top or bottom"); + break; case NONE: sb.append(""); + break; } sb.append(" of its owner's library instead of into that player's graveyard"); } diff --git a/Mage/src/main/java/mage/abilities/effects/common/ExileTargetEffect.java b/Mage/src/main/java/mage/abilities/effects/common/ExileTargetEffect.java index cc0eb23cf5d..9862689e266 100644 --- a/Mage/src/main/java/mage/abilities/effects/common/ExileTargetEffect.java +++ b/Mage/src/main/java/mage/abilities/effects/common/ExileTargetEffect.java @@ -137,8 +137,8 @@ public class ExileTargetEffect extends OneShotEffect { } } else { StackObject stackObject = game.getStack().getStackObject(targetId); - if (stackObject instanceof Spell && ((Spell) stackObject).getCard() != null) { - toExile.add(((Spell) stackObject).getCard()); + if (stackObject instanceof Spell) { + toExile.add((Spell) stackObject); } } } diff --git a/Mage/src/main/java/mage/abilities/effects/common/ManaEffect.java b/Mage/src/main/java/mage/abilities/effects/common/ManaEffect.java index 1541c53114e..e489056436b 100644 --- a/Mage/src/main/java/mage/abilities/effects/common/ManaEffect.java +++ b/Mage/src/main/java/mage/abilities/effects/common/ManaEffect.java @@ -63,7 +63,7 @@ public abstract class ManaEffect extends OneShotEffect { * @param source */ public void checkToFirePossibleEvents(Mana mana, Game game, Ability source) { - if (source.getAbilityType().equals(AbilityType.MANA)) { + if (source.getAbilityType()==AbilityType.MANA) { for (Cost cost: source.getCosts()) { if (cost instanceof TapSourceCost) { ManaEvent event = new ManaEvent(GameEvent.EventType.TAPPED_FOR_MANA, source.getSourceId(), source.getSourceId(), source.getControllerId(), mana); diff --git a/Mage/src/main/java/mage/abilities/effects/common/MeldEffect.java b/Mage/src/main/java/mage/abilities/effects/common/MeldEffect.java index 1c28325374e..127957787f5 100644 --- a/Mage/src/main/java/mage/abilities/effects/common/MeldEffect.java +++ b/Mage/src/main/java/mage/abilities/effects/common/MeldEffect.java @@ -27,6 +27,7 @@ */ package mage.abilities.effects.common; +import java.util.HashSet; import java.util.Set; import java.util.UUID; import mage.abilities.Ability; @@ -93,12 +94,14 @@ public class MeldEffect extends OneShotEffect { Permanent sourcePermanent = game.getPermanent(sourceId); Permanent meldWithPermanent = game.getPermanent(meldWithId); if (sourcePermanent != null && meldWithPermanent != null) { - sourcePermanent.moveToExile(null, "", sourceId, game); - meldWithPermanent.moveToExile(null, "", sourceId, game); + Set toExile = new HashSet<>(); + toExile.add(sourcePermanent); + toExile.add(meldWithPermanent); + controller.moveCards(toExile, Zone.EXILED, source, game); // Create the meld card and move it to the battlefield. Card sourceCard = game.getExile().getCard(sourceId, game); Card meldWithCard = game.getExile().getCard(meldWithId, game); - if (!sourceCard.isCopy() && !meldWithCard.isCopy()) { + if (sourceCard != null && !sourceCard.isCopy() && meldWithCard != null && !meldWithCard.isCopy()) { meldCard.setOwnerId(controller.getId()); meldCard.setTopHalfCard(meldWithCard, game); meldCard.setBottomHalfCard(sourceCard, game); @@ -106,7 +109,7 @@ public class MeldEffect extends OneShotEffect { game.addMeldCard(meldCard.getId(), meldCard); game.getState().addCard(meldCard); meldCard.setZone(Zone.EXILED, game); - meldCard.moveToZone(Zone.BATTLEFIELD, sourceId, game, false); + controller.moveCards(meldCard, Zone.BATTLEFIELD, source, game); } return true; } diff --git a/Mage/src/main/java/mage/abilities/effects/common/PreventDamageToControllerEffect.java b/Mage/src/main/java/mage/abilities/effects/common/PreventDamageToControllerEffect.java index 3bd662416c2..92ae7dcf75e 100644 --- a/Mage/src/main/java/mage/abilities/effects/common/PreventDamageToControllerEffect.java +++ b/Mage/src/main/java/mage/abilities/effects/common/PreventDamageToControllerEffect.java @@ -88,7 +88,7 @@ public class PreventDamageToControllerEffect extends PreventionEffectImpl { sb.append("combat "); } sb.append("damage that would be dealt to you"); - if (duration.equals(Duration.EndOfTurn)) { + if (duration == Duration.EndOfTurn) { sb.append(" this turn"); } return sb.toString(); diff --git a/Mage/src/main/java/mage/abilities/effects/common/SwordsToPlowsharesEffect.java b/Mage/src/main/java/mage/abilities/effects/common/SwordsToPlowsharesEffect.java index 7cd7f595295..180d76acf4e 100644 --- a/Mage/src/main/java/mage/abilities/effects/common/SwordsToPlowsharesEffect.java +++ b/Mage/src/main/java/mage/abilities/effects/common/SwordsToPlowsharesEffect.java @@ -25,7 +25,6 @@ * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. */ - package mage.abilities.effects.common; import mage.abilities.Ability; @@ -42,7 +41,7 @@ public class SwordsToPlowsharesEffect extends OneShotEffect { public SwordsToPlowsharesEffect() { super(Outcome.GainLife); - staticText = "Its controller gains life equal to its power"; + staticText = "Exile target creature. Its controller gains life equal to its power"; } public SwordsToPlowsharesEffect(final SwordsToPlowsharesEffect effect) { @@ -60,7 +59,9 @@ public class SwordsToPlowsharesEffect extends OneShotEffect { if (permanent != null) { Player player = game.getPlayer(permanent.getControllerId()); if (player != null) { - player.gainLife(permanent.getPower().getValue(), game); + int creaturePower = permanent.getPower().getValue(); + permanent.moveToExile(null, null, source.getSourceId(), game); + player.gainLife(creaturePower, game); } return true; } diff --git a/Mage/src/main/java/mage/abilities/effects/common/discard/DiscardTargetEffect.java b/Mage/src/main/java/mage/abilities/effects/common/discard/DiscardTargetEffect.java index 95f92e6ab20..65a390a537a 100644 --- a/Mage/src/main/java/mage/abilities/effects/common/discard/DiscardTargetEffect.java +++ b/Mage/src/main/java/mage/abilities/effects/common/discard/DiscardTargetEffect.java @@ -91,9 +91,8 @@ public class DiscardTargetEffect extends OneShotEffect { if (player != null) { player.discard(amount.calculate(game, source, this), randomDiscard, source, game); } - return true; } - return false; + return true; } @Override diff --git a/Mage/src/main/java/mage/abilities/effects/common/enterAttribute/EnterAttributeAddChosenSubtypeEffect.java b/Mage/src/main/java/mage/abilities/effects/common/enterAttribute/EnterAttributeAddChosenSubtypeEffect.java new file mode 100644 index 00000000000..b5db7190aee --- /dev/null +++ b/Mage/src/main/java/mage/abilities/effects/common/enterAttribute/EnterAttributeAddChosenSubtypeEffect.java @@ -0,0 +1,73 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.abilities.effects.common.enterAttribute; + +import mage.MageObject; +import mage.abilities.Ability; +import mage.abilities.effects.OneShotEffect; +import mage.constants.Outcome; +import mage.game.Game; +import mage.game.permanent.Permanent; + +/** + * + * @author LevelX2 + */ +public class EnterAttributeAddChosenSubtypeEffect extends OneShotEffect { + + public EnterAttributeAddChosenSubtypeEffect() { + super(Outcome.Benefit); + this.staticText = "{this} is the chosen type in addition to its other types"; + } + + public EnterAttributeAddChosenSubtypeEffect(final EnterAttributeAddChosenSubtypeEffect effect) { + super(effect); + } + + @Override + public EnterAttributeAddChosenSubtypeEffect copy() { + return new EnterAttributeAddChosenSubtypeEffect(this); + } + + @Override + public boolean apply(Game game, Ability source) { + Permanent permanent = game.getPermanentEntering(source.getSourceId()); + String subtype = (String) game.getState().getValue(source.getSourceId() + "_type"); + if (permanent != null && subtype != null) { + MageObject mageObject = permanent.getBasicMageObject(game); + if (!mageObject.getSubtype(null).contains(subtype)) { + mageObject.getSubtype(null).add(subtype); + } + if (!permanent.getSubtype(null).contains(subtype)) { + permanent.getSubtype(null).add(subtype); + } + return true; + } + return false; + } +} diff --git a/Mage/src/main/java/mage/abilities/effects/common/search/SearchLibraryGraveyardPutInHandEffect.java b/Mage/src/main/java/mage/abilities/effects/common/search/SearchLibraryGraveyardPutInHandEffect.java new file mode 100644 index 00000000000..0b007176b85 --- /dev/null +++ b/Mage/src/main/java/mage/abilities/effects/common/search/SearchLibraryGraveyardPutInHandEffect.java @@ -0,0 +1,113 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.abilities.effects.common.search; + +import mage.MageObject; +import mage.abilities.Ability; +import mage.abilities.effects.OneShotEffect; +import mage.cards.Card; +import mage.cards.CardsImpl; +import mage.constants.Outcome; +import mage.constants.Zone; +import mage.filter.FilterCard; +import mage.game.Game; +import mage.players.Player; +import mage.target.TargetCard; +import mage.target.common.TargetCardInLibrary; + +/** + * + * @author Styxo + */ +public class SearchLibraryGraveyardPutInHandEffect extends OneShotEffect { + + private FilterCard filter; + private boolean forceToSearchBoth; + + public SearchLibraryGraveyardPutInHandEffect(FilterCard filter) { + this(filter, false); + } + + public SearchLibraryGraveyardPutInHandEffect(FilterCard filter, boolean forceToSearchBoth) { + super(Outcome.Benefit); + this.filter = filter; + this.forceToSearchBoth = forceToSearchBoth; + staticText = "Search your library and" + (forceToSearchBoth ? "" : "/or ") + " graveyard for a card named " + filter.getMessage() + ", reveal it, and put it into your hand. Then shuffle your library"; + } + + public SearchLibraryGraveyardPutInHandEffect(final SearchLibraryGraveyardPutInHandEffect effect) { + super(effect); + this.filter = effect.filter; + this.forceToSearchBoth = effect.forceToSearchBoth; + + } + + @Override + public SearchLibraryGraveyardPutInHandEffect copy() { + return new SearchLibraryGraveyardPutInHandEffect(this); + } + + @Override + public boolean apply(Game game, Ability source) { + Player controller = game.getPlayer(source.getControllerId()); + MageObject sourceObject = source.getSourceObject(game); + Card cardFound = null; + if (controller != null && sourceObject != null) { + if (forceToSearchBoth || controller.chooseUse(outcome, "Search your library for a card named " + filter.getMessage() + "?", source, game)) { + TargetCardInLibrary target = new TargetCardInLibrary(0, 1, filter); + target.clearChosen(); + if (controller.searchLibrary(target, game)) { + if (target.getTargets().size() > 0) { + cardFound = game.getCard(target.getFirstTarget()); + } + } + controller.shuffleLibrary(source, game); + } + + if (cardFound == null && controller.chooseUse(outcome, "Search your graveyard for a card named " + filter.getMessage() + "?", source, game)) { + TargetCard target = new TargetCard(0, 1, Zone.GRAVEYARD, filter); + target.clearChosen(); + if (controller.choose(outcome, controller.getGraveyard(), target, game)) { + if (target.getTargets().size() > 0) { + cardFound = game.getCard(target.getFirstTarget()); + } + } + } + + if (cardFound != null) { + controller.revealCards(sourceObject.getIdName(), new CardsImpl(cardFound), game); + controller.moveCards(cardFound, Zone.HAND, source, game); + } + + return true; + } + + return false; + } + +} diff --git a/Mage/src/main/java/mage/abilities/effects/common/search/SearchLibraryWithLessCMCPutInPlayEffect.java b/Mage/src/main/java/mage/abilities/effects/common/search/SearchLibraryWithLessCMCPutInPlayEffect.java new file mode 100644 index 00000000000..2096e438436 --- /dev/null +++ b/Mage/src/main/java/mage/abilities/effects/common/search/SearchLibraryWithLessCMCPutInPlayEffect.java @@ -0,0 +1,90 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.abilities.effects.common.search; + +import mage.abilities.Ability; +import mage.abilities.effects.OneShotEffect; +import mage.cards.Card; +import mage.constants.Outcome; +import mage.constants.Zone; +import mage.filter.Filter; +import mage.filter.FilterCard; +import mage.filter.predicate.mageobject.ConvertedManaCostPredicate; +import mage.game.Game; +import mage.players.Player; +import mage.target.common.TargetCardInLibrary; + +/** + * + * @author Styxo + */ +public class SearchLibraryWithLessCMCPutInPlayEffect extends OneShotEffect { + + private FilterCard filter; + + public SearchLibraryWithLessCMCPutInPlayEffect() { + this(new FilterCard()); + } + + public SearchLibraryWithLessCMCPutInPlayEffect(FilterCard filter) { + super(Outcome.PutCreatureInPlay); + this.filter = filter; + staticText = "Search your library for a " + filter.getMessage() + " with converted mana cost X or less, put it onto the battlefield, then shuffle your library"; + } + + public SearchLibraryWithLessCMCPutInPlayEffect(final SearchLibraryWithLessCMCPutInPlayEffect effect) { + super(effect); + this.filter = effect.filter; + } + + @Override + public boolean apply(Game game, Ability source) { + Player controller = game.getPlayer(source.getControllerId()); + if (controller != null) { + filter.add(new ConvertedManaCostPredicate(Filter.ComparisonType.LessThan, source.getManaCostsToPay().getX() + 1)); + TargetCardInLibrary target = new TargetCardInLibrary(filter); + if (controller.searchLibrary(target, game)) { + if (target.getTargets().size() > 0) { + Card card = controller.getLibrary().getCard(target.getFirstTarget(), game); + if (card != null) { + controller.moveCards(card, Zone.BATTLEFIELD, source, game); + } + } + controller.shuffleLibrary(source, game); + } + return true; + } + return false; + } + + @Override + public SearchLibraryWithLessCMCPutInPlayEffect copy() { + return new SearchLibraryWithLessCMCPutInPlayEffect(this); + } + +} diff --git a/Mage/src/main/java/mage/abilities/keyword/BestowAbility.java b/Mage/src/main/java/mage/abilities/keyword/BestowAbility.java index fffff63fb24..ab0dbd2c065 100644 --- a/Mage/src/main/java/mage/abilities/keyword/BestowAbility.java +++ b/Mage/src/main/java/mage/abilities/keyword/BestowAbility.java @@ -27,25 +27,23 @@ */ package mage.abilities.keyword; +import mage.MageObject; import mage.abilities.Ability; import mage.abilities.SpellAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.mana.ManaCostsImpl; -import mage.abilities.effects.ContinuousEffectImpl; +import mage.abilities.effects.ReplacementEffectImpl; import mage.abilities.effects.common.AttachEffect; -import mage.abilities.effects.common.continuous.SourceEffect; import mage.cards.Card; -import mage.cards.repository.CardRepository; import mage.constants.CardType; -import mage.constants.DependencyType; import mage.constants.Duration; -import mage.constants.Layer; import mage.constants.Outcome; import mage.constants.SpellAbilityType; -import mage.constants.SubLayer; import mage.constants.TimingRule; import mage.constants.Zone; import mage.game.Game; +import mage.game.events.GameEvent; +import mage.game.events.GameEvent.EventType; import mage.game.permanent.Permanent; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; @@ -123,7 +121,7 @@ public class BestowAbility extends SpellAbility { TargetPermanent auraTarget = new TargetCreaturePermanent(); this.addTarget(auraTarget); this.addEffect(new AttachEffect(Outcome.BoostCreature)); - Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, new BestowTypeChangingEffect()); + Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, new BestowEntersBattlefieldEffect()); ability.setRuleVisible(false); addSubAbility(ability); } @@ -147,64 +145,60 @@ public class BestowAbility extends SpellAbility { return "Bestow " + getManaCostsToPay().getText() + " (If you cast this card for its bestow cost, it's an Aura spell with enchant creature. It becomes a creature again if it's not attached to a creature.)"; } - class BestowTypeChangingEffect extends ContinuousEffectImpl implements SourceEffect { - - private boolean wasAttached; - - public BestowTypeChangingEffect() { - super(Duration.WhileOnBattlefield, Outcome.BoostCreature); - wasAttached = false; - dependencyTypes.add(DependencyType.AuraAddingRemoving); - } - - public BestowTypeChangingEffect(final BestowTypeChangingEffect effect) { - super(effect); - this.wasAttached = effect.wasAttached; - } - - @Override - public BestowTypeChangingEffect copy() { - return new BestowTypeChangingEffect(this); - } - - @Override - public boolean apply(Layer layer, SubLayer sublayer, Ability source, Game game) { - Permanent permanent = game.getPermanent(source.getSourceId()); - if (permanent != null) { - switch (layer) { - case TypeChangingEffects_4: - if (sublayer == SubLayer.NA) { - if (permanent.getAttachedTo() == null) { - if (wasAttached && permanent.getSubtype(game).contains("Aura")) { - permanent.getSubtype(game).remove("Aura"); - wasAttached = false; - } - } else { - permanent.getCardType().remove(CardType.CREATURE); - permanent.getSubtype(game).retainAll(CardRepository.instance.getLandTypes()); - if (!permanent.getSubtype(game).contains("Aura")) { - permanent.getSubtype(game).add("Aura"); - } - wasAttached = true; - } - } - break; + static public void becomeCreature(Permanent permanent, Game game) { + if (permanent != null) { + MageObject basicObject = permanent.getBasicMageObject(game); + if (basicObject != null) { + basicObject.getSubtype(null).remove("Aura"); + if (!basicObject.getCardType().contains(CardType.CREATURE)) { + basicObject.getCardType().add(CardType.CREATURE); } - return true; } - return false; - } + permanent.getSubtype(null).remove("Aura"); + if (!permanent.getCardType().contains(CardType.CREATURE)) { + permanent.getCardType().add(CardType.CREATURE); + } - @Override - public boolean apply(Game game, Ability source) { - return false; } + } +} - @Override - public boolean hasLayer(Layer layer) { - return layer == Layer.TypeChangingEffects_4; +class BestowEntersBattlefieldEffect extends ReplacementEffectImpl { + + public BestowEntersBattlefieldEffect() { + super(Duration.WhileOnBattlefield, Outcome.Neutral); + } + + public BestowEntersBattlefieldEffect(final BestowEntersBattlefieldEffect effect) { + super(effect); + } + + @Override + public boolean checksEventType(GameEvent event, Game game) { + return EventType.ENTERS_THE_BATTLEFIELD_SELF.equals(event.getType()); + } + + @Override + public boolean applies(GameEvent event, Ability source, Game game) { + return event.getTargetId().equals(source.getSourceId()); + } + + @Override + public boolean replaceEvent(GameEvent event, Ability source, Game game) { + Permanent bestowPermanent = game.getPermanentEntering(source.getSourceId()); + if (bestowPermanent != null) { + if (bestowPermanent.getSubtype(game).contains("Aura")) { + MageObject basicObject = bestowPermanent.getBasicMageObject(game); + basicObject.getSubtype(null).add("Aura"); + basicObject.getCardType().remove(CardType.CREATURE); + } } + return false; + } + @Override + public BestowEntersBattlefieldEffect copy() { + return new BestowEntersBattlefieldEffect(this); } } diff --git a/Mage/src/main/java/mage/abilities/keyword/ImproviseAbility.java b/Mage/src/main/java/mage/abilities/keyword/ImproviseAbility.java index 12ff28c8611..738537f59d1 100644 --- a/Mage/src/main/java/mage/abilities/keyword/ImproviseAbility.java +++ b/Mage/src/main/java/mage/abilities/keyword/ImproviseAbility.java @@ -6,6 +6,7 @@ package mage.abilities.keyword; import java.util.UUID; + import mage.Mana; import mage.abilities.Ability; import mage.abilities.SpecialAction; @@ -30,7 +31,6 @@ import mage.target.Target; import mage.target.common.TargetControlledPermanent; /** - * * @author LevelX2 */ public class ImproviseAbility extends SimpleStaticAbility implements AlternateManaPaymentAbility { @@ -59,7 +59,7 @@ public class ImproviseAbility extends SimpleStaticAbility implements AlternateMa public void addSpecialAction(Ability source, Game game, ManaCost unpaid) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null && game.getBattlefield().contains(filterUntapped, controller.getId(), 1, game)) { - if (source.getAbilityType().equals(AbilityType.SPELL) && unpaid.getMana().getGeneric() > 0) { + if (source.getAbilityType() == AbilityType.SPELL && unpaid.getMana().getGeneric() > 0) { SpecialAction specialAction = new ImproviseSpecialAction(unpaid); specialAction.setControllerId(source.getControllerId()); specialAction.setSourceId(source.getSourceId()); diff --git a/Mage/src/main/java/mage/abilities/keyword/ProtectionAbility.java b/Mage/src/main/java/mage/abilities/keyword/ProtectionAbility.java index b75bacfae7f..5db0f90de49 100644 --- a/Mage/src/main/java/mage/abilities/keyword/ProtectionAbility.java +++ b/Mage/src/main/java/mage/abilities/keyword/ProtectionAbility.java @@ -30,7 +30,6 @@ package mage.abilities.keyword; import java.util.UUID; import mage.MageObject; import mage.ObjectColor; -import mage.abilities.Ability; import mage.abilities.StaticAbility; import mage.cards.Card; import mage.constants.CardType; diff --git a/Mage/src/main/java/mage/cards/CardImpl.java b/Mage/src/main/java/mage/cards/CardImpl.java index f85dfb0c52c..10a0aa8d124 100644 --- a/Mage/src/main/java/mage/cards/CardImpl.java +++ b/Mage/src/main/java/mage/cards/CardImpl.java @@ -49,7 +49,6 @@ import mage.constants.Zone; import mage.counters.Counter; import mage.counters.Counters; import mage.game.*; -import mage.game.command.Commander; import mage.game.events.GameEvent; import mage.game.events.ZoneChangeEvent; import mage.game.permanent.Permanent; diff --git a/Mage/src/main/java/mage/cards/CardsImpl.java b/Mage/src/main/java/mage/cards/CardsImpl.java index 55123325f38..c7228776be9 100644 --- a/Mage/src/main/java/mage/cards/CardsImpl.java +++ b/Mage/src/main/java/mage/cards/CardsImpl.java @@ -230,9 +230,7 @@ public class CardsImpl extends LinkedHashSet implements Cards, Serializabl Map cards = new HashMap<>(); for (UUID cardId : this) { Card card = game.getCard(cardId); - if (!cards.containsKey(card.getName())) { - cards.put(card.getName(), card); - } + cards.putIfAbsent(card.getName(), card); } return cards.values(); } diff --git a/Mage/src/main/java/mage/cards/ExpansionSet.java b/Mage/src/main/java/mage/cards/ExpansionSet.java index 24e3d35dc23..384601df49c 100644 --- a/Mage/src/main/java/mage/cards/ExpansionSet.java +++ b/Mage/src/main/java/mage/cards/ExpansionSet.java @@ -406,7 +406,7 @@ public abstract class ExpansionSet implements Serializable { Iterator iterator = savedCardsInfos.iterator(); while (iterator.hasNext()) { CardInfo next = iterator.next(); - if (Integer.valueOf(next.getCardNumber()) > maxCardNumberInBooster) { + if (Integer.valueOf(next.getCardNumber()) > maxCardNumberInBooster && !rarity.equals(Rarity.LAND)) { iterator.remove(); } } diff --git a/Mage/src/main/java/mage/cards/MeldCard.java b/Mage/src/main/java/mage/cards/MeldCard.java index bbf2faef5d9..736dd293f2f 100644 --- a/Mage/src/main/java/mage/cards/MeldCard.java +++ b/Mage/src/main/java/mage/cards/MeldCard.java @@ -55,13 +55,13 @@ public abstract class MeldCard extends CardImpl { halves = new CardsImpl(); } - public MeldCard(MeldCard card) { + public MeldCard(final MeldCard card) { super(card); this.topHalfCard = card.topHalfCard; this.bottomHalfCard = card.bottomHalfCard; this.topLastZoneChangeCounter = card.topLastZoneChangeCounter; this.bottomLastZoneChangeCounter = card.bottomLastZoneChangeCounter; - this.halves = new CardsImpl(halves); + this.halves = new CardsImpl(card.halves); this.isMelded = card.isMelded; } @@ -211,4 +211,5 @@ public abstract class MeldCard extends CardImpl { public Cards getHalves() { return halves; } + } diff --git a/Mage/src/main/java/mage/cards/repository/CardRepository.java b/Mage/src/main/java/mage/cards/repository/CardRepository.java index e0b8a494958..41d39928c75 100644 --- a/Mage/src/main/java/mage/cards/repository/CardRepository.java +++ b/Mage/src/main/java/mage/cards/repository/CardRepository.java @@ -60,7 +60,7 @@ public enum CardRepository { // raise this if db structure was changed private static final long CARD_DB_VERSION = 50; // raise this if new cards were added to the server - private static final long CARD_CONTENT_VERSION = 67; + private static final long CARD_CONTENT_VERSION = 68; private final TreeSet landTypes = new TreeSet(); private Dao cardDao; private Set classNames; diff --git a/Mage/src/main/java/mage/cards/repository/ExpansionInfo.java b/Mage/src/main/java/mage/cards/repository/ExpansionInfo.java index 4bff5ee0ca4..572e5ef3d19 100644 --- a/Mage/src/main/java/mage/cards/repository/ExpansionInfo.java +++ b/Mage/src/main/java/mage/cards/repository/ExpansionInfo.java @@ -16,7 +16,7 @@ public class ExpansionInfo { @DatabaseField(unique = true) protected String name; - @DatabaseField(unique = true) + @DatabaseField(id = true,unique = true) protected String code; @DatabaseField protected String blockName; diff --git a/Mage/src/main/java/mage/constants/EnterEventType.java b/Mage/src/main/java/mage/constants/EnterEventType.java new file mode 100644 index 00000000000..09a5b75a92a --- /dev/null +++ b/Mage/src/main/java/mage/constants/EnterEventType.java @@ -0,0 +1,12 @@ +package mage.constants; + +/** + * + * @author LevelX2 + */ +public enum EnterEventType { + SELF, + CONTROL, + COPY, + OTHER +} diff --git a/Mage/src/main/java/mage/constants/Zone.java b/Mage/src/main/java/mage/constants/Zone.java index f9718238001..618f58b4aad 100644 --- a/Mage/src/main/java/mage/constants/Zone.java +++ b/Mage/src/main/java/mage/constants/Zone.java @@ -47,4 +47,7 @@ public enum Zone { return super.toString(); } + public static boolean isPublicZone(Zone zone) { + return GRAVEYARD.equals(zone) || BATTLEFIELD.equals(zone) || STACK.equals(zone) || EXILED.equals(zone) || COMMAND.equals(zone); + } } diff --git a/Mage/src/main/java/mage/counters/Counter.java b/Mage/src/main/java/mage/counters/Counter.java index 53ee5c039d5..dba60bda36f 100644 --- a/Mage/src/main/java/mage/counters/Counter.java +++ b/Mage/src/main/java/mage/counters/Counter.java @@ -73,13 +73,6 @@ public class Counter implements Serializable { this.count = counter.count; } - /** - * Increases the {@code count} by 1 - */ - public void increase() { - count++; - } - /** * Adds the passed in {@code amount} to the {@code count} * diff --git a/Mage/src/main/java/mage/counters/Counters.java b/Mage/src/main/java/mage/counters/Counters.java index c52c7d6cefb..4dacb284ccd 100644 --- a/Mage/src/main/java/mage/counters/Counters.java +++ b/Mage/src/main/java/mage/counters/Counters.java @@ -24,8 +24,7 @@ * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. -*/ - + */ package mage.counters; import java.io.Serializable; @@ -35,15 +34,15 @@ import java.util.List; import java.util.Map; /** - * * @author BetaSteward_at_googlemail.com */ public class Counters extends HashMap implements Serializable { - public Counters() {} + public Counters() { + } public Counters(final Counters counters) { - for (Map.Entry entry: counters.entrySet()) { + for (Map.Entry entry : counters.entrySet()) { this.put(entry.getKey(), entry.getValue().copy()); } } @@ -52,17 +51,8 @@ public class Counters extends HashMap implements Serializable { return new Counters(this); } - public void addCounter(String name) { - if (!this.containsKey(name)) { - this.put(name, new Counter(name)); - } - this.get(name).increase(); - } - public void addCounter(String name, int amount) { - if (!this.containsKey(name)) { - this.put(name, new Counter(name)); - } + putIfAbsent(name, new Counter(name)); this.get(name).add(amount); } @@ -100,13 +90,14 @@ public class Counters extends HashMap implements Serializable { return false; } - public void removeAllCounters(CounterType counterType){ + public void removeAllCounters(CounterType counterType) { removeAllCounters(counterType.getName()); } - public void removeAllCounters(String name){ - if (this.containsKey(name)){ + public void removeAllCounters(String name) { + if (this.containsKey(name)) { this.remove(name); + } } @@ -130,9 +121,9 @@ public class Counters extends HashMap implements Serializable { public List getBoostCounters() { List boosters = new ArrayList<>(); - for (Counter counter: this.values()) { + for (Counter counter : this.values()) { if (counter instanceof BoostCounter) { - boosters.add((BoostCounter)counter); + boosters.add((BoostCounter) counter); } } return boosters; diff --git a/Mage/src/main/java/mage/game/GameCommanderImpl.java b/Mage/src/main/java/mage/game/GameCommanderImpl.java index 45d23434ed3..3be3b93eb95 100644 --- a/Mage/src/main/java/mage/game/GameCommanderImpl.java +++ b/Mage/src/main/java/mage/game/GameCommanderImpl.java @@ -27,7 +27,6 @@ */ package mage.game; -import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -38,7 +37,6 @@ import mage.abilities.effects.common.InfoEffect; import mage.abilities.effects.common.continuous.CommanderReplacementEffect; import mage.abilities.effects.common.cost.CommanderCostModification; import mage.cards.Card; -import mage.cards.Cards; import mage.constants.MultiplayerAttackOption; import mage.constants.PhaseStep; import mage.constants.RangeOfInfluence; @@ -49,11 +47,8 @@ import mage.watchers.common.CommanderInfoWatcher; public abstract class GameCommanderImpl extends GameImpl { - static boolean CHECK_COMMANDER_DAMAGE = true; - - private final Map mulliganedCards = new HashMap<>(); - // private final Set commanderCombatWatcher = new HashSet<>(); - + // private final Map mulliganedCards = new HashMap<>(); + protected boolean checkCommanderDamage = true; protected boolean alsoHand; // replace commander going to hand protected boolean alsoLibrary; // replace commander going to library protected boolean startingPlayerSkipsDraw = true; @@ -67,6 +62,7 @@ public abstract class GameCommanderImpl extends GameImpl { this.alsoHand = game.alsoHand; this.alsoLibrary = game.alsoLibrary; this.startingPlayerSkipsDraw = game.startingPlayerSkipsDraw; + this.checkCommanderDamage = game.checkCommanderDamage; } @Override @@ -85,7 +81,7 @@ public abstract class GameCommanderImpl extends GameImpl { ability.addEffect(new CommanderReplacementEffect(commander.getId(), alsoHand, alsoLibrary)); ability.addEffect(new CommanderCostModification(commander.getId())); getState().setValue(commander.getId() + "_castCount", 0); - CommanderInfoWatcher watcher = new CommanderInfoWatcher(commander.getId(), CHECK_COMMANDER_DAMAGE); + CommanderInfoWatcher watcher = new CommanderInfoWatcher(commander.getId(), checkCommanderDamage); getState().getWatchers().add(watcher); watcher.addCardInfoToCommander(this); } @@ -227,4 +223,13 @@ public abstract class GameCommanderImpl extends GameImpl { public void setAlsoLibrary(boolean alsoLibrary) { this.alsoLibrary = alsoLibrary; } + + public boolean isCheckCommanderDamage() { + return checkCommanderDamage; + } + + public void setCheckCommanderDamage(boolean checkCommanderDamage) { + this.checkCommanderDamage = checkCommanderDamage; + } + } diff --git a/Mage/src/main/java/mage/game/GameImpl.java b/Mage/src/main/java/mage/game/GameImpl.java index eac5e08104c..68133f69edf 100644 --- a/Mage/src/main/java/mage/game/GameImpl.java +++ b/Mage/src/main/java/mage/game/GameImpl.java @@ -57,6 +57,7 @@ import mage.abilities.effects.ContinuousEffects; import mage.abilities.effects.Effect; import mage.abilities.effects.PreventionEffectData; import mage.abilities.effects.common.CopyEffect; +import mage.abilities.keyword.BestowAbility; import mage.abilities.keyword.MorphAbility; import mage.abilities.keyword.TransformAbility; import mage.abilities.mana.DelayedTriggeredManaAbility; @@ -109,7 +110,6 @@ import mage.game.events.TableEventSource; import mage.game.permanent.Battlefield; import mage.game.permanent.Permanent; import mage.game.permanent.PermanentCard; -import mage.game.permanent.PermanentImpl; import mage.game.stack.Spell; import mage.game.stack.SpellStack; import mage.game.stack.StackObject; @@ -1788,7 +1788,7 @@ public abstract class GameImpl implements Game, Serializable { } } else { SpellAbility spellAbility = perm.getSpellAbility(); - if (perm.getSpellAbility().getTargets().isEmpty()) { + if (spellAbility.getTargets().isEmpty()) { for (Ability ability : perm.getAbilities(this)) { if ((ability instanceof SpellAbility) && SpellAbilityType.BASE_ALTERNATE.equals(((SpellAbility) ability).getSpellAbilityType()) @@ -1811,6 +1811,7 @@ public abstract class GameImpl implements Game, Serializable { if (card != null && card.getCardType().contains(CardType.CREATURE)) { UUID wasAttachedTo = perm.getAttachedTo(); perm.attachTo(null, this); + BestowAbility.becomeCreature(perm, this); fireEvent(new GameEvent(GameEvent.EventType.UNATTACHED, wasAttachedTo, perm.getId(), perm.getControllerId())); } else if (movePermanentToGraveyardWithInfo(perm)) { somethingHappened = true; @@ -2676,17 +2677,17 @@ public abstract class GameImpl implements Game, Serializable { card.setZone(Zone.GRAVEYARD, this); player.getGraveyard().add(card); } - for (PermanentCard card : battlefield) { - card.setZone(Zone.BATTLEFIELD, this); - card.setOwnerId(ownerId); - PermanentCard permanent = new PermanentCard(card.getCard(), ownerId, this); - getPermanentsEntering().put(permanent.getId(), permanent); - permanent.entersBattlefield(permanent.getId(), this, Zone.OUTSIDE, false); - getBattlefield().addPermanent(permanent); - getPermanentsEntering().remove(permanent.getId()); - permanent.removeSummoningSickness(); - if (card.isTapped()) { - permanent.setTapped(true); + for (PermanentCard permanentCard : battlefield) { + permanentCard.setZone(Zone.BATTLEFIELD, this); + permanentCard.setOwnerId(ownerId); + PermanentCard newPermanent = new PermanentCard(permanentCard.getCard(), ownerId, this); + getPermanentsEntering().put(newPermanent.getId(), newPermanent); + newPermanent.entersBattlefield(newPermanent.getId(), this, Zone.OUTSIDE, false); + getBattlefield().addPermanent(newPermanent); + getPermanentsEntering().remove(newPermanent.getId()); + newPermanent.removeSummoningSickness(); + if (permanentCard.isTapped()) { + newPermanent.setTapped(true); } } applyEffects(); diff --git a/Mage/src/main/java/mage/game/LookedAt.java b/Mage/src/main/java/mage/game/LookedAt.java index 501cb34c70d..8bab425822f 100644 --- a/Mage/src/main/java/mage/game/LookedAt.java +++ b/Mage/src/main/java/mage/game/LookedAt.java @@ -64,9 +64,7 @@ public class LookedAt extends HashMap implements Serializable, Co } public Cards createLookedAt(String name) { - if (!this.containsKey(name)) { - this.put(name, new CardsImpl()); - } + putIfAbsent(name, new CardsImpl()); return this.get(name); } diff --git a/Mage/src/main/java/mage/game/ZonesHandler.java b/Mage/src/main/java/mage/game/ZonesHandler.java index 427095c91bf..fc733a970b8 100644 --- a/Mage/src/main/java/mage/game/ZonesHandler.java +++ b/Mage/src/main/java/mage/game/ZonesHandler.java @@ -204,8 +204,7 @@ public class ZonesHandler { // If we can't find the card we can't remove it. return false; } - // If needed take attributes from the spell (e.g. color of spell was changed) - card = takeAttributesFromSpell(card, event, game); + boolean success = false; if (info.faceDown) { card.setFaceDown(true, game); @@ -213,6 +212,8 @@ public class ZonesHandler { if (!game.replaceEvent(event)) { Zone fromZone = event.getFromZone(); if (event.getToZone() == Zone.BATTLEFIELD) { + // If needed take attributes from the spell (e.g. color of spell was changed) + card = takeAttributesFromSpell(card, event, game); // controlling player can be replaced so use event player now Permanent permanent; if (card instanceof MeldCard) { @@ -232,7 +233,6 @@ public class ZonesHandler { if (info.faceDown) { card.setFaceDown(false, game); } - // make sure the controller of all continuous effects of this card are switched to the current controller game.setScopeRelevant(true); game.getContinuousEffects().setController(permanent.getId(), permanent.getControllerId()); @@ -282,16 +282,12 @@ public class ZonesHandler { } private static Card takeAttributesFromSpell(Card card, ZoneChangeEvent event, Game game) { + card = card.copy(); if (Zone.STACK.equals(event.getFromZone())) { Spell spell = game.getStack().getSpell(event.getTargetId()); if (spell != null && !spell.isFaceDown(game)) { - boolean doCopy = false; if (!card.getColor(game).equals(spell.getColor(game))) { - doCopy = true; - } - if (doCopy) { // the card that is referenced to in the permanent is copied and the spell attributes are set to this copied card - card = card.copy(); card.getColor(game).setColor(spell.getColor(game)); } } diff --git a/Mage/src/main/java/mage/game/events/EntersTheBattlefieldEvent.java b/Mage/src/main/java/mage/game/events/EntersTheBattlefieldEvent.java index c4948e4b6e0..ab63ce854d9 100644 --- a/Mage/src/main/java/mage/game/events/EntersTheBattlefieldEvent.java +++ b/Mage/src/main/java/mage/game/events/EntersTheBattlefieldEvent.java @@ -24,12 +24,12 @@ * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. -*/ - + */ package mage.game.events; -import java.util.ArrayList; import java.util.UUID; +import mage.constants.EnterEventType; +import static mage.constants.EnterEventType.SELF; import mage.constants.Zone; import mage.game.permanent.Permanent; @@ -43,17 +43,24 @@ public class EntersTheBattlefieldEvent extends GameEvent { private Permanent target; public EntersTheBattlefieldEvent(Permanent target, UUID sourceId, UUID playerId, Zone fromZone) { - super(EventType.ENTERS_THE_BATTLEFIELD, target.getId(), sourceId, playerId); - this.fromZone = fromZone; - this.target = target; + this(target, sourceId, playerId, fromZone, EnterEventType.OTHER); } - public EntersTheBattlefieldEvent(Permanent target, UUID sourceId, UUID playerId, Zone fromZone, ArrayList appliedEffects) { + public EntersTheBattlefieldEvent(Permanent target, UUID sourceId, UUID playerId, Zone fromZone, EnterEventType enterType) { super(EventType.ENTERS_THE_BATTLEFIELD, target.getId(), sourceId, playerId); - this.fromZone = fromZone; - if (appliedEffects != null) { - this.appliedEffects = appliedEffects; + switch (enterType) { + case SELF: + type = EventType.ENTERS_THE_BATTLEFIELD_SELF; + break; + case CONTROL: + type = EventType.ENTERS_THE_BATTLEFIELD_CONTROL; + break; + case COPY: + type = EventType.ENTERS_THE_BATTLEFIELD_COPY; + break; } + this.fromZone = fromZone; + this.target = target; } public Zone getFromZone() { diff --git a/Mage/src/main/java/mage/game/events/GameEvent.java b/Mage/src/main/java/mage/game/events/GameEvent.java index a38958c2ea2..a554d276558 100644 --- a/Mage/src/main/java/mage/game/events/GameEvent.java +++ b/Mage/src/main/java/mage/game/events/GameEvent.java @@ -229,7 +229,10 @@ public class GameEvent implements Serializable { PAID_CUMULATIVE_UPKEEP, DIDNT_PAY_CUMULATIVE_UPKEEP, //permanent events - ENTERS_THE_BATTLEFIELD, + ENTERS_THE_BATTLEFIELD_SELF, // 616.1a If any of the replacement and/or prevention effects are self-replacement effects (see rule 614.15), one of them must be chosen. If not, proceed to rule 616.1b. + ENTERS_THE_BATTLEFIELD_CONTROL, // 616.1b + ENTERS_THE_BATTLEFIELD_COPY, // 616.1c + ENTERS_THE_BATTLEFIELD, // 616.1d TAP, TAPPED, TAPPED_FOR_MANA, UNTAP, UNTAPPED, FLIP, FLIPPED, diff --git a/Mage/src/main/java/mage/game/permanent/Permanent.java b/Mage/src/main/java/mage/game/permanent/Permanent.java index 37f2a7efa2e..f4071c12148 100644 --- a/Mage/src/main/java/mage/game/permanent/Permanent.java +++ b/Mage/src/main/java/mage/game/permanent/Permanent.java @@ -149,6 +149,8 @@ public interface Permanent extends Card, Controllable { void reset(Game game); + MageObject getBasicMageObject(Game game); + boolean destroy(UUID sourceId, Game game, boolean noRegen); boolean sacrifice(UUID sourceId, Game game); diff --git a/Mage/src/main/java/mage/game/permanent/PermanentCard.java b/Mage/src/main/java/mage/game/permanent/PermanentCard.java index 9ff7eb7578a..c3ff27de593 100644 --- a/Mage/src/main/java/mage/game/permanent/PermanentCard.java +++ b/Mage/src/main/java/mage/game/permanent/PermanentCard.java @@ -28,6 +28,7 @@ package mage.game.permanent; import java.util.UUID; +import mage.MageObject; import mage.abilities.Abilities; import mage.abilities.Ability; import mage.abilities.costs.mana.ManaCost; @@ -44,6 +45,7 @@ import mage.game.events.ZoneChangeEvent; public class PermanentCard extends PermanentImpl { protected int maxLevelCounters; + // A copy of the origin card that was cast (this is not the original card, so it's possible to chnage some attribute to this blueprint to change attributes to the permanent if it enters the battlefield with e.g. a subtype) protected Card card; // the number this permanent instance had protected int zoneChangeCounter; @@ -141,6 +143,11 @@ public class PermanentCard extends PermanentImpl { this.flipCardName = card.getFlipCardName(); } + @Override + public MageObject getBasicMageObject(Game game) { + return card; + } + public Card getCard() { return card; } diff --git a/Mage/src/main/java/mage/game/permanent/PermanentImpl.java b/Mage/src/main/java/mage/game/permanent/PermanentImpl.java index 23f00de9823..b8a21942091 100644 --- a/Mage/src/main/java/mage/game/permanent/PermanentImpl.java +++ b/Mage/src/main/java/mage/game/permanent/PermanentImpl.java @@ -59,6 +59,7 @@ import mage.cards.CardImpl; import mage.constants.AsThoughEffectType; import mage.constants.CardType; import mage.constants.EffectType; +import mage.constants.EnterEventType; import mage.constants.Rarity; import mage.constants.Zone; import mage.counters.Counter; @@ -872,12 +873,18 @@ public abstract class PermanentImpl extends CardImpl implements Permanent { // remove some attributes here, because first apply effects comes later otherwise abilities (e.g. color related) will unintended trigger MorphAbility.setPermanentToFaceDownCreature(this); } - EntersTheBattlefieldEvent event = new EntersTheBattlefieldEvent(this, sourceId, getControllerId(), fromZone); + + EntersTheBattlefieldEvent event = new EntersTheBattlefieldEvent(this, sourceId, getControllerId(), fromZone, EnterEventType.SELF); + if (game.replaceEvent(event)) { + return false; + } + event = new EntersTheBattlefieldEvent(this, sourceId, getControllerId(), fromZone); if (!game.replaceEvent(event)) { if (fireEvent) { game.addSimultaneousEvent(event); return true; } + } return false; } diff --git a/Mage/src/main/java/mage/game/permanent/PermanentToken.java b/Mage/src/main/java/mage/game/permanent/PermanentToken.java index fe51ad6c62b..c190345d9a1 100644 --- a/Mage/src/main/java/mage/game/permanent/PermanentToken.java +++ b/Mage/src/main/java/mage/game/permanent/PermanentToken.java @@ -28,6 +28,7 @@ package mage.game.permanent; import java.util.UUID; +import mage.MageObject; import mage.abilities.Ability; import mage.abilities.costs.mana.ManaCost; import mage.game.Game; @@ -92,6 +93,11 @@ public class PermanentToken extends PermanentImpl { this.tokenDescriptor = token.getTokenDescriptor(); } + @Override + public MageObject getBasicMageObject(Game game) { + return token; + } + public Token getToken() { return token; } diff --git a/Mage/src/main/java/mage/game/permanent/token/DevilToken.java b/Mage/src/main/java/mage/game/permanent/token/DevilToken.java index 8b3e2cafccb..4b67258340a 100644 --- a/Mage/src/main/java/mage/game/permanent/token/DevilToken.java +++ b/Mage/src/main/java/mage/game/permanent/token/DevilToken.java @@ -27,7 +27,6 @@ */ package mage.game.permanent.token; -import java.util.Arrays; import java.util.Collections; import mage.MageInt; diff --git a/Mage/src/main/java/mage/game/permanent/token/DroidToken.java b/Mage/src/main/java/mage/game/permanent/token/DroidToken.java index d9a440efad6..bf94743f5cb 100644 --- a/Mage/src/main/java/mage/game/permanent/token/DroidToken.java +++ b/Mage/src/main/java/mage/game/permanent/token/DroidToken.java @@ -27,7 +27,6 @@ */ package mage.game.permanent.token; -import java.util.Arrays; import java.util.Collections; import mage.MageInt; diff --git a/Mage/src/main/java/mage/game/permanent/token/EldraziHorrorToken.java b/Mage/src/main/java/mage/game/permanent/token/EldraziHorrorToken.java index 1ec3623b87f..15dd2d04b0e 100644 --- a/Mage/src/main/java/mage/game/permanent/token/EldraziHorrorToken.java +++ b/Mage/src/main/java/mage/game/permanent/token/EldraziHorrorToken.java @@ -28,7 +28,6 @@ package mage.game.permanent.token; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import mage.MageInt; diff --git a/Mage/src/main/java/mage/game/permanent/token/EwokToken.java b/Mage/src/main/java/mage/game/permanent/token/EwokToken.java index 1d930992c5d..740a1a58d8f 100644 --- a/Mage/src/main/java/mage/game/permanent/token/EwokToken.java +++ b/Mage/src/main/java/mage/game/permanent/token/EwokToken.java @@ -27,7 +27,6 @@ */ package mage.game.permanent.token; -import java.util.Arrays; import java.util.Collections; import mage.constants.CardType; diff --git a/Mage/src/main/java/mage/game/permanent/token/GremlinToken.java b/Mage/src/main/java/mage/game/permanent/token/GremlinToken.java new file mode 100644 index 00000000000..9a47d9a9a8d --- /dev/null +++ b/Mage/src/main/java/mage/game/permanent/token/GremlinToken.java @@ -0,0 +1,48 @@ +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.game.permanent.token; + +import mage.MageInt; +import mage.constants.CardType; + +/** + * + * @author Styxo + */ +public class GremlinToken extends Token { + + public GremlinToken() { + super("Gremlin", "2/2 red Gremlin creature token"); + cardType.add(CardType.CREATURE); + this.setOriginalExpansionSetCode("AER"); + subtype.add("Gremlin"); + color.setRed(true); + power = new MageInt(2); + toughness = new MageInt(2); + } +} diff --git a/Mage/src/main/java/mage/game/permanent/token/PrismToken.java b/Mage/src/main/java/mage/game/permanent/token/PrismToken.java index b59ddd270f0..cb9f56b4485 100644 --- a/Mage/src/main/java/mage/game/permanent/token/PrismToken.java +++ b/Mage/src/main/java/mage/game/permanent/token/PrismToken.java @@ -28,7 +28,6 @@ package mage.game.permanent.token; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import mage.MageInt; diff --git a/Mage/src/main/java/mage/game/permanent/token/ServoToken.java b/Mage/src/main/java/mage/game/permanent/token/ServoToken.java index 0c9db5b39f0..6be5dc0bde3 100644 --- a/Mage/src/main/java/mage/game/permanent/token/ServoToken.java +++ b/Mage/src/main/java/mage/game/permanent/token/ServoToken.java @@ -28,7 +28,6 @@ package mage.game.permanent.token; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import mage.MageInt; diff --git a/Mage/src/main/java/mage/game/permanent/token/SquirrelToken.java b/Mage/src/main/java/mage/game/permanent/token/SquirrelToken.java index 77dc0fdabad..347546b0d64 100644 --- a/Mage/src/main/java/mage/game/permanent/token/SquirrelToken.java +++ b/Mage/src/main/java/mage/game/permanent/token/SquirrelToken.java @@ -28,7 +28,6 @@ package mage.game.permanent.token; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import mage.MageInt; diff --git a/Mage/src/main/java/mage/game/permanent/token/ThrullToken.java b/Mage/src/main/java/mage/game/permanent/token/ThrullToken.java index 759a93d2010..ca6bd3b3e38 100644 --- a/Mage/src/main/java/mage/game/permanent/token/ThrullToken.java +++ b/Mage/src/main/java/mage/game/permanent/token/ThrullToken.java @@ -29,7 +29,6 @@ package mage.game.permanent.token; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import mage.MageInt; diff --git a/Mage/src/main/java/mage/game/permanent/token/TrooperToken.java b/Mage/src/main/java/mage/game/permanent/token/TrooperToken.java index 00a5b43e450..3270d6b0b71 100644 --- a/Mage/src/main/java/mage/game/permanent/token/TrooperToken.java +++ b/Mage/src/main/java/mage/game/permanent/token/TrooperToken.java @@ -27,7 +27,6 @@ */ package mage.game.permanent.token; -import java.util.Arrays; import java.util.Collections; import mage.MageInt; diff --git a/Mage/src/main/java/mage/game/stack/Spell.java b/Mage/src/main/java/mage/game/stack/Spell.java index 3fd17d3a5eb..57a0fb74f9c 100644 --- a/Mage/src/main/java/mage/game/stack/Spell.java +++ b/Mage/src/main/java/mage/game/stack/Spell.java @@ -161,6 +161,7 @@ public class Spell extends StackObjImpl implements Card { } } } + setDoneActivatingManaAbilities(false); // can be activated again maybe during the resolution of the spell (e.g. Metallic Rebuke) return true; } @@ -256,8 +257,8 @@ public class Spell extends StackObjImpl implements Card { Permanent permanent = game.getPermanent(card.getId()); if (permanent != null && permanent instanceof PermanentCard) { permanent.setSpellAbility(ability); // otherwise spell ability without bestow will be set - ((PermanentCard) permanent).getCard().getCardType().add(CardType.CREATURE); - ((PermanentCard) permanent).getCard().getSubtype(game).remove("Aura"); + card.getCardType().add(CardType.CREATURE); + card.getSubtype(game).remove("Aura"); } } return ability.resolve(game); @@ -270,7 +271,15 @@ public class Spell extends StackObjImpl implements Card { // Aura has no legal target and its a bestow enchantment -> Add it to battlefield as creature if (this.getSpellAbility() instanceof BestowAbility) { updateOptionalCosts(0); - return controller.moveCards(card, Zone.BATTLEFIELD, ability, game, false, faceDown, false, null); + if (controller.moveCards(card, Zone.BATTLEFIELD, ability, game, false, faceDown, false, null)) { + Permanent permanent = game.getPermanent(card.getId()); + if (permanent != null && permanent instanceof PermanentCard) { + ((PermanentCard) permanent).getCard().getCardType().add(CardType.CREATURE); + ((PermanentCard) permanent).getCard().getSubtype(game).remove("Aura"); + return true; + } + } + return false; } else { //20091005 - 608.2b if (!game.isSimulation()) { diff --git a/Mage/src/main/java/mage/game/turn/Phase.java b/Mage/src/main/java/mage/game/turn/Phase.java index 4d2d1a0d331..e4b276336e1 100644 --- a/Mage/src/main/java/mage/game/turn/Phase.java +++ b/Mage/src/main/java/mage/game/turn/Phase.java @@ -107,7 +107,7 @@ public abstract class Phase implements Serializable { if (game.isPaused() || game.gameOver(null)) { return false; } - if (game.getTurn().isEndTurnRequested() && !step.getType().equals(PhaseStep.CLEANUP)) { + if (game.getTurn().isEndTurnRequested() && step.getType()!=PhaseStep.CLEANUP) { continue; } currentStep = step; diff --git a/Mage/src/main/java/mage/players/Library.java b/Mage/src/main/java/mage/players/Library.java index f8a4d2bae4b..b4f5e44a1a1 100644 --- a/Mage/src/main/java/mage/players/Library.java +++ b/Mage/src/main/java/mage/players/Library.java @@ -208,9 +208,7 @@ public class Library implements Serializable { Map cards = new HashMap<>(); for (UUID cardId : library) { Card card = game.getCard(cardId); - if (!cards.containsKey(card.getName())) { - cards.put(card.getName(), card); - } + cards.putIfAbsent(card.getName(), card); } return cards.values(); } diff --git a/Mage/src/main/java/mage/players/PlayerImpl.java b/Mage/src/main/java/mage/players/PlayerImpl.java index 9efa5814256..70308b01bbe 100644 --- a/Mage/src/main/java/mage/players/PlayerImpl.java +++ b/Mage/src/main/java/mage/players/PlayerImpl.java @@ -29,53 +29,22 @@ package mage.players; import java.io.Serializable; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; -import java.util.UUID; import mage.ConditionalMana; import mage.MageObject; import mage.Mana; -import mage.abilities.Abilities; -import mage.abilities.AbilitiesImpl; -import mage.abilities.Ability; -import mage.abilities.ActivatedAbility; -import mage.abilities.DelayedTriggeredAbility; -import mage.abilities.Mode; -import mage.abilities.PlayLandAbility; -import mage.abilities.SpecialAction; -import mage.abilities.SpellAbility; -import mage.abilities.TriggeredAbility; +import mage.abilities.*; import mage.abilities.common.PassAbility; import mage.abilities.common.delayed.AtTheEndOfTurnStepPostDelayedTriggeredAbility; -import mage.abilities.costs.AdjustingSourceCosts; -import mage.abilities.costs.AlternativeCostSourceAbility; -import mage.abilities.costs.AlternativeSourceCosts; -import mage.abilities.costs.Cost; -import mage.abilities.costs.Costs; -import mage.abilities.costs.OptionalAdditionalSourceCosts; +import mage.abilities.costs.*; import mage.abilities.costs.mana.ManaCost; import mage.abilities.costs.mana.ManaCosts; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.RestrictionEffect; import mage.abilities.effects.RestrictionUntapNotMoreThanEffect; import mage.abilities.effects.common.LoseControlOnOtherPlayersControllerEffect; -import mage.abilities.keyword.ConvokeAbility; -import mage.abilities.keyword.FlashbackAbility; -import mage.abilities.keyword.HexproofAbility; -import mage.abilities.keyword.InfectAbility; -import mage.abilities.keyword.LifelinkAbility; -import mage.abilities.keyword.ProtectionAbility; -import mage.abilities.keyword.ShroudAbility; +import mage.abilities.keyword.*; import mage.abilities.mana.ActivatedManaAbilityImpl; import mage.abilities.mana.ManaOptions; import mage.actions.MageDrawAction; @@ -84,17 +53,7 @@ import mage.cards.Cards; import mage.cards.CardsImpl; import mage.cards.SplitCard; import mage.cards.decks.Deck; -import mage.constants.AbilityType; -import mage.constants.AsThoughEffectType; -import mage.constants.CardType; -import mage.constants.ManaType; -import mage.constants.Outcome; -import mage.constants.PhaseStep; -import mage.constants.PlayerAction; -import mage.constants.RangeOfInfluence; -import mage.constants.SpellAbilityType; -import mage.constants.TimingRule; -import mage.constants.Zone; +import mage.constants.*; import mage.counters.Counter; import mage.counters.CounterType; import mage.counters.Counters; @@ -105,12 +64,7 @@ import mage.filter.common.FilterCreatureForCombat; import mage.filter.common.FilterCreatureForCombatBlock; import mage.filter.predicate.Predicates; import mage.filter.predicate.permanent.PermanentIdPredicate; -import mage.game.ExileZone; -import mage.game.Game; -import mage.game.Graveyard; -import mage.game.Table; -import mage.game.ZoneChangeInfo; -import mage.game.ZonesHandler; +import mage.game.*; import mage.game.combat.CombatGroup; import mage.game.command.CommandObject; import mage.game.events.DamagePlayerEvent; @@ -472,7 +426,6 @@ public abstract class PlayerImpl implements Player, Serializable { /** * called before apply effects - * */ @Override public void reset() { @@ -701,7 +654,6 @@ public abstract class PlayerImpl implements Player, Serializable { } /** - * * @param amount * @param source * @param game @@ -998,7 +950,7 @@ public abstract class PlayerImpl implements Player, Serializable { if (game == null || ability == null) { return false; } - if (!ability.getSpellAbilityType().equals(SpellAbilityType.BASE)) { + if (ability.getSpellAbilityType() != SpellAbilityType.BASE) { ability = chooseSpellAbilityForCast(ability, game, noMana); } //20091005 - 601.2a @@ -1221,7 +1173,7 @@ public abstract class PlayerImpl implements Player, Serializable { //if player has taken an action then reset all player passed flags justActivatedType = null; if (result) { - if (isHuman() && (ability.getAbilityType().equals(AbilityType.SPELL) || ability.getAbilityType().equals(AbilityType.ACTIVATED))) { + if (isHuman() && (ability.getAbilityType() == AbilityType.SPELL || ability.getAbilityType() == AbilityType.ACTIVATED)) { if (ability.isUsesStack()) { // if the ability does not use the stack (e.g. Suspend) auto pass would go to next phase unintended setJustActivatedType(ability.getAbilityType()); } @@ -1269,8 +1221,8 @@ public abstract class PlayerImpl implements Player, Serializable { LinkedHashMap useable = new LinkedHashMap<>(); for (Ability ability : object.getAbilities()) { if (ability instanceof SpellAbility) { - if (((SpellAbility) ability).getSpellAbilityType().equals(SpellAbilityType.SPLIT_FUSED)) { - if (zone.equals(Zone.HAND)) { + if (((SpellAbility) ability).getSpellAbilityType() == SpellAbilityType.SPLIT_FUSED) { + if (zone == Zone.HAND) { // Fix so you don't need to choose Fuse twice useable.clear(); useable.put(ability.getId(), (SpellAbility) ability); @@ -1280,7 +1232,7 @@ public abstract class PlayerImpl implements Player, Serializable { continue; } } - if (((SpellAbility) ability).getSpellAbilityType().equals(SpellAbilityType.SPLIT)) { + if (((SpellAbility) ability).getSpellAbilityType() == SpellAbilityType.SPLIT) { continue; } useable.put(ability.getId(), (SpellAbility) ability); @@ -1297,7 +1249,7 @@ public abstract class PlayerImpl implements Player, Serializable { // ManaOptions availableMana = getManaAvailable(game); // can only be activated if mana calculation works flawless otherwise player can't play spells they could play if calculation would work correctly // availableMana.addMana(manaPool.getMana()); for (Ability ability : object.getAbilities()) { - if (canUse || ability.getAbilityType().equals(AbilityType.SPECIAL_ACTION)) { + if (canUse || ability.getAbilityType() == AbilityType.SPECIAL_ACTION) { if (ability.getZone().match(zone)) { if (ability instanceof ActivatedAbility) { if (ability instanceof ActivatedManaAbilityImpl) { @@ -1320,9 +1272,9 @@ public abstract class PlayerImpl implements Player, Serializable { } } if (zone != Zone.HAND) { - if (Zone.GRAVEYARD.equals(zone) && canPlayCardsFromGraveyard()) { + if (Zone.GRAVEYARD == zone && canPlayCardsFromGraveyard()) { for (ActivatedAbility ability : object.getAbilities().getPlayableAbilities(Zone.HAND)) { - if (canUse || ability.getAbilityType().equals(AbilityType.SPECIAL_ACTION)) { + if (canUse || ability.getAbilityType() == AbilityType.SPECIAL_ACTION) { if (ability.getManaCosts().isEmpty() && ability.getCosts().isEmpty() && ability instanceof SpellAbility) { continue; // You can't play spells from graveyard that have no costs } @@ -1334,7 +1286,7 @@ public abstract class PlayerImpl implements Player, Serializable { } if (zone != Zone.BATTLEFIELD && game.getContinuousEffects().asThough(object.getId(), AsThoughEffectType.PLAY_FROM_NOT_OWN_HAND_ZONE, this.getId(), game)) { for (Ability ability : object.getAbilities()) { - if (canUse || ability.getAbilityType().equals(AbilityType.SPECIAL_ACTION)) { + if (canUse || ability.getAbilityType() == AbilityType.SPECIAL_ACTION) { if (ability.getManaCosts().isEmpty() && ability.getCosts().isEmpty() && ability instanceof SpellAbility && !(ability.getSourceId() == getCastSourceIdWithAlternateMana())) { continue; // You can't play spells that have no costs, unless you can play them without paying their mana costs } @@ -1358,7 +1310,7 @@ public abstract class PlayerImpl implements Player, Serializable { if (otherAbilities != null) { boolean canUse = !(object instanceof Permanent) || ((Permanent) object).canUseActivatedAbilities(game); for (ActivatedAbility ability : otherAbilities) { - if (canUse || ability.getAbilityType().equals(AbilityType.SPECIAL_ACTION)) { + if (canUse || ability.getAbilityType() == AbilityType.SPECIAL_ACTION) { Card card = game.getCard(ability.getSourceId()); if (card.isSplitCard() && ability instanceof FlashbackAbility) { FlashbackAbility flashbackAbility; @@ -1401,7 +1353,7 @@ public abstract class PlayerImpl implements Player, Serializable { LinkedHashMap useable = new LinkedHashMap<>(); boolean canUse = !(object instanceof Permanent) || ((Permanent) object).canUseActivatedAbilities(game); for (ActivatedManaAbilityImpl ability : object.getAbilities().getActivatedManaAbilities(zone)) { - if (canUse || ability.getAbilityType().equals(AbilityType.SPECIAL_ACTION)) { + if (canUse || ability.getAbilityType() == AbilityType.SPECIAL_ACTION) { if (ability.canActivate(playerId, game)) { useable.put(ability.getId(), ability); } @@ -2057,7 +2009,7 @@ public abstract class PlayerImpl implements Player, Serializable { passedUntilEndOfTurn = true; passedUntilStackResolved = false; passedUntilEndStepBeforeMyTurn = false; - skippedAtLeastOnce = !PhaseStep.END_TURN.equals(game.getTurn().getStepType()); + skippedAtLeastOnce = PhaseStep.END_TURN != game.getTurn().getStepType(); this.skip(); break; case PASS_PRIORITY_UNTIL_NEXT_TURN: // F4 @@ -2088,7 +2040,7 @@ public abstract class PlayerImpl implements Player, Serializable { passedUntilNextMain = true; passedUntilStackResolved = false; passedUntilEndStepBeforeMyTurn = false; - skippedAtLeastOnce = !(game.getTurn().getStepType().equals(PhaseStep.POSTCOMBAT_MAIN) || game.getTurn().getStepType().equals(PhaseStep.PRECOMBAT_MAIN)); + skippedAtLeastOnce = !(game.getTurn().getStepType() == PhaseStep.POSTCOMBAT_MAIN || game.getTurn().getStepType() == PhaseStep.PRECOMBAT_MAIN); this.skip(); break; case PASS_PRIORITY_UNTIL_STACK_RESOLVED: //F8 @@ -2333,7 +2285,6 @@ public abstract class PlayerImpl implements Player, Serializable { /** * @param game * @param appliedEffects - * * @return true if player won the toss */ @Override @@ -2470,7 +2421,6 @@ public abstract class PlayerImpl implements Player, Serializable { } /** - * * @param ability * @param available if null, it won't be checked if enough mana is available * @param sourceObject @@ -2608,7 +2558,7 @@ public abstract class PlayerImpl implements Player, Serializable { if (!(sourceObject instanceof Permanent)) { Ability sourceAbility = null; for (Ability landAbility : sourceObject.getAbilities()) { - if (landAbility.getAbilityType().equals(AbilityType.PLAY_LAND)) { + if (landAbility.getAbilityType() == AbilityType.PLAY_LAND) { sourceAbility = landAbility; break; } @@ -2748,9 +2698,7 @@ public abstract class PlayerImpl implements Player, Serializable { for (Permanent permanent : game.getBattlefield().getAllActivePermanents(playerId)) { LinkedHashMap useableAbilities = getUseableActivatedAbilities(permanent, Zone.BATTLEFIELD, game); for (ActivatedAbility ability : useableAbilities.values()) { - if (!playableActivated.containsKey(ability.toString())) { - playableActivated.put(ability.toString(), ability); - } + playableActivated.putIfAbsent(ability.toString(), ability); } } // activated abilities from stack objects @@ -2781,10 +2729,8 @@ public abstract class PlayerImpl implements Player, Serializable { * Creates a list of card ids that are currently playable.
* Used to mark the playable cards in GameView * - * @return A Set of cardIds that are playable - * * @param game - * + * @return A Set of cardIds that are playable */ @Override public Set getPlayableInHand(Game game @@ -3191,8 +3137,8 @@ public abstract class PlayerImpl implements Player, Serializable { case HAND: for (Card card : cards) { fromZone = game.getState().getZone(card.getId()); - boolean hideCard = fromZone.equals(Zone.LIBRARY) - || (card.isFaceDown(game) && !fromZone.equals(Zone.STACK) && !fromZone.equals(Zone.BATTLEFIELD)); + boolean hideCard = fromZone == Zone.LIBRARY + || (card.isFaceDown(game) && fromZone != Zone.STACK && fromZone != Zone.BATTLEFIELD); if (moveCardToHandWithInfo(card, source == null ? null : source.getSourceId(), game, !hideCard)) { successfulMovedCards.add(card); } @@ -3201,7 +3147,7 @@ public abstract class PlayerImpl implements Player, Serializable { case EXILED: for (Card card : cards) { fromZone = game.getState().getZone(card.getId()); - boolean withName = (fromZone.equals(Zone.BATTLEFIELD) || fromZone.equals(Zone.STACK)) || !card.isFaceDown(game); + boolean withName = (fromZone == Zone.BATTLEFIELD || fromZone == Zone.STACK) || !card.isFaceDown(game); if (moveCardToExileWithInfo(card, null, "", source == null ? null : source.getSourceId(), game, fromZone, withName)) { successfulMovedCards.add(card); } @@ -3214,7 +3160,7 @@ public abstract class PlayerImpl implements Player, Serializable { } else { fromZone = game.getState().getZone(card.getId()); } - boolean hideCard = fromZone.equals(Zone.HAND) || fromZone.equals(Zone.LIBRARY); + boolean hideCard = fromZone == Zone.HAND || fromZone == Zone.LIBRARY; if (moveCardToLibraryWithInfo(card, source == null ? null : source.getSourceId(), game, fromZone, true, !hideCard)) { successfulMovedCards.add(card); } @@ -3255,7 +3201,7 @@ public abstract class PlayerImpl implements Player, Serializable { public boolean moveCardToHandWithInfo(Card card, UUID sourceId, Game game, boolean withName) { boolean result = false; Zone fromZone = game.getState().getZone(card.getId()); - if (fromZone.equals(Zone.BATTLEFIELD) && !(card instanceof Permanent)) { + if (fromZone == Zone.BATTLEFIELD && !(card instanceof Permanent)) { card = game.getPermanent(card.getId()); } if (card.moveToZone(Zone.HAND, sourceId, game, false)) { @@ -3345,7 +3291,7 @@ public abstract class PlayerImpl implements Player, Serializable { public boolean moveCardToGraveyardWithInfo(Card card, UUID sourceId, Game game, Zone fromZone) { boolean result = false; // Zone fromZone = game.getState().getZone(card.getId()); - if (card.moveToZone(Zone.GRAVEYARD, sourceId, game, fromZone != null ? fromZone.equals(Zone.BATTLEFIELD) : false)) { + if (card.moveToZone(Zone.GRAVEYARD, sourceId, game, fromZone != null ? fromZone == Zone.BATTLEFIELD : false)) { if (!game.isSimulation()) { if (card instanceof PermanentCard && game.getCard(card.getId()) != null) { card = game.getCard(card.getId()); @@ -3406,7 +3352,7 @@ public abstract class PlayerImpl implements Player, Serializable { card = basicCard; } } - game.informPlayers(this.getLogName() + " moves " + (withName ? card.getLogName() : "a card face down") + " " + game.informPlayers(this.getLogName() + " moves " + (withName ? card.getLogName() + (card.isCopy() ? " (Copy)" : "") : "a card face down") + " " + (fromZone != null ? "from " + fromZone.toString().toLowerCase(Locale.ENGLISH) + " " : "") + "to the exile zone"); } result = true; diff --git a/Mage/src/main/java/mage/target/TargetImpl.java b/Mage/src/main/java/mage/target/TargetImpl.java index 4e6f9cc4c74..0bd012dd1ba 100644 --- a/Mage/src/main/java/mage/target/TargetImpl.java +++ b/Mage/src/main/java/mage/target/TargetImpl.java @@ -36,6 +36,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; + import mage.MageObject; import mage.abilities.Ability; import mage.cards.Card; @@ -49,7 +50,6 @@ import mage.players.Player; import mage.util.RandomUtil; /** - * * @author BetaSteward_at_googlemail.com */ public abstract class TargetImpl implements Target { @@ -184,7 +184,7 @@ public abstract class TargetImpl implements Target { @Override public boolean isRequired(Ability ability) { - return ability == null || ability.isActivated() || !(ability.getAbilityType().equals(AbilityType.SPELL) || ability.getAbilityType().equals(AbilityType.ACTIVATED)); + return ability == null || ability.isActivated() || !(ability.getAbilityType() == AbilityType.SPELL || ability.getAbilityType() == AbilityType.ACTIVATED); } @Override diff --git a/Mage/src/main/java/mage/target/TargetSpell.java b/Mage/src/main/java/mage/target/TargetSpell.java index f679aadddc4..aad10b11ef8 100644 --- a/Mage/src/main/java/mage/target/TargetSpell.java +++ b/Mage/src/main/java/mage/target/TargetSpell.java @@ -132,6 +132,6 @@ public class TargetSpell extends TargetObject { private boolean canBeChosen(StackObject stackObject, UUID sourceID, UUID sourceControllerId, Game game) { return stackObject instanceof Spell && game.getState().getPlayersInRange(sourceControllerId, game).contains(stackObject.getControllerId()) - && filter.match((Spell) stackObject, sourceID, sourceControllerId, game); + && filter.match(stackObject, sourceID, sourceControllerId, game); } } diff --git a/Mage/src/main/java/mage/target/common/TargetCardInLibrary.java b/Mage/src/main/java/mage/target/common/TargetCardInLibrary.java index 699f7278b60..b23298e1074 100644 --- a/Mage/src/main/java/mage/target/common/TargetCardInLibrary.java +++ b/Mage/src/main/java/mage/target/common/TargetCardInLibrary.java @@ -28,7 +28,6 @@ package mage.target.common; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.UUID; diff --git a/Mage/src/main/java/mage/target/common/TargetOpponent.java b/Mage/src/main/java/mage/target/common/TargetOpponent.java index 4483f1e971c..4c4eb6d623c 100644 --- a/Mage/src/main/java/mage/target/common/TargetOpponent.java +++ b/Mage/src/main/java/mage/target/common/TargetOpponent.java @@ -27,12 +27,9 @@ */ package mage.target.common; -import java.util.UUID; import mage.constants.TargetController; -import mage.abilities.Ability; import mage.filter.FilterPlayer; import mage.filter.predicate.other.PlayerPredicate; -import mage.game.Game; import mage.target.TargetPlayer; /** @@ -56,16 +53,6 @@ public class TargetOpponent extends TargetPlayer { super(target); } - @Override - public boolean canChoose(UUID sourceId, UUID sourceControllerId, Game game) { - return super.canChoose(sourceId, sourceControllerId, game); - } - - @Override - public boolean canTarget(UUID id, Ability source, Game game) { - return super.canTarget(id, source, game); - } - @Override public TargetOpponent copy() { return new TargetOpponent(this); diff --git a/Mage/src/main/java/mage/util/CardUtil.java b/Mage/src/main/java/mage/util/CardUtil.java index a007722f8fd..d40647ebae2 100644 --- a/Mage/src/main/java/mage/util/CardUtil.java +++ b/Mage/src/main/java/mage/util/CardUtil.java @@ -69,7 +69,7 @@ public class CardUtil { private static final String SOURCE_EXILE_ZONE_TEXT = "SourceExileZone"; - static String numberStrings[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", + static final String[] numberStrings = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "ninteen", "twenty"}; public static final String[] NON_CHANGELING_SUBTYPES_VALUES = new String[]{ diff --git a/Mage/src/main/java/mage/util/CircularList.java b/Mage/src/main/java/mage/util/CircularList.java index 27eaf144bfa..7a131d4d441 100644 --- a/Mage/src/main/java/mage/util/CircularList.java +++ b/Mage/src/main/java/mage/util/CircularList.java @@ -45,7 +45,7 @@ import java.util.concurrent.locks.ReentrantLock; public class CircularList implements List, Iterable, Serializable { //TODO: might have to make E extend Copyable - protected List list = new ArrayList<>(); + protected final List list = new ArrayList<>(); protected final ReentrantLock lock = new ReentrantLock(); @@ -357,8 +357,8 @@ public class CircularList implements List, Iterable, Serializable { private class CircularIterator implements Iterator { int cursor; - int lastIndex; - int curModCount; + final int lastIndex; + final int curModCount; boolean hasMoved = false; private CircularIterator() { @@ -399,9 +399,9 @@ public class CircularList implements List, Iterable, Serializable { private class CircularListIterator implements ListIterator { int cursor; - int lastIndex; - int firstIndex; - int curModCount; + final int lastIndex; + final int firstIndex; + final int curModCount; boolean hasMoved = false; private CircularListIterator() { diff --git a/Mage/src/main/java/mage/util/CopierObjectInputStream.java b/Mage/src/main/java/mage/util/CopierObjectInputStream.java index 72189f7b76a..cfde5cd1c17 100644 --- a/Mage/src/main/java/mage/util/CopierObjectInputStream.java +++ b/Mage/src/main/java/mage/util/CopierObjectInputStream.java @@ -32,7 +32,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; -import java.io.StreamCorruptedException; /** * diff --git a/Mage/src/main/java/mage/util/TargetAddress.java b/Mage/src/main/java/mage/util/TargetAddress.java index 80c5724676d..0a0d1820575 100644 --- a/Mage/src/main/java/mage/util/TargetAddress.java +++ b/Mage/src/main/java/mage/util/TargetAddress.java @@ -42,9 +42,9 @@ import mage.target.Target; */ public class TargetAddress { - protected int spellAbilityIndex; - protected UUID mode; - protected int targetIndex; + protected final int spellAbilityIndex; + protected final UUID mode; + protected final int targetIndex; public TargetAddress(int spellAbilityIndex, UUID mode, int targetIndex) { this.spellAbilityIndex = spellAbilityIndex; @@ -68,7 +68,7 @@ public class TargetAddress { protected static class TargetAddressIterator implements Iterator { - protected Iterator spellAbilityIterator; + protected final Iterator spellAbilityIterator; protected Integer lastSpellAbilityIndex = null; protected Iterator modeIterator = null; protected Modes modes = null; diff --git a/Mage/src/main/java/mage/util/ThreadLocalStringBuilder.java b/Mage/src/main/java/mage/util/ThreadLocalStringBuilder.java index bfa102d83f7..e27257936f8 100644 --- a/Mage/src/main/java/mage/util/ThreadLocalStringBuilder.java +++ b/Mage/src/main/java/mage/util/ThreadLocalStringBuilder.java @@ -6,7 +6,7 @@ package mage.util; */ public class ThreadLocalStringBuilder extends ThreadLocal { - private int size; + private final int size; public ThreadLocalStringBuilder(int size) { this.size = size; diff --git a/Mage/src/main/java/mage/watchers/Watcher.java b/Mage/src/main/java/mage/watchers/Watcher.java index 0ab4efc7547..ad38050b85b 100644 --- a/Mage/src/main/java/mage/watchers/Watcher.java +++ b/Mage/src/main/java/mage/watchers/Watcher.java @@ -57,6 +57,7 @@ public abstract class Watcher implements Serializable { this.controllerId = watcher.controllerId; this.sourceId = watcher.sourceId; this.scope = watcher.scope; + this.basicKey = watcher.basicKey; } public UUID getControllerId() { diff --git a/Mage/src/main/java/mage/watchers/Watchers.java b/Mage/src/main/java/mage/watchers/Watchers.java index 70227e9d2d6..9304e24b572 100644 --- a/Mage/src/main/java/mage/watchers/Watchers.java +++ b/Mage/src/main/java/mage/watchers/Watchers.java @@ -28,7 +28,6 @@ package mage.watchers; import java.util.HashMap; -import java.util.Iterator; import java.util.UUID; import mage.game.Game; import mage.game.events.GameEvent; @@ -43,7 +42,7 @@ public class Watchers extends HashMap { } public Watchers(final Watchers watchers) { - watchers.entrySet().stream().forEach((entry) -> this.put(entry.getKey(), entry.getValue().copy())); + watchers.entrySet().forEach((entry) -> this.put(entry.getKey(), entry.getValue().copy())); } public Watchers copy() { @@ -51,9 +50,7 @@ public class Watchers extends HashMap { } public void add(Watcher watcher) { - if (!this.containsKey(watcher.getKey())) { - this.put(watcher.getKey(), watcher); - } + putIfAbsent(watcher.getKey(), watcher); } public void watch(GameEvent event, Game game) { @@ -63,7 +60,7 @@ public class Watchers extends HashMap { } public void reset() { - this.values().stream().forEach(Watcher::reset); + this.values().forEach(Watcher::reset); } public Watcher get(String key, UUID id) { diff --git a/Mage/src/main/java/mage/watchers/common/CardsPutIntoGraveyardWatcher.java b/Mage/src/main/java/mage/watchers/common/CardsPutIntoGraveyardWatcher.java index f89306278ea..4fbf9765f62 100644 --- a/Mage/src/main/java/mage/watchers/common/CardsPutIntoGraveyardWatcher.java +++ b/Mage/src/main/java/mage/watchers/common/CardsPutIntoGraveyardWatcher.java @@ -33,6 +33,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; + import mage.MageObjectReference; import mage.constants.WatcherScope; import mage.constants.Zone; @@ -80,7 +81,7 @@ public class CardsPutIntoGraveyardWatcher extends Watcher { ++amount; } amountOfCardsThisTurn.put(playerId, amount); - if (((ZoneChangeEvent) event).getFromZone().equals(Zone.BATTLEFIELD)) { + if (((ZoneChangeEvent) event).getFromZone() == Zone.BATTLEFIELD) { cardsPutToGraveyardFromBattlefield.add(new MageObjectReference(event.getTargetId(), game)); } } diff --git a/Mage/src/main/java/mage/watchers/common/CastFromGraveyardWatcher.java b/Mage/src/main/java/mage/watchers/common/CastFromGraveyardWatcher.java index 41d07639af4..44e831b1f58 100644 --- a/Mage/src/main/java/mage/watchers/common/CastFromGraveyardWatcher.java +++ b/Mage/src/main/java/mage/watchers/common/CastFromGraveyardWatcher.java @@ -66,11 +66,7 @@ public class CastFromGraveyardWatcher extends Watcher { if (event.getType() == GameEvent.EventType.SPELL_CAST && event.getZone().equals(Zone.GRAVEYARD)) { Spell spell = (Spell) game.getObject(event.getTargetId()); if (spell != null) { - HashSet zcc = spellsCastFromGraveyard.get(spell.getSourceId()); - if (zcc == null) { - zcc = new HashSet<>(); - spellsCastFromGraveyard.put(spell.getSourceId(), zcc); - } + HashSet zcc = spellsCastFromGraveyard.computeIfAbsent(spell.getSourceId(), k -> new HashSet<>()); zcc.add(spell.getZoneChangeCounter(game)); } diff --git a/Mage/src/main/java/mage/watchers/common/FirstTimeStepWatcher.java b/Mage/src/main/java/mage/watchers/common/FirstTimeStepWatcher.java index d216f48d37a..303f4586a24 100644 --- a/Mage/src/main/java/mage/watchers/common/FirstTimeStepWatcher.java +++ b/Mage/src/main/java/mage/watchers/common/FirstTimeStepWatcher.java @@ -64,9 +64,4 @@ public class FirstTimeStepWatcher extends Watcher { condition = true; } } - - @Override - public void reset() { - super.reset(); - } } diff --git a/Mage/src/test/java/mage/counters/CounterTest.java b/Mage/src/test/java/mage/counters/CounterTest.java index 77bb39cf010..6d0037f5f38 100644 --- a/Mage/src/test/java/mage/counters/CounterTest.java +++ b/Mage/src/test/java/mage/counters/CounterTest.java @@ -1,10 +1,9 @@ package mage.counters; +import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - /** * Custom unit tests for {@link Counter} */ @@ -17,20 +16,6 @@ public class CounterTest { counter = new Counter("test", 1); } - - @Test - public void shouldIncreaseCounter() { - // given - - // when - counter.increase(); - - // then - assertEquals(2, counter.getCount()); - assertEquals("test", counter.getName()); - } - - @Test public void shouldAddMana() { // given @@ -42,38 +27,10 @@ public class CounterTest { assertEquals(6, counter.getCount()); } - - @Test - public void shouldDecreaseCounter() { - // given - - - // when - counter.decrease(); - - // then - assertEquals(0, counter.getCount()); - } - - - @Test - public void shouldNotDecreaseToLessThanZero() { - // given - - // when - counter.decrease(); - counter.decrease(); - - // then - assertEquals(0, counter.getCount()); - } - - @Test public void shouldRemoveCounters() { // given - // when counter.remove(1); @@ -81,7 +38,6 @@ public class CounterTest { assertEquals(0, counter.getCount()); } - @Test public void shouldNotRemoveMoreCountersThanAvailable() { // given @@ -93,7 +49,6 @@ public class CounterTest { assertEquals(0, counter.getCount()); } - @Test public void shouldReturnCopy() { // given @@ -106,7 +61,6 @@ public class CounterTest { assertFalse(copy == counter); } - @Test public void shouldCreateCounterFromCounter() { // given @@ -119,12 +73,10 @@ public class CounterTest { assertEquals("test", copy.getName()); } - @Test public void shouldCreatDefaultCounter() { // given - // when Counter defaultCounter = new Counter("default"); @@ -132,4 +84,4 @@ public class CounterTest { assertEquals(1, defaultCounter.getCount()); assertEquals("default", defaultCounter.getName()); } -} \ No newline at end of file +} diff --git a/Utils/gen-card.pl b/Utils/gen-card.pl index 44bf93cadaa..31a30365dc2 100755 --- a/Utils/gen-card.pl +++ b/Utils/gen-card.pl @@ -108,7 +108,7 @@ if (!exists $cards{$cardName}) { } # Check if card is already implemented -my $fileName = "../Mage.Sets/src/mage/cards/".substr($cardName, 0, 1)."/".toCamelCase($cardName).".java"; +my $fileName = "../Mage.Sets/src/mage/cards/".lc(substr($cardName, 0, 1))."/".toCamelCase($cardName).".java"; if(-e $fileName) { die "$cardName is already implemented.\n"; } diff --git a/Utils/mtg-cards-data.txt b/Utils/mtg-cards-data.txt index f0f03b4cdfe..78e73d2867c 100644 --- a/Utils/mtg-cards-data.txt +++ b/Utils/mtg-cards-data.txt @@ -30403,7 +30403,7 @@ Shipwreck Moray|Aether Revolt|45|C|{3}{U}|Creature - Fish|0|5|When Shipwreck Mor Skyship Plunderer|Aether Revolt|46|U|{1}{U}|Creature - Human Pirate|2|1|Flying$Whenever Skyship Plunderer deals combat damage to a player, for each kind of counter on target permanent or player, give that permanent or player another counter of that kind.| Take into Custody|Aether Revolt|47|C|{U}|Instant|||Tap target creature. It doesn't untap during its controller's next untap step.| Trophy Mage|Aether Revolt|48|U|{2}{U}|Creature - Human Wizard|2|2|When Trophy Mage enters the battlefield, you may search your library for an artifact card with converted mana cost 3, reveal it, put it into your hand, then shuffle your library.| -Whir of Invention|Aether Revolt|49|R|{X}{U}{U}{U}|Sorcery|||Improvise (Your artifacts can help cast this spell. Each artifact you tap after you're done activating mana abilities pays for {1}.)$Search your library for an artifact card with converted mana cost X or less, put it onto the battlefield, then shuffle your library.| +Whir of Invention|Aether Revolt|49|R|{X}{U}{U}{U}|Instant|||Improvise (Your artifacts can help cast this spell. Each artifact you tap after you're done activating mana abilities pays for {1}.)$Search your library for an artifact card with converted mana cost X or less, put it onto the battlefield, then shuffle your library.| Wind-King Raiders|Aether Revolt|50|U|{4}{U}{U}|Creature - Human Artificer|4|3|Improvise (Your artifacts can help cast this spell. Each artifact you tap after you're done activating mana abilities pays for {1}.)$Flying| Aether Poisoner|Aether Revolt|51|C|{1}{B}|Creature - Human Artificer|1|1|Deathtouch (Any amount of damage this deals to a creature is enough to destroy it.)$When Aether Poisoner enters the battlefield, you get {E}{E} (two energy counters).$Whenever Aether Poisoner attacks, you may pay {E}{E}. If you do, create a 1/1 colorless Servo artifact creature token.| Alley Strangler|Aether Revolt|52|C|{2}{B}|Creature - Aetherborn Rogue|2|3|Menace| @@ -30470,7 +30470,7 @@ Lifecraft Awakening|Aether Revolt|112|U|{X}{G}|Instant|||Put X +1/+1 counters on Lifecraft Cavalry|Aether Revolt|113|C|{4}{G}|Creature - Elf Warrior|4|4|Trample$Revolt — Lifecraft Cavalry enters the battlefield with two +1/+1 counters on it if a permanent you controlled left the battlefield this turn.| Lifecrafter's Gift|Aether Revolt|114|U|{3}{G}|Instant|||Put a +1/+1 counter on target creature, then put a +1/+1 counter on each creature you control with a +1/+1 counter on it.| Maulfist Revolutionary|Aether Revolt|115|U|{1}{G}{G}|Creature - Human Warrior|3|3|Trample$When Maulfist Revolutionary enters the battlefield or dies, for each kind of counter on target permanent or players, give that permanent or player another counter of that kind.| -Monstrous Onslaught|Aether Revolt|116|U|{3}{G}{G}|Sorcery|||Monstrous Onslaught deals X damage divided as you choose among any number of target creatures, where X is the greater power among creatures you control as you cast Monstrous Onslaught.| +Monstrous Onslaught|Aether Revolt|116|U|{3}{G}{G}|Sorcery|||Monstrous Onslaught deals X damage divided as you choose among any number of target creatures, where X is the greatest power among creatures you control as you cast Monstrous Onslaught.| Narnam Renegade|Aether Revolt|117|U|{G}|Creature - Elf Warrior|1|2|Deathtouch$Revolt — Narnam Renegade enters the battlefield with a +1/+1 counter on it if a permanent you controlled left this battlefield this turn.| Natural Obsolescence|Aether Revolt|118|C|{1}{G}|Instant|||Put target artifact on the bottom of its owner's library.| Peema Aether-Seer|Aether Revolt|119|U|{3}{G}|Creature - Elf Druid|3|2|When Peema Aether-Seer enters the battlefield, you get an amount of {E} (energy counters) equal to the greatest power among creatures you control.$Pay {E}{E}{E}: Target creature blocks this turn if able.| diff --git a/pom.xml b/pom.xml index 86548cf48cd..1c643d77939 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 1.4.20 + 1.4.21 pom Mage Root Mage Root POM @@ -84,7 +84,7 @@ - 1.4.20 + 1.4.21 UTF-8