diff --git a/Mage.Client/src/main/java/mage/client/chat/ChatPanel.java b/Mage.Client/src/main/java/mage/client/chat/ChatPanel.java index 12b95847501..bc8d98adc5c 100644 --- a/Mage.Client/src/main/java/mage/client/chat/ChatPanel.java +++ b/Mage.Client/src/main/java/mage/client/chat/ChatPanel.java @@ -63,7 +63,7 @@ import org.mage.card.arcane.ManaSymbols; * @author BetaSteward_at_googlemail.com, nantuko */ public class ChatPanel extends javax.swing.JPanel { - + private UUID chatId; private Session session; private final List players = new ArrayList<>(); @@ -71,7 +71,7 @@ public class ChatPanel extends javax.swing.JPanel { /** * Chat message color for opponents. */ - private static final String OPPONENT_COLOR = "#FF7F50"; + private static final String OPPONENT_COLOR = "#FF7F50"; /** * Chat message color for client player. */ @@ -123,7 +123,7 @@ public class ChatPanel extends javax.swing.JPanel { private ChatType chatType = ChatType.DEFAULT; private static final int[] defaultColumnsWidth = {20, 100, 100, 80}; - + public enum ChatType { DEFAULT, GAME, TABLES, TOURNAMENT @@ -142,6 +142,7 @@ public class ChatPanel extends javax.swing.JPanel { */ /** * Creates new form ChatPanel + * * @param addPlayersTab */ public ChatPanel(boolean addPlayersTab) { @@ -151,10 +152,10 @@ public class ChatPanel extends javax.swing.JPanel { jTablePlayers.setBackground(new Color(0, 0, 0, ALPHA)); jTablePlayers.setForeground(Color.white); jTablePlayers.setRowSorter(new MageTableRowSorter(userTableModel)); - + TableUtil.setColumnWidthAndOrder(jTablePlayers, defaultColumnsWidth, KEY_USERS_COLUMNS_WIDTH, KEY_USERS_COLUMNS_ORDER); jTablePlayers.setDefaultRenderer(Icon.class, new CountryCellRenderer()); - + if (jScrollPaneTxt != null) { jScrollPaneTxt.setBackground(new Color(0, 0, 0, ALPHA)); jScrollPaneTxt.getViewport().setBackground(new Color(0, 0, 0, ALPHA)); @@ -169,7 +170,7 @@ public class ChatPanel extends javax.swing.JPanel { } public void cleanUp() { - TableUtil.saveColumnWidthAndOrderToPrefs(jTablePlayers, KEY_USERS_COLUMNS_WIDTH, KEY_USERS_COLUMNS_ORDER); + TableUtil.saveColumnWidthAndOrderToPrefs(jTablePlayers, KEY_USERS_COLUMNS_WIDTH, KEY_USERS_COLUMNS_ORDER); } public ChatType getChatType() { @@ -248,7 +249,7 @@ public class ChatPanel extends javax.swing.JPanel { } if (username != null && !username.isEmpty()) { text.append(getColoredText(userColor, username + userSeparator)); - } + } text.append(getColoredText(textColor, ManaSymbols.replaceSymbolsWithHTML(message, ManaSymbols.Type.PAY))); this.txtConversation.append(text.toString()); } @@ -262,6 +263,7 @@ public class ChatPanel extends javax.swing.JPanel { sb.append(""); return sb.toString(); } + public String getText() { return txtConversation.getText(); } @@ -325,8 +327,8 @@ public class ChatPanel extends javax.swing.JPanel { } class UserTableModel extends AbstractTableModel { - - private final String[] columnNames = new String[]{" ","Players", "Info", "Games", "Connection"}; + + private final String[] columnNames = new String[]{"Loc", "Players", "Info", "Games", "Connection"}; private UsersView[] players = new UsersView[0]; public void loadData(Collection roomUserInfoList) throws MageRemoteException { @@ -334,12 +336,12 @@ public class ChatPanel extends javax.swing.JPanel { this.players = roomUserInfo.getUsersView().toArray(new UsersView[0]); JTableHeader th = jTablePlayers.getTableHeader(); TableColumnModel tcm = th.getColumnModel(); - + tcm.getColumn(jTablePlayers.convertColumnIndexToView(1)).setHeaderValue("Players (" + this.players.length + ")"); tcm.getColumn(jTablePlayers.convertColumnIndexToView(3)).setHeaderValue( - "Games " + roomUserInfo.getNumberActiveGames() + - (roomUserInfo.getNumberActiveGames() != roomUserInfo.getNumberGameThreads() ? " (T:" + roomUserInfo.getNumberGameThreads():" (") + - " limit: " + roomUserInfo.getNumberMaxGames() + ")"); + "Games " + roomUserInfo.getNumberActiveGames() + + (roomUserInfo.getNumberActiveGames() != roomUserInfo.getNumberGameThreads() ? " (T:" + roomUserInfo.getNumberGameThreads() : " (") + + " limit: " + roomUserInfo.getNumberMaxGames() + ")"); th.repaint(); this.fireTableDataChanged(); } @@ -358,7 +360,7 @@ public class ChatPanel extends javax.swing.JPanel { public Object getValueAt(int arg0, int arg1) { switch (arg1) { case 0: - return players[arg0].getFlagName(); + return players[arg0].getFlagName(); case 1: return players[arg0].getUserName(); case 2: @@ -389,16 +391,14 @@ public class ChatPanel extends javax.swing.JPanel { return Icon.class; default: return String.class; - } + } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } - - } public void clear() { @@ -486,9 +486,9 @@ public class ChatPanel extends javax.swing.JPanel { layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() - .addComponent(jScrollPaneTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))); + .addComponent(jScrollPaneTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))); jTablePlayers = null; jScrollPanePlayers = null; } 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 4210bf4ffb8..f198e866d29 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/AddLandDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/AddLandDialog.java @@ -1,30 +1,30 @@ /* -* Copyright 2011 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. -*/ + * Copyright 2011 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.client.dialog; import java.util.HashSet; @@ -46,6 +46,7 @@ import mage.cards.repository.ExpansionRepository; import mage.client.MageFrame; import mage.client.constants.Constants.DeckEditorMode; import mage.constants.Rarity; +import org.apache.log4j.Logger; /** * @@ -53,12 +54,16 @@ import mage.constants.Rarity; */ public class AddLandDialog extends MageDialog { + private static final Logger logger = Logger.getLogger(MageDialog.class); + private Deck deck; private final Set setCodesland = new HashSet<>(); - + private static final int DEFAULT_SEALED_DECK_CARD_NUMBER = 40; - /** Creates new form AddLandDialog */ + /** + * Creates new form AddLandDialog + */ public AddLandDialog() { initComponents(); this.setModal(true); @@ -69,7 +74,7 @@ public class AddLandDialog extends MageDialog { SortedSet landSets = new TreeSet<>(); if (!mode.equals(DeckEditorMode.FREE_BUILDING)) { // decide from which sets basic lands are taken from - for (String setCode :deck.getExpansionSetCodes()) { + for (String setCode : deck.getExpansionSetCodes()) { ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode); if (expansionInfo != null && expansionInfo.hasBasicLands()) { this.setCodesland.add(expansionInfo.getCode()); @@ -79,11 +84,11 @@ public class AddLandDialog extends MageDialog { // if sets have no basic land, take land from block if (this.setCodesland.isEmpty()) { - for (String setCode :deck.getExpansionSetCodes()) { + for (String setCode : deck.getExpansionSetCodes()) { ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode); if (expansionInfo != null) { List blockSets = ExpansionRepository.instance.getSetsFromBlock(expansionInfo.getBlockName()); - for (ExpansionInfo blockSet: blockSets) { + for (ExpansionInfo blockSet : blockSets) { if (blockSet.hasBasicLands()) { this.setCodesland.add(blockSet.getCode()); landSets.add(blockSet.getName()); @@ -92,22 +97,22 @@ public class AddLandDialog extends MageDialog { } } } - } + } // if still no set with lands found, add list of all available if (this.setCodesland.isEmpty()) { List basicLandSets = ExpansionRepository.instance.getSetsWithBasicLandsByReleaseDate(); - for (ExpansionInfo expansionInfo: basicLandSets) { + for (ExpansionInfo expansionInfo : basicLandSets) { landSets.add(expansionInfo.getName()); } - } + } if (landSets.isEmpty()) { throw new IllegalArgumentException("No set with basic land was found"); } - if(landSets.size() > 1) { + if (landSets.size() > 1) { landSets.add(""); } cbLandSet.setModel(new DefaultComboBoxModel(landSets.toArray())); - + MageFrame.getDesktop().add(this, JLayeredPane.PALETTE_LAYER); this.setVisible(true); } @@ -115,7 +120,7 @@ public class AddLandDialog extends MageDialog { private void addLands(String landName, int number) { Random random = new Random(); String landSetName = (String) cbLandSet.getSelectedItem(); - + CardCriteria criteria = new CardCriteria(); if (landSetName.equals("")) { criteria.setCodes(setCodesland.toArray(new String[setCodesland.size()])); @@ -123,13 +128,17 @@ public class AddLandDialog extends MageDialog { ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByName(landSetName); if (expansionInfo == null) { throw new IllegalArgumentException("Code of Set " + landSetName + " not found"); - } - criteria.setCodes(expansionInfo.getCode()); - } + } + criteria.setCodes(expansionInfo.getCode()); + } criteria.rarities(Rarity.LAND).name(landName); List cards = CardRepository.instance.findCards(criteria); if (cards.isEmpty()) { - throw new IllegalArgumentException("No basic lands found in Set: " + landSetName); + logger.error("No basic lands found in Set: " + landSetName); + criteria = new CardCriteria(); + criteria.rarities(Rarity.LAND).name(landName); + criteria.setCodes("M15"); + cards = CardRepository.instance.findCards(criteria); } for (int i = 0; i < number; i++) { @@ -138,10 +147,10 @@ public class AddLandDialog extends MageDialog { } } - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents @@ -298,11 +307,11 @@ public class AddLandDialog extends MageDialog { }//GEN-LAST:event_btnCancelActionPerformed private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed - int nForest = ((Number)spnForest.getValue()).intValue(); - int nIsland = ((Number)spnIsland.getValue()).intValue(); - int nMountain = ((Number)spnMountain.getValue()).intValue(); - int nPlains = ((Number)spnPlains.getValue()).intValue(); - int nSwamp = ((Number)spnSwamp.getValue()).intValue(); + int nForest = ((Number) spnForest.getValue()).intValue(); + int nIsland = ((Number) spnIsland.getValue()).intValue(); + int nMountain = ((Number) spnMountain.getValue()).intValue(); + int nPlains = ((Number) spnPlains.getValue()).intValue(); + int nSwamp = ((Number) spnSwamp.getValue()).intValue(); addLands("Forest", nForest); addLands("Island", nIsland); @@ -316,7 +325,7 @@ public class AddLandDialog extends MageDialog { autoAddLands(); }//GEN-LAST:event_btnAutoAddActionPerformed - private void autoAddLands(){ + private void autoAddLands() { int red = 0; int green = 0; int black = 0; @@ -324,7 +333,9 @@ public class AddLandDialog extends MageDialog { int white = 0; Set cards = deck.getCards(); int land_number = DEFAULT_SEALED_DECK_CARD_NUMBER - cards.size(); - if(land_number < 0) land_number = 0; + if (land_number < 0) { + land_number = 0; + } for (Card cd : cards) { Mana m = cd.getManaCost().getMana(); red += m.getRed(); @@ -334,14 +345,18 @@ public class AddLandDialog extends MageDialog { white += m.getWhite(); } int total = red + green + black + blue + white; - int redcards = Math.round(land_number*((float)red/(float)total)); - total -= red; land_number -= redcards; - int greencards = Math.round(land_number*((float)green/(float)total)); - total -= green; land_number -= greencards; - int blackcards = Math.round(land_number*((float)black/(float)total)); - total -= black; land_number -= blackcards; - int bluecards = Math.round(land_number*((float)blue/(float)total)); - total -= blue; land_number -= bluecards; + int redcards = Math.round(land_number * ((float) red / (float) total)); + total -= red; + land_number -= redcards; + int greencards = Math.round(land_number * ((float) green / (float) total)); + total -= green; + land_number -= greencards; + int blackcards = Math.round(land_number * ((float) black / (float) total)); + total -= black; + land_number -= blackcards; + int bluecards = Math.round(land_number * ((float) blue / (float) total)); + total -= blue; + land_number -= bluecards; int whitecards = land_number; spnMountain.setValue(redcards); spnForest.setValue(greencards); @@ -349,7 +364,7 @@ public class AddLandDialog extends MageDialog { spnIsland.setValue(bluecards); spnPlains.setValue(whitecards); } - + // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAdd; private javax.swing.JButton btnAutoAdd; 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 27390bedf11..39f59bf388f 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java @@ -1,30 +1,30 @@ /* -* Copyright 2011 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. -*/ + * Copyright 2011 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. + */ /* * PreferencesDialog.java @@ -63,10 +63,11 @@ import mage.client.MageFrame; import mage.client.util.Config; import mage.client.util.ImageHelper; import mage.client.util.gui.BufferedImageBuilder; +import mage.players.net.UserData; +import mage.players.net.UserGroup; import mage.players.net.UserSkipPrioritySteps; import mage.remote.Connection; import mage.remote.Connection.ProxyType; -import mage.view.UserDataView; import org.apache.log4j.Logger; /** @@ -77,7 +78,7 @@ import org.apache.log4j.Logger; public class PreferencesDialog extends javax.swing.JDialog { private static final transient Logger log = Logger.getLogger(PreferencesDialog.class); - + public static final String KEY_HAND_USE_BIG_CARDS = "handUseBigCards"; public static final String KEY_SHOW_TOOLTIPS_ANY_ZONE = "showTooltipsInAnyZone"; public static final String KEY_SHOW_CARD_NAMES = "showCardNames"; @@ -88,7 +89,7 @@ public class PreferencesDialog extends javax.swing.JDialog { public static final String KEY_GAME_SHOW_STORM_COUNTER = "gameShowStormCounter"; public static final String KEY_GAME_CONFIRM_EMPTY_MANA_POOL = "gameConfirmEmptyManaPool"; public static final String KEY_GAME_ASK_MOVE_TO_GRAVE_ORDER = "gameAskMoveToGraveORder"; - + public static final String KEY_GAME_LOG_AUTO_SAVE = "gameLogAutoSave"; public static final String KEY_CARD_IMAGES_USE_DEFAULT = "cardImagesUseDefault"; @@ -96,12 +97,12 @@ public class PreferencesDialog extends javax.swing.JDialog { public static final String KEY_CARD_IMAGES_CHECK = "cardImagesCheck"; public static final String KEY_CARD_IMAGES_SAVE_TO_ZIP = "cardImagesSaveToZip"; public static final String KEY_CARD_IMAGES_PREF_LANGUAGE = "cardImagesPreferedImageLaguage"; - + public static final String KEY_BACKGROUND_IMAGE = "backgroundImage"; public static final String KEY_BATTLEFIELD_IMAGE = "battlefieldImage"; public static final String KEY_BACKGROUND_IMAGE_DEFAULT = "backgroundImagedDefault"; public static final String KEY_BATTLEFIELD_IMAGE_RANDOM = "battlefieldImagerandom"; - public static final String KEY_BATTLEFIELD_IMAGE_DEFAULT = "battlefieldImageDefault"; + public static final String KEY_BATTLEFIELD_IMAGE_DEFAULT = "battlefieldImageDefault"; public static final String KEY_SOUNDS_GAME_ON = "soundsOn"; public static final String KEY_SOUNDS_DRAFT_ON = "soundsDraftOn"; @@ -112,7 +113,6 @@ public class PreferencesDialog extends javax.swing.JDialog { public static final String KEY_BIG_CARD_TOGGLED = "bigCardToggled"; - // Phases public static final String UPKEEP_YOU = "upkeepYou"; public static final String DRAW_YOU = "drawYou"; @@ -138,15 +138,15 @@ public class PreferencesDialog extends javax.swing.JDialog { // mana auto payment public static final String KEY_GAME_MANA_AUTOPAYMENT = "gameManaAutopayment"; public static final String KEY_GAME_MANA_AUTOPAYMENT_ONLY_ONE = "gameManaAutopaymentOnlyOne"; - + // Size of frame to check if divider locations should be used public static final String KEY_MAGE_PANEL_LAST_SIZE = "gamepanelLastSize"; - + // pref settings of table settings and filtering public static final String KEY_TABLES_FILTER_SETTINGS = "tablePanelFilterSettings"; public static final String KEY_TABLES_COLUMNS_WIDTH = "tablePanelColumnWidth"; public static final String KEY_TABLES_COLUMNS_ORDER = "tablePanelColumnSort"; - + // positions of divider bars public static final String KEY_TABLES_DIVIDER_LOCATION_1 = "tablePanelDividerLocation1"; public static final String KEY_TABLES_DIVIDER_LOCATION_2 = "tablePanelDividerLocation2"; @@ -155,11 +155,20 @@ public class PreferencesDialog extends javax.swing.JDialog { // user list public static final String KEY_USERS_COLUMNS_WIDTH = "userPanelColumnWidth"; public static final String KEY_USERS_COLUMNS_ORDER = "userPanelColumnSort"; - + // table waiting dialog + public static final String KEY_TABLE_WAITING_WIDTH = "tableWaitingPanelWidth"; + public static final String KEY_TABLE_WAITING_HEIGHT = "tableWaitingPanelHeight"; + public static final String KEY_TABLE_WAITING_COLUMNS_WIDTH = "tableWaitingPanelColumnWidth"; + public static final String KEY_TABLE_WAITING_COLUMNS_ORDER = "tableWaitingPanelColumnSort"; + public static final String KEY_GAMEPANEL_DIVIDER_LOCATION_0 = "gamepanelDividerLocation0"; public static final String KEY_GAMEPANEL_DIVIDER_LOCATION_1 = "gamepanelDividerLocation1"; public static final String KEY_GAMEPANEL_DIVIDER_LOCATION_2 = "gamepanelDividerLocation2"; + public static final String KEY_TOURNAMENT_PLAYER_COLUMNS_WIDTH = "tournamentPlayerPanelColumnWidth"; + public static final String KEY_TOURNAMENT_PLAYER_COLUMNS_ORDER = "tournamentPlayerPanelColumnSort"; + public static final String KEY_TOURNAMENT_MATCH_COLUMNS_WIDTH = "tournamentMatchPanelColumnWidth"; + public static final String KEY_TOURNAMENT_MATCH_COLUMNS_ORDER = "tournamentMatchPanelColumnSort"; public static final String KEY_TOURNAMENT_DIVIDER_LOCATION_1 = "tournamentPanelDividerLocation1"; public static final String KEY_TOURNAMENT_DIVIDER_LOCATION_2 = "tournamentPanelDividerLocation2"; @@ -204,7 +213,7 @@ public class PreferencesDialog extends javax.swing.JDialog { // used to save and restore the settings for the cardArea (draft, sideboarding, deck builder) public static final String KEY_DRAFT_VIEW = "draftView"; - + public static final String KEY_DRAFT_SORT_BY = "draftSortBy"; public static final String KEY_DRAFT_SORT_INDEX = "draftSortIndex"; public static final String KEY_DRAFT_SORT_ASCENDING = "draftSortAscending"; @@ -234,10 +243,9 @@ public class PreferencesDialog extends javax.swing.JDialog { public static final String KEY_CONNECTION_URL_SERVER_LIST = "connectionURLServerList"; public static final String KEY_AVATAR = "selectedId"; - + public static final String KEY_CONNECT_AUTO_CONNECT = "autoConnect"; public static final String KEY_CONNECT_FLAG = "connectFlag"; - private static final Map cache = new HashMap<>(); @@ -278,38 +286,37 @@ public class PreferencesDialog extends javax.swing.JDialog { { fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } - + private final JFileChooser fc_i = new JFileChooser(); + { fc_i.setAcceptAllFileFilterUsed(false); fc_i.addChoosableFileFilter(new ImageFileFilter()); } - private static class ImageFileFilter extends FileFilter{ - + private static class ImageFileFilter extends FileFilter { + @Override public boolean accept(File f) { String filename = f.getName(); - if(f.isDirectory()){ + if (f.isDirectory()) { return true; } - if(filename != null){ - if(filename.endsWith(".jpg") || filename.endsWith(".jpeg") || - filename.endsWith(".png") || filename.endsWith(".bmp")){ - return true; + if (filename != null) { + if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") + || filename.endsWith(".png") || filename.endsWith(".bmp")) { + return true; } } return false; } - + @Override public String getDescription() { - return "*.png | *.bmp |*.jpg | *.jpeg"; - } + return "*.png | *.bmp |*.jpg | *.jpeg"; + } } - - - + /** * Creates new form PreferencesDialog * @@ -322,15 +329,15 @@ public class PreferencesDialog extends javax.swing.JDialog { txtImageFolderPath.setEditable(false); cbProxyType.setModel(new DefaultComboBoxModel<>(Connection.ProxyType.values())); addAvatars(); - - cbPreferedImageLanguage.setModel(new DefaultComboBoxModel<>(new String[] {"en","de","fr","it","es","pt","jp","cn","ru","tw","ko"})); - + + cbPreferedImageLanguage.setModel(new DefaultComboBoxModel<>(new String[]{"en", "de", "fr", "it", "es", "pt", "jp", "cn", "ru", "tw", "ko"})); + } - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents @@ -1698,9 +1705,9 @@ public class PreferencesDialog extends javax.swing.JDialog { save(prefs, dialog.cbUseDefaultImageFolder, KEY_CARD_IMAGES_USE_DEFAULT, "true", "false", UPDATE_CACHE_POLICY); saveImagesPath(prefs); save(prefs, dialog.cbCheckForNewImages, KEY_CARD_IMAGES_CHECK, "true", "false", UPDATE_CACHE_POLICY); - save(prefs, dialog.cbSaveToZipFiles, KEY_CARD_IMAGES_SAVE_TO_ZIP, "true", "false", UPDATE_CACHE_POLICY); + save(prefs, dialog.cbSaveToZipFiles, KEY_CARD_IMAGES_SAVE_TO_ZIP, "true", "false", UPDATE_CACHE_POLICY); save(prefs, dialog.cbPreferedImageLanguage, KEY_CARD_IMAGES_PREF_LANGUAGE); - + save(prefs, dialog.cbUseDefaultBackground, KEY_BACKGROUND_IMAGE_DEFAULT, "true", "false", UPDATE_CACHE_POLICY); save(prefs, dialog.cbUseDefaultBattleImage, KEY_BATTLEFIELD_IMAGE_DEFAULT, "true", "false", UPDATE_CACHE_POLICY); save(prefs, dialog.cbUseRandomBattleImage, KEY_BATTLEFIELD_IMAGE_RANDOM, "true", "false", UPDATE_CACHE_POLICY); @@ -1712,7 +1719,7 @@ public class PreferencesDialog extends javax.swing.JDialog { save(prefs, dialog.cbEnableOtherSounds, KEY_SOUNDS_OTHER_ON, "true", "false", UPDATE_CACHE_POLICY); save(prefs, dialog.cbEnableBattlefieldBGM, KEY_SOUNDS_MATCH_MUSIC_ON, "true", "false", UPDATE_CACHE_POLICY); saveSoundPath(prefs); - + // connection save(prefs, dialog.cbProxyType, KEY_PROXY_TYPE); save(prefs, dialog.txtProxyServer, KEY_PROXY_ADDRESS); @@ -1770,7 +1777,7 @@ public class PreferencesDialog extends javax.swing.JDialog { private void btnBrowseImageLocationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseImageLocationActionPerformed int returnVal = fc.showOpenDialog(PreferencesDialog.this); - + if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); txtImageFolderPath.setText(file.getAbsolutePath()); @@ -1803,101 +1810,101 @@ public class PreferencesDialog extends javax.swing.JDialog { }//GEN-LAST:event_cbEnableGameSoundsActionPerformed private void cbEnableBattlefieldBGMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbEnableBattlefieldBGMActionPerformed - if(cbEnableBattlefieldBGM.isSelected()){ + if (cbEnableBattlefieldBGM.isSelected()) { txtBattlefieldIBGMPath.setEnabled(true); btnBattlefieldBGMBrowse.setEnabled(true); - }else{ + } else { txtBattlefieldIBGMPath.setEnabled(false); btnBattlefieldBGMBrowse.setEnabled(false); } }//GEN-LAST:event_cbEnableBattlefieldBGMActionPerformed - + private void cbUseDefaultBackgroundActionPerformed(java.awt.event.ActionEvent evt) { - if(cbUseDefaultBackground.isSelected()){ + if (cbUseDefaultBackground.isSelected()) { useDefaultBackgroundImage(); - }else{ + } else { useSelectBackgroundImage(); } - } + } - private void useDefaultBackgroundImage(){ + private void useDefaultBackgroundImage() { txtBackgroundImagePath.setEnabled(false); btnBrowseBackgroundImage.setEnabled(false); txtBackgroundImagePath.setText(""); } - - private void useSelectBackgroundImage(){ + + private void useSelectBackgroundImage() { String path = cache.get(KEY_BACKGROUND_IMAGE); dialog.txtBackgroundImagePath.setText(path); txtBackgroundImagePath.setEnabled(true); btnBrowseBackgroundImage.setEnabled(true); } - + private void cbUseDefaultBattleImageActionPerformed(java.awt.event.ActionEvent evt) { - if(cbUseDefaultBattleImage.isSelected()){ + if (cbUseDefaultBattleImage.isSelected()) { useDefaultBattlefield(); - }else{ + } else { useSelectedOrRandom(); } - } - - private void useDefaultBattlefield(){ + } + + private void useDefaultBattlefield() { cbUseRandomBattleImage.setEnabled(false); txtBattlefieldImagePath.setEnabled(false); btnBrowseBattlefieldImage.setEnabled(false); } - - private void useSelectedOrRandom(){ + + private void useSelectedOrRandom() { cbUseRandomBattleImage.setEnabled(true); String temp = cache.get(KEY_BATTLEFIELD_IMAGE_RANDOM); - if(temp != null){ - if(temp.equals("true")){ + if (temp != null) { + if (temp.equals("true")) { useRandomBattleField(); cbUseRandomBattleImage.setSelected(true); - }else{ + } else { useSelectedBattleField(); cbUseRandomBattleImage.setSelected(false); } - }else{ - useSelectedBattleField(); - cbUseRandomBattleImage.setSelected(false); + } else { + useSelectedBattleField(); + cbUseRandomBattleImage.setSelected(false); } } - + private void cbUseRandomBattleImageActionPerformed(java.awt.event.ActionEvent evt) { - if(cbUseRandomBattleImage.isSelected()){ + if (cbUseRandomBattleImage.isSelected()) { useRandomBattleField(); - }else{ + } else { useSelectedBattleField(); } - } + } - private void useRandomBattleField(){ + private void useRandomBattleField() { txtBattlefieldImagePath.setEnabled(false); btnBrowseBattlefieldImage.setEnabled(false); } - - private void useSelectedBattleField(){ + + private void useSelectedBattleField() { txtBattlefieldImagePath.setEnabled(true); btnBrowseBattlefieldImage.setEnabled(true); } - + private void btnBrowseBackgroundImageActionPerformed(java.awt.event.ActionEvent evt) { - int returnVal = fc_i.showOpenDialog(PreferencesDialog.this); + int returnVal = fc_i.showOpenDialog(PreferencesDialog.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc_i.getSelectedFile(); txtBackgroundImagePath.setText(file.getAbsolutePath()); } - } + } private void btnBrowseBattlefieldImageActionPerformed(java.awt.event.ActionEvent evt) { - int returnVal = fc_i.showOpenDialog(PreferencesDialog.this); + int returnVal = fc_i.showOpenDialog(PreferencesDialog.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc_i.getSelectedFile(); txtBattlefieldImagePath.setText(file.getAbsolutePath()); } - } - + } + private void txtBackgroundImagePathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBackgroundImagePathActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtBackgroundImagePathActionPerformed @@ -1995,12 +2002,10 @@ public class PreferencesDialog extends javax.swing.JDialog { if (cbProxyType.getSelectedItem() == Connection.ProxyType.SOCKS) { this.pnlProxy.setVisible(true); this.pnlProxySettings.setVisible(true); - } - else if (cbProxyType.getSelectedItem() == Connection.ProxyType.HTTP) { + } else if (cbProxyType.getSelectedItem() == Connection.ProxyType.HTTP) { this.pnlProxy.setVisible(true); this.pnlProxySettings.setVisible(true); - } - else if (cbProxyType.getSelectedItem() == Connection.ProxyType.NONE) { + } else if (cbProxyType.getSelectedItem() == Connection.ProxyType.NONE) { this.pnlProxy.setVisible(false); this.pnlProxySettings.setVisible(false); } @@ -2059,7 +2064,7 @@ public class PreferencesDialog extends javax.swing.JDialog { } private static void loadPhases(Preferences prefs) { - load(prefs, dialog.displayBigCardsInHand, KEY_HAND_USE_BIG_CARDS, "true","true"); + load(prefs, dialog.displayBigCardsInHand, KEY_HAND_USE_BIG_CARDS, "true", "true"); load(prefs, dialog.showToolTipsInAnyZone, KEY_SHOW_TOOLTIPS_ANY_ZONE, "true"); load(prefs, dialog.showCardName, KEY_SHOW_CARD_NAMES, "true"); load(prefs, dialog.nonLandPermanentsInOnePile, KEY_PERMANENTS_IN_ONE_PILE, "true"); @@ -2072,21 +2077,21 @@ public class PreferencesDialog extends javax.swing.JDialog { load(prefs, dialog.cbGameLogAutoSave, KEY_GAME_LOG_AUTO_SAVE, "true"); - load(prefs, dialog.checkBoxUpkeepYou, UPKEEP_YOU, "on","on"); - load(prefs, dialog.checkBoxDrawYou, DRAW_YOU, "on","on"); - load(prefs, dialog.checkBoxMainYou, MAIN_YOU, "on","on"); - load(prefs, dialog.checkBoxBeforeCYou, BEFORE_COMBAT_YOU, "on","on"); - load(prefs, dialog.checkBoxEndOfCYou, END_OF_COMBAT_YOU, "on","on"); - load(prefs, dialog.checkBoxMain2You, MAIN_2_YOU, "on","on"); - load(prefs, dialog.checkBoxEndTurnYou, END_OF_TURN_YOU, "on","on"); + load(prefs, dialog.checkBoxUpkeepYou, UPKEEP_YOU, "on", "on"); + load(prefs, dialog.checkBoxDrawYou, DRAW_YOU, "on", "on"); + load(prefs, dialog.checkBoxMainYou, MAIN_YOU, "on", "on"); + load(prefs, dialog.checkBoxBeforeCYou, BEFORE_COMBAT_YOU, "on", "on"); + load(prefs, dialog.checkBoxEndOfCYou, END_OF_COMBAT_YOU, "on", "on"); + load(prefs, dialog.checkBoxMain2You, MAIN_2_YOU, "on", "on"); + load(prefs, dialog.checkBoxEndTurnYou, END_OF_TURN_YOU, "on", "on"); - load(prefs, dialog.checkBoxUpkeepOthers, UPKEEP_OTHERS, "on","on"); - load(prefs, dialog.checkBoxDrawOthers, DRAW_OTHERS, "on","on"); - load(prefs, dialog.checkBoxMainOthers, MAIN_OTHERS, "on","on"); - load(prefs, dialog.checkBoxBeforeCOthers, BEFORE_COMBAT_OTHERS, "on","on"); - load(prefs, dialog.checkBoxEndOfCOthers, END_OF_COMBAT_OTHERS, "on","on"); - load(prefs, dialog.checkBoxMain2Others, MAIN_2_OTHERS, "on","on"); - load(prefs, dialog.checkBoxEndTurnOthers, END_OF_TURN_OTHERS, "on","on"); + load(prefs, dialog.checkBoxUpkeepOthers, UPKEEP_OTHERS, "on", "on"); + load(prefs, dialog.checkBoxDrawOthers, DRAW_OTHERS, "on", "on"); + load(prefs, dialog.checkBoxMainOthers, MAIN_OTHERS, "on", "on"); + load(prefs, dialog.checkBoxBeforeCOthers, BEFORE_COMBAT_OTHERS, "on", "on"); + load(prefs, dialog.checkBoxEndOfCOthers, END_OF_COMBAT_OTHERS, "on", "on"); + load(prefs, dialog.checkBoxMain2Others, MAIN_2_OTHERS, "on", "on"); + load(prefs, dialog.checkBoxEndTurnOthers, END_OF_TURN_OTHERS, "on", "on"); load(prefs, dialog.cbStopAttack, KEY_STOP_ATTACK, "true", "true"); load(prefs, dialog.cbStopBlock, KEY_STOP_BLOCK, "true", "true"); @@ -2110,13 +2115,13 @@ public class PreferencesDialog extends javax.swing.JDialog { load(prefs, dialog.cbCheckForNewImages, KEY_CARD_IMAGES_CHECK, "true"); load(prefs, dialog.cbSaveToZipFiles, KEY_CARD_IMAGES_SAVE_TO_ZIP, "true"); dialog.cbPreferedImageLanguage.setSelectedItem(MageFrame.getPreferences().get(KEY_CARD_IMAGES_PREF_LANGUAGE, "en")); - - //add background load precedure + + //add background load precedure prop = prefs.get(KEY_BACKGROUND_IMAGE_DEFAULT, "true"); - if(prop.equals("true")){ + if (prop.equals("true")) { dialog.cbUseDefaultBackground.setSelected(true); dialog.useDefaultBackgroundImage(); - }else{ + } else { dialog.cbUseDefaultBackground.setSelected(false); dialog.useSelectBackgroundImage(); String path = prefs.get(KEY_BACKGROUND_IMAGE, ""); @@ -2124,27 +2129,27 @@ public class PreferencesDialog extends javax.swing.JDialog { updateCache(KEY_BACKGROUND_IMAGE, path); } prop = prefs.get(KEY_BATTLEFIELD_IMAGE_DEFAULT, "true"); - if(prop.equals("true")){ + if (prop.equals("true")) { dialog.cbUseDefaultBattleImage.setSelected(true); - dialog.useDefaultBattlefield(); - }else{ + dialog.useDefaultBattlefield(); + } else { dialog.cbUseDefaultBattleImage.setSelected(false); dialog.useSelectedOrRandom(); } prop = prefs.get(KEY_BATTLEFIELD_IMAGE_RANDOM, "true"); - - if(dialog.cbUseRandomBattleImage.isEnabled()) { - if(prop.equals("true")){ + + if (dialog.cbUseRandomBattleImage.isEnabled()) { + if (prop.equals("true")) { dialog.cbUseRandomBattleImage.setSelected(true); dialog.useRandomBattleField(); - }else{ + } else { dialog.cbUseRandomBattleImage.setSelected(false); dialog.useSelectedBattleField(); String path = prefs.get(KEY_BATTLEFIELD_IMAGE, ""); dialog.txtBattlefieldImagePath.setText(path); updateCache(KEY_BATTLEFIELD_IMAGE, path); } - } + } } private static void loadSoundSettings(Preferences prefs) { @@ -2200,7 +2205,7 @@ public class PreferencesDialog extends javax.swing.JDialog { loadPhases(MageFrame.getPreferences()); } UserSkipPrioritySteps userSkipPrioritySteps = new UserSkipPrioritySteps(); - + userSkipPrioritySteps.getYourTurn().setUpkeep(dialog.checkBoxUpkeepYou.isSelected()); userSkipPrioritySteps.getYourTurn().setDraw(dialog.checkBoxDrawYou.isSelected()); userSkipPrioritySteps.getYourTurn().setMain1(dialog.checkBoxMainYou.isSelected()); @@ -2216,7 +2221,7 @@ public class PreferencesDialog extends javax.swing.JDialog { userSkipPrioritySteps.getOpponentTurn().setEndOfCombat(dialog.checkBoxEndOfCOthers.isSelected()); userSkipPrioritySteps.getOpponentTurn().setMain2(dialog.checkBoxMain2Others.isSelected()); userSkipPrioritySteps.getOpponentTurn().setEndOfTurn(dialog.checkBoxEndTurnOthers.isSelected()); - + userSkipPrioritySteps.setStopOnDeclareAttackersDuringSkipActions(dialog.cbStopAttack.isSelected()); userSkipPrioritySteps.setStopOnDeclareBlockerIfNoneAvailable(dialog.cbStopBlock.isSelected()); userSkipPrioritySteps.setStopOnAllEndPhases(dialog.cbStopOnAllEnd.isSelected()); @@ -2235,7 +2240,6 @@ public class PreferencesDialog extends javax.swing.JDialog { } } - private static void saveImagesPath(Preferences prefs) { if (!dialog.cbUseDefaultImageFolder.isSelected()) { String path = dialog.txtImageFolderPath.getText(); @@ -2243,19 +2247,19 @@ public class PreferencesDialog extends javax.swing.JDialog { updateCache(KEY_CARD_IMAGES_PATH, path); } // background path save precedure - if(!dialog.cbUseDefaultBackground.isSelected()){ + if (!dialog.cbUseDefaultBackground.isSelected()) { String path = dialog.txtBackgroundImagePath.getText(); prefs.put(KEY_BACKGROUND_IMAGE, path); updateCache(KEY_BACKGROUND_IMAGE, path); } - if(!dialog.cbUseDefaultBattleImage.isSelected() && !dialog.cbUseRandomBattleImage.isSelected()){ + if (!dialog.cbUseDefaultBattleImage.isSelected() && !dialog.cbUseRandomBattleImage.isSelected()) { String path = dialog.txtBattlefieldImagePath.getText(); prefs.put(KEY_BATTLEFIELD_IMAGE, path); updateCache(KEY_BATTLEFIELD_IMAGE, path); } } - - private static void saveSoundPath(Preferences prefs){ + + private static void saveSoundPath(Preferences prefs) { String path = dialog.txtBattlefieldIBGMPath.getText(); prefs.put(KEY_SOUNDS_MATCH_MUSIC_PATH, path); updateCache(KEY_SOUNDS_MATCH_MUSIC_PATH, path); @@ -2294,13 +2298,14 @@ public class PreferencesDialog extends javax.swing.JDialog { } public static void setPrefValue(String key, boolean value) { - switch(key) { + switch (key) { case KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS: dialog.cbAllowRequestToShowHandCards.setSelected(value); save(MageFrame.getPreferences(), dialog.cbAllowRequestToShowHandCards, KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, "true", "false", UPDATE_CACHE_POLICY); break; - } + } } + private static void save(Preferences prefs, JCheckBox checkBox, String propName, String yesValue, String noValue, boolean updateCache) { prefs.put(propName, checkBox.isSelected() ? yesValue : noValue); if (updateCache) { @@ -2356,7 +2361,7 @@ public class PreferencesDialog extends javax.swing.JDialog { try { addAvatar(jPanel10, 51, true, false); addAvatar(jPanel13, 13, false, false); - addAvatar(jPanel11, 9, false, false); + addAvatar(jPanel11, 9, false, false); addAvatar(jPanel12, 53, false, false); addAvatar(jPanel14, 10, false, false); addAvatar(jPanel15, 39, false, false); @@ -2409,25 +2414,25 @@ public class PreferencesDialog extends javax.swing.JDialog { public void mousePressed(MouseEvent e) { if (selectedAvatarId != id) { setSelectedId(id); - MageFrame.getSession().updatePreferencesForServer(getUserData()); + MageFrame.getSession().updatePreferencesForServer(getUserData()); } } }); } } - public static UserDataView getUserData(){ - return new UserDataView( - getSelectedAvatar(), - PreferencesDialog.getCachedValue(PreferencesDialog.KEY_SHOW_TOOLTIPS_ANY_ZONE, "true").equals("true"), - PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, "true").equals("true"), - PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_CONFIRM_EMPTY_MANA_POOL, "true").equals("true"), - getUserSkipPrioritySteps(), - MageFrame.getPreferences().get(KEY_CONNECT_FLAG, "world"), - PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_ASK_MOVE_TO_GRAVE_ORDER, "true").equals("true") + public static UserData getUserData() { + return new UserData(UserGroup.PLAYER, + getSelectedAvatar(), + PreferencesDialog.getCachedValue(PreferencesDialog.KEY_SHOW_TOOLTIPS_ANY_ZONE, "true").equals("true"), + PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, "true").equals("true"), + PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_CONFIRM_EMPTY_MANA_POOL, "true").equals("true"), + getUserSkipPrioritySteps(), + MageFrame.getPreferences().get(KEY_CONNECT_FLAG, "world"), + PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_ASK_MOVE_TO_GRAVE_ORDER, "true").equals("true") ); } - + // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnBattlefieldBGMBrowse; private javax.swing.JButton btnBrowseBackgroundImage; 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 c2166b34d4b..156ea32b0a1 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java @@ -1,50 +1,54 @@ /* -* 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. -*/ + * 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. + */ /* * TableWaitingDialog.java * * Created on Dec 16, 2009, 10:27:44 AM */ - package mage.client.dialog; import java.util.List; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; +import javax.swing.Icon; import javax.swing.SwingWorker; import javax.swing.table.AbstractTableModel; import mage.client.MageFrame; import mage.client.chat.ChatPanel; import mage.client.components.MageComponents; import mage.client.components.tray.MageTray; +import static mage.client.dialog.PreferencesDialog.KEY_TABLE_WAITING_COLUMNS_ORDER; +import static mage.client.dialog.PreferencesDialog.KEY_TABLE_WAITING_COLUMNS_WIDTH; import mage.client.util.audio.AudioManager; +import mage.client.util.gui.TableUtil; +import mage.client.util.gui.countryBox.CountryCellRenderer; import mage.remote.Session; import mage.view.SeatView; import mage.view.TableView; @@ -64,8 +68,11 @@ public class TableWaitingDialog extends MageDialog { private Session session; private final TableWaitModel tableWaitModel; private UpdateSeatsTask updateTask; + private static final int[] defaultColumnsWidth = {20, 50, 100, 100}; - /** Creates new form TableWaitingDialog */ + /** + * Creates new form TableWaitingDialog + */ public TableWaitingDialog() { session = MageFrame.getSession(); @@ -73,8 +80,17 @@ public class TableWaitingDialog extends MageDialog { initComponents(); + int prefWidth = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_TABLE_WAITING_WIDTH, "500")); + int prefHeight = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_TABLE_WAITING_HEIGHT, "400")); + if (prefWidth > 40 && prefHeight > 40) { + this.setSize(prefWidth, prefHeight); + } + chatPanel.useExtendedView(ChatPanel.VIEW_MODE.NONE); tableSeats.createDefaultColumnsFromModel(); + TableUtil.setColumnWidthAndOrder(tableSeats, defaultColumnsWidth, KEY_TABLE_WAITING_COLUMNS_WIDTH, KEY_TABLE_WAITING_COLUMNS_ORDER); + tableSeats.setDefaultRenderer(Icon.class, new CountryCellRenderer()); + MageFrame.getUI().addButton(MageComponents.TABLE_WAITING_START_BUTTON, btnStart); } @@ -97,11 +113,14 @@ public class TableWaitingDialog extends MageDialog { return; } int row = this.tableSeats.getSelectedRow(); + if (getTitle().equals("Waiting for players")) { + this.title = getTitle() + " - " + table.getDeckType() + " / " + table.getGameType(); + this.repaint(); + } tableWaitModel.loadData(table); this.tableSeats.repaint(); this.tableSeats.getSelectionModel().setSelectionInterval(row, row); - } - else { + } else { closeDialog(); } } catch (Exception ex) { @@ -131,8 +150,7 @@ public class TableWaitingDialog extends MageDialog { this.setModal(false); this.setLocation(100, 100); this.setVisible(true); - } - else { + } else { closeDialog(); } } @@ -144,14 +162,15 @@ public class TableWaitingDialog extends MageDialog { this.chatPanel.disconnect(); MageFrame.getUI().removeButton(MageComponents.TABLE_WAITING_START_BUTTON); this.removeDialog(); + TableUtil.saveColumnWidthAndOrderToPrefs(tableSeats, KEY_TABLE_WAITING_COLUMNS_WIDTH, KEY_TABLE_WAITING_COLUMNS_ORDER); + PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLE_WAITING_WIDTH, Integer.toString(getWidth())); + PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLE_WAITING_HEIGHT, Integer.toString(getHeight())); } - - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents @@ -248,12 +267,11 @@ public class TableWaitingDialog extends MageDialog { if (session.startMatch(roomId, tableId)) { closeDialog(); } - } - else { + } else { if (session.startTournament(roomId, tableId)) { closeDialog(); } - } + } }//GEN-LAST:event_btnStartActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed @@ -285,7 +303,6 @@ public class TableWaitingDialog extends MageDialog { } }//GEN-LAST:event_btnMoveUpActionPerformed - // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCancel; private javax.swing.JButton btnMoveDown; @@ -300,7 +317,8 @@ public class TableWaitingDialog extends MageDialog { } class TableWaitModel extends AbstractTableModel { - private final String[] columnNames = new String[]{"Seat Num", "Player Name", "Player Type"}; + + private final String[] columnNames = new String[]{"Seat", "Loc", "Player Name", "Player Type"}; private SeatView[] seats = new SeatView[0]; public void loadData(TableView table) { @@ -324,14 +342,15 @@ class TableWaitModel extends AbstractTableModel { if (arg1 == 0) { return Integer.toString(arg0 + 1); } - } - else { + } else { switch (arg1) { case 0: return Integer.toString(arg0 + 1); case 1: - return seats[arg0].getPlayerName(); + return seats[arg0].getFlagName(); case 2: + return seats[arg0].getPlayerName(); + case 3: return seats[arg0].getPlayerType(); } } @@ -350,8 +369,13 @@ class TableWaitModel extends AbstractTableModel { } @Override - public Class getColumnClass(int columnIndex){ - return String.class; + public Class getColumnClass(int columnIndex) { + switch (columnIndex) { + case 1: + return Icon.class; + default: + return String.class; + } } @Override @@ -413,7 +437,7 @@ class UpdateSeatsTask extends SwingWorker { private int getPlayersCount(TableView tableView) { int playerCount = 0; if (tableView != null) { - for (SeatView seatView: tableView.getSeats()) { + for (SeatView seatView : tableView.getSeats()) { if (seatView.getPlayerId() != null && seatView.getPlayerType().equals("Human")) { playerCount++; } @@ -422,7 +446,6 @@ class UpdateSeatsTask extends SwingWorker { return playerCount; } - @Override protected void done() { try { @@ -431,7 +454,8 @@ class UpdateSeatsTask extends SwingWorker { logger.fatal("Update Seats Task error", ex); } catch (ExecutionException ex) { logger.fatal("Update Seats Task error", ex); - } catch (CancellationException ex) {} + } catch (CancellationException ex) { + } } -} \ No newline at end of file +} 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 f82dda7b13b..c7be776f300 100644 --- a/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java +++ b/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java @@ -1,30 +1,30 @@ /* -* 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. -*/ + * 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.client.game; import java.awt.Color; @@ -37,7 +37,6 @@ import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.lang.reflect.Field; import java.util.UUID; - import javax.swing.BorderFactory; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; @@ -72,21 +71,23 @@ public class PlayAreaPanel extends javax.swing.JPanel { private boolean playingMode = true; private final GamePanel gamePanel; private final PlayAreaPanelOptions options; - + private JCheckBoxMenuItem manaPoolMenuItem1; private JCheckBoxMenuItem manaPoolMenuItem2; private JCheckBoxMenuItem allowViewHandCardsMenuItem; - + public static final int PANEL_HEIGHT = 242; public static final int PANEL_HEIGHT_SMALL = 190; - /** Creates new form PlayAreaPanel + /** + * Creates new form PlayAreaPanel + * * @param player * @param bigCard * @param gameId * @param priorityTime * @param gamePanel - * @param options + * @param options */ public PlayAreaPanel(PlayerView player, BigCard bigCard, UUID gameId, int priorityTime, GamePanel gamePanel, PlayAreaPanelOptions options) { this.gamePanel = gamePanel; @@ -97,7 +98,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { popupMenu = new JPopupMenu(); if (options.isPlayer) { - addPopupMenuPlayer(player.getUserData().allowRequestShowHandCards()); + addPopupMenuPlayer(player.getUserData().isAllowRequestShowHandCards()); } else { addPopupMenuWatcher(); } @@ -109,15 +110,14 @@ public class PlayAreaPanel extends javax.swing.JPanel { public void CleanUp() { battlefieldPanel.cleanUp(); playerPanel.cleanUp(); - - for (ActionListener al : btnCheat.getActionListeners() ) { + for (ActionListener al : btnCheat.getActionListeners()) { btnCheat.removeActionListener(al); } - + // Taken form : https://community.oracle.com/thread/2183145 // removed the internal focus of a popupMenu data to allow GC before another popup menu is selected - for(ChangeListener listener : MenuSelectionManager.defaultManager().getChangeListeners()) { + for (ChangeListener listener : MenuSelectionManager.defaultManager().getChangeListeners()) { if (listener.getClass().getName().contains("MenuKeyboardHelper")) { try { Field field = listener.getClass().getDeclaredField("menuInputMap"); @@ -130,7 +130,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { } } - for (MouseListener ml :battlefieldPanel.getMainPanel().getMouseListeners()) { + for (MouseListener ml : battlefieldPanel.getMainPanel().getMouseListeners()) { battlefieldPanel.getMainPanel().removeMouseListener(ml); } popupMenu.getUI().uninstallUI(this); @@ -170,11 +170,11 @@ public class PlayAreaPanel extends javax.swing.JPanel { case "F9": { gamePanel.getSession().sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_MY_NEXT_TURN, gameId, null); break; - } + } } } }; - + menuItem = new JMenuItem("F2 - Confirm current request"); menuItem.setActionCommand("F2"); menuItem.setMnemonic(KeyEvent.VK_O); @@ -187,11 +187,10 @@ public class PlayAreaPanel extends javax.swing.JPanel { popupMenu.add(menuItem); menuItem.addActionListener(skipListener); - JMenu skipMenu = new JMenu("Skip"); skipMenu.setMnemonic(KeyEvent.VK_S); popupMenu.add(skipMenu); - + String tooltipText = "This skip actions stops if something goes to
stack and if attackers or blocker have to be declared."; menuItem = new JMenuItem("F4 - Phases until next turn"); menuItem.setActionCommand("F4"); @@ -213,7 +212,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.setMnemonic(KeyEvent.VK_M); skipMenu.add(menuItem); menuItem.addActionListener(skipListener); - + menuItem = new JMenuItem("F9 - Everything until your own next turn"); menuItem.setActionCommand("F9"); menuItem.setToolTipText(tooltipText); @@ -222,50 +221,50 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(skipListener); popupMenu.addSeparator(); - + JMenu manaPoolMenu = new JMenu("Mana payment"); - manaPoolMenu.setMnemonic(KeyEvent.VK_M); + manaPoolMenu.setMnemonic(KeyEvent.VK_M); popupMenu.add(manaPoolMenu); - + manaPoolMenuItem1 = new JCheckBoxMenuItem("Automatically", true); manaPoolMenuItem1.setMnemonic(KeyEvent.VK_A); manaPoolMenuItem1.setToolTipText("If not active, produced mana goes only to the mana pool
" - + "and you have to click the type of mana you want to use
" - + "in the player mana pool panel for payment."); + + "and you have to click the type of mana you want to use
" + + "in the player mana pool panel for payment."); 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"); + boolean manaPoolAutomatic = ((JCheckBoxMenuItem) e.getSource()).getState(); + PreferencesDialog.saveValue(KEY_GAME_MANA_AUTOPAYMENT, manaPoolAutomatic ? "true" : "false"); gamePanel.setMenuStates(manaPoolAutomatic, manaPoolMenuItem2.getState()); - gamePanel.getSession().sendPlayerAction(manaPoolAutomatic ? PlayerAction.MANA_AUTO_PAYMENT_ON: PlayerAction.MANA_AUTO_PAYMENT_OFF, gameId, null); + gamePanel.getSession().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); manaPoolMenuItem2.setMnemonic(KeyEvent.VK_N); manaPoolMenuItem2.setToolTipText("Mana that is already in the mana pool as you start casting a spell or activating an ability
" - + " needs to be payed manually. So you use the mana in the pool only by clicking on the related
" - + " mana symbols of mana pool area."); + + " needs to be payed manually. So you use the mana in the pool only by clicking on the related
" + + " mana symbols of mana pool area."); 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"); + boolean manaPoolAutomaticRestricted = ((JCheckBoxMenuItem) e.getSource()).getState(); + PreferencesDialog.saveValue(KEY_GAME_MANA_AUTOPAYMENT_ONLY_ONE, manaPoolAutomaticRestricted ? "true" : "false"); gamePanel.setMenuStates(manaPoolMenuItem1.getState(), manaPoolAutomaticRestricted); - gamePanel.getSession().sendPlayerAction(manaPoolAutomaticRestricted ? PlayerAction.MANA_AUTO_PAYMENT_RESTRICTED_ON: PlayerAction.MANA_AUTO_PAYMENT_RESTRICTED_OFF, gameId, null); + gamePanel.getSession().sendPlayerAction(manaPoolAutomaticRestricted ? PlayerAction.MANA_AUTO_PAYMENT_RESTRICTED_ON : PlayerAction.MANA_AUTO_PAYMENT_RESTRICTED_OFF, gameId, null); } }); JMenu automaticConfirmsMenu = new JMenu("Automatic confirms"); automaticConfirmsMenu.setMnemonic(KeyEvent.VK_U); popupMenu.add(automaticConfirmsMenu); - + menuItem = new JMenuItem("Replacement effects - reset auto select"); menuItem.setMnemonic(KeyEvent.VK_R); menuItem.setToolTipText("Reset all effects that were added to the list of auto select replacement effects this game."); @@ -281,7 +280,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { JMenu handCardsMenu = new JMenu("Cards on hand"); handCardsMenu.setMnemonic(KeyEvent.VK_H); popupMenu.add(handCardsMenu); - + if (!options.playerItself) { menuItem = new JMenuItem("Request permission to see the hand cards"); menuItem.setMnemonic(KeyEvent.VK_P); @@ -304,9 +303,9 @@ public class PlayAreaPanel extends javax.swing.JPanel { allowViewHandCardsMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - boolean requestsAllowed = ((JCheckBoxMenuItem)e.getSource()).getState(); + boolean requestsAllowed = ((JCheckBoxMenuItem) e.getSource()).getState(); PreferencesDialog.setPrefValue(KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, requestsAllowed); - gamePanel.getSession().sendPlayerAction(requestsAllowed ? PlayerAction.PERMISSION_REQUESTS_ALLOWED_ON: PlayerAction.PERMISSION_REQUESTS_ALLOWED_OFF, gameId, null); + gamePanel.getSession().sendPlayerAction(requestsAllowed ? PlayerAction.PERMISSION_REQUESTS_ALLOWED_ON : PlayerAction.PERMISSION_REQUESTS_ALLOWED_OFF, gameId, null); } }); @@ -323,7 +322,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { } }); } - + if (options.rollbackTurnsAllowed) { ActionListener rollBackActionListener = new ActionListener() { @Override @@ -332,44 +331,42 @@ public class PlayAreaPanel extends javax.swing.JPanel { gamePanel.getSession().sendPlayerAction(PlayerAction.ROLLBACK_TURNS, gameId, turnsToRollBack); } }; - + JMenu rollbackMainItem = new JMenu("Roll back"); rollbackMainItem.setMnemonic(KeyEvent.VK_R); rollbackMainItem.setToolTipText("The game will be rolled back to the start of the requested turn if all players agree."); popupMenu.add(rollbackMainItem); - + menuItem = new JMenuItem("To the start of the current turn"); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.setActionCommand("0"); - menuItem.addActionListener(rollBackActionListener); + menuItem.addActionListener(rollBackActionListener); rollbackMainItem.add(menuItem); - + menuItem = new JMenuItem("To the start of the previous turn"); menuItem.setMnemonic(KeyEvent.VK_P); menuItem.setActionCommand("1"); - menuItem.addActionListener(rollBackActionListener); + menuItem.addActionListener(rollBackActionListener); rollbackMainItem.add(menuItem); menuItem = new JMenuItem("The current turn and the 2 turns before"); menuItem.setMnemonic(KeyEvent.VK_2); menuItem.setActionCommand("2"); - menuItem.addActionListener(rollBackActionListener); + menuItem.addActionListener(rollBackActionListener); rollbackMainItem.add(menuItem); menuItem = new JMenuItem("The current turn and the 3 turns before"); menuItem.setMnemonic(KeyEvent.VK_3); menuItem.setActionCommand("3"); - menuItem.addActionListener(rollBackActionListener); + menuItem.addActionListener(rollBackActionListener); rollbackMainItem.add(menuItem); - - } - - + + } JMenu concedeMenu = new JMenu("Concede"); concedeMenu.setMnemonic(KeyEvent.VK_C); popupMenu.add(concedeMenu); - + ActionListener concedeListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { @@ -377,19 +374,19 @@ public class PlayAreaPanel extends javax.swing.JPanel { case "Game": { if (JOptionPane.showConfirmDialog(PlayAreaPanel.this, "Are you sure you want to concede the game?", "Confirm concede game", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { MageFrame.getSession().sendPlayerAction(PlayerAction.CONCEDE, gameId, null); - } + } break; } case "Match": { if (JOptionPane.showConfirmDialog(PlayAreaPanel.this, "Are you sure you want to concede the complete match?", "Confirm concede match", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { MageFrame.getSession().quitMatch(gameId); - } + } break; } } } }; - + // Concede Game menuItem = new JMenuItem("Game"); menuItem.setMnemonic(KeyEvent.VK_G); @@ -397,7 +394,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.setToolTipText("Concedes only the current game and after that the next game of the match is started if there is another game needed."); concedeMenu.add(menuItem); menuItem.addActionListener(concedeListener); - + // Concede Match menuItem = new JMenuItem("Match"); menuItem.setMnemonic(KeyEvent.VK_M); @@ -406,20 +403,19 @@ public class PlayAreaPanel extends javax.swing.JPanel { concedeMenu.add(menuItem); menuItem.addActionListener(concedeListener); - battlefieldPanel.getMainPanel().addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent Me) { this.checkMenu(Me); } - + // neccessary for linux and mac systems @Override public void mousePressed(MouseEvent Me) { this.checkMenu(Me); } - private void checkMenu(MouseEvent Me){ + private void checkMenu(MouseEvent Me) { if (Me.isPopupTrigger() && playingMode) { popupMenu.show(Me.getComponent(), Me.getX(), Me.getY()); } @@ -461,13 +457,14 @@ public class PlayAreaPanel extends javax.swing.JPanel { public void mouseReleased(MouseEvent Me) { this.checkMenu(Me); } + // neccessary for linux and mac systems @Override public void mousePressed(MouseEvent Me) { this.checkMenu(Me); } - private void checkMenu(MouseEvent Me){ + private void checkMenu(MouseEvent Me) { if (Me.isPopupTrigger() && playingMode) { popupMenu.show(Me.getComponent(), Me.getX(), Me.getY()); } @@ -483,8 +480,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { if (MageFrame.getSession().isTestMode()) { this.playerId = player.getPlayerId(); this.btnCheat.setVisible(true); - } - else { + } else { this.btnCheat.setVisible(false); } } @@ -493,7 +489,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { this.playerPanel.update(player); this.battlefieldPanel.update(player.getBattlefield()); if (this.allowViewHandCardsMenuItem != null) { - this.allowViewHandCardsMenuItem.setSelected(player.getUserData().allowRequestShowHandCards()); + this.allowViewHandCardsMenuItem.setSelected(player.getUserData().isAllowRequestShowHandCards()); } } @@ -506,7 +502,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { } private void initComponents() { - setBorder(BorderFactory.createLineBorder(new Color(0,0,0,0))); + setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0, 0))); playerPanel = new PlayerPanelExt(); btnCheat = new javax.swing.JButton(); //jScrollPane1 = new javax.swing.JScrollPane(); @@ -525,16 +521,15 @@ public class PlayAreaPanel extends javax.swing.JPanel { //Border empty = new EmptyBorder(0,0,0,0); //jScrollPane1.setBorder(empty); //jScrollPane1.setViewportBorder(empty); - javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); layout.setHorizontalGroup( - layout.createSequentialGroup() + layout.createSequentialGroup() .addComponent(playerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(battlefieldPanel, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( - layout.createParallelGroup(Alignment.LEADING) + layout.createParallelGroup(Alignment.LEADING) .addComponent(playerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(battlefieldPanel, GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE) ); @@ -548,8 +543,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { this.playerPanel.setPreferredSize(new Dimension(92, PANEL_HEIGHT_SMALL)); //this.jScrollPane1.setPreferredSize(new Dimension(160, 160)); this.battlefieldPanel.setPreferredSize(new Dimension(160, PANEL_HEIGHT_SMALL)); - } - else { + } else { this.playerPanel.setPreferredSize(new Dimension(92, PANEL_HEIGHT)); //this.jScrollPane1.setPreferredSize(new Dimension(160, 212)); this.battlefieldPanel.setPreferredSize(new Dimension(160, PANEL_HEIGHT)); @@ -576,7 +570,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { manaPoolMenuItem2.setSelected(manaPoolAutomaticRestricted); } } - + private mage.client.game.BattlefieldPanel battlefieldPanel; private javax.swing.JButton btnCheat; //private javax.swing.JScrollPane jScrollPane1; 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 bf8a5721825..895d0f7c699 100644 --- a/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java +++ b/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java @@ -36,6 +36,7 @@ package mage.client.game; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; +import java.awt.GridLayout; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionEvent; @@ -67,6 +68,7 @@ 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; import mage.components.ImagePanel; import mage.constants.ManaType; import mage.remote.Session; @@ -103,6 +105,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { private static final Border emptyBorder = BorderFactory.createEmptyBorder(0, 0, 0, 0); private int avatarId = -1; + private String flagName = ""; private PriorityTimer timer; @@ -234,6 +237,11 @@ public class PlayerPanelExt extends javax.swing.JPanel { BufferedImage resized = ImageHelper.getResizedImage(BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB), r); this.avatar.update("player", resized, resized, resized, resized, r); } + if (!player.getUserData().getFlagName().equals(flagName)) { + flagName = player.getUserData().getFlagName(); + this.avatarFlag.setIcon(CountryUtil.getCountryFlagIcon(flagName)); + avatar.repaint(); + } } this.avatar.setText(player.getName()); if (this.timer != null) { @@ -298,6 +306,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { panelBackground = new MageRoundPane(); panelBackground.setPreferredSize(new Dimension(PANEL_WIDTH - 2, PANEL_HEIGHT)); Rectangle r = new Rectangle(80, 80); + avatarFlag = new JLabel(); timerLabel = new JLabel(); lifeLabel = new JLabel(); handLabel = new JLabel(); @@ -315,6 +324,14 @@ public class PlayerPanelExt extends javax.swing.JPanel { BufferedImage resized = ImageHelper.getResizedImage(BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB), r); avatar = new HoverButton("player", resized, resized, resized, r); + avatar.setLayout(new GridLayout(4, 1, 0, 0)); + avatar.add(new JLabel()); + avatar.add(new JLabel()); + avatar.add(avatarFlag); + avatar.setAlignmentY(CENTER_ALIGNMENT); + avatarFlag.setHorizontalAlignment(JLabel.CENTER); + avatarFlag.setVerticalAlignment(JLabel.BOTTOM); + avatar.add(new JLabel()); String showPlayerNamePermanently = MageFrame.getPreferences().get(PreferencesDialog.KEY_SHOW_PLAYER_NAMES_PERMANENTLY, "true"); if (showPlayerNamePermanently.equals("true")) { avatar.setTextAlwaysVisible(true); @@ -326,6 +343,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { session.sendPlayerUUID(gameId, playerId); } }); + // timer area /small layout) timerLabel.setToolTipText("Time left"); timerLabel.setSize(80, 12); @@ -637,6 +655,8 @@ public class PlayerPanelExt extends javax.swing.JPanel { .addComponent(btnPlayer, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(timerLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(avatar, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE)) + // .addGroup(gl_panelBackground.createSequentialGroup() + // .addComponent(avatarFlag, GroupLayout.PREFERRED_SIZE, 16, GroupLayout.PREFERRED_SIZE)) .addGap(14)) .addGroup(gl_panelBackground.createSequentialGroup() .addGap(6) @@ -748,12 +768,14 @@ public class PlayerPanelExt extends javax.swing.JPanel { protected void sizePlayerPanel(boolean smallMode) { if (smallMode) { avatar.setVisible(false); + avatarFlag.setVisible(false); btnPlayer.setVisible(true); timerLabel.setVisible(true); panelBackground.setPreferredSize(new Dimension(PANEL_WIDTH - 2, PANEL_HEIGHT_SMALL)); panelBackground.setBounds(0, 0, PANEL_WIDTH - 2, PANEL_HEIGHT_SMALL); } else { avatar.setVisible(true); + avatarFlag.setVisible(true); btnPlayer.setVisible(false); timerLabel.setVisible(false); panelBackground.setPreferredSize(new Dimension(PANEL_WIDTH - 2, PANEL_HEIGHT)); @@ -791,6 +813,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { } private HoverButton avatar; + private JLabel avatarFlag; private JButton btnPlayer; private ImagePanel life; private ImagePanel poison; 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 6b681fc17d3..1d76e09ae52 100644 --- a/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java +++ b/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java @@ -31,7 +31,6 @@ * * Created on 20-Jan-2011, 9:18:30 PM */ - package mage.client.tournament; import java.awt.Component; @@ -45,14 +44,21 @@ import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import javax.swing.AbstractAction; import javax.swing.Action; +import javax.swing.Icon; import javax.swing.JOptionPane; import javax.swing.SwingWorker; import javax.swing.table.AbstractTableModel; import mage.client.MageFrame; import mage.client.chat.ChatPanel; import mage.client.dialog.PreferencesDialog; +import static mage.client.dialog.PreferencesDialog.KEY_TOURNAMENT_MATCH_COLUMNS_ORDER; +import static mage.client.dialog.PreferencesDialog.KEY_TOURNAMENT_MATCH_COLUMNS_WIDTH; +import static mage.client.dialog.PreferencesDialog.KEY_TOURNAMENT_PLAYER_COLUMNS_ORDER; +import static mage.client.dialog.PreferencesDialog.KEY_TOURNAMENT_PLAYER_COLUMNS_WIDTH; import mage.client.util.ButtonColumn; import mage.client.util.Format; +import mage.client.util.gui.TableUtil; +import mage.client.util.gui.countryBox.CountryCellRenderer; import mage.remote.Session; import mage.view.RoundView; import mage.view.TournamentGameView; @@ -76,7 +82,12 @@ public class TournamentPanel extends javax.swing.JPanel { private UpdateTournamentTask updateTask; private final DateFormat df; - /** Creates new form TournamentPanel */ + private static final int[] defaultColumnsWidthPlayers = {30, 150, 150, 60, 400}; + private static final int[] defaultColumnsWidthMatches = {60, 140, 140, 400, 80}; + + /** + * Creates new form TournamentPanel + */ public TournamentPanel() { playersModel = new TournamentPlayersTableModel(); matchesModel = new TournamentMatchesTableModel(); @@ -84,28 +95,29 @@ public class TournamentPanel extends javax.swing.JPanel { initComponents(); this.restoreDividerLocations(); btnQuitTournament.setVisible(false); - + df = DateFormat.getDateTimeInstance(); tablePlayers.createDefaultColumnsFromModel(); + TableUtil.setColumnWidthAndOrder(tablePlayers, defaultColumnsWidthPlayers, KEY_TOURNAMENT_PLAYER_COLUMNS_WIDTH, KEY_TOURNAMENT_PLAYER_COLUMNS_ORDER); + tablePlayers.setDefaultRenderer(Icon.class, new CountryCellRenderer()); + tableMatches.createDefaultColumnsFromModel(); + TableUtil.setColumnWidthAndOrder(tableMatches, defaultColumnsWidthMatches, KEY_TOURNAMENT_MATCH_COLUMNS_WIDTH, KEY_TOURNAMENT_MATCH_COLUMNS_ORDER); chatPanel1.useExtendedView(ChatPanel.VIEW_MODE.NONE); chatPanel1.setChatType(ChatPanel.ChatType.TOURNAMENT); - Action action = new AbstractAction() - { + Action action = new AbstractAction() { @Override - public void actionPerformed(ActionEvent e) - { - int modelRow = Integer.valueOf( e.getActionCommand() ); - - String state = (String)tableMatches.getValueAt(modelRow, 2); - String actionText = (String)tableMatches.getValueAt(modelRow, TournamentMatchesTableModel.ACTION_COLUMN); - UUID tableId = UUID.fromString((String)matchesModel.getValueAt(modelRow, TournamentMatchesTableModel.ACTION_COLUMN +1)); - UUID gameId = UUID.fromString((String)matchesModel.getValueAt(modelRow, TournamentMatchesTableModel.ACTION_COLUMN +3)); + public void actionPerformed(ActionEvent e) { + int modelRow = Integer.valueOf(e.getActionCommand()); + + String state = (String) tableMatches.getValueAt(modelRow, 2); + String actionText = (String) tableMatches.getValueAt(modelRow, TournamentMatchesTableModel.ACTION_COLUMN); + UUID tableId = UUID.fromString((String) matchesModel.getValueAt(modelRow, TournamentMatchesTableModel.ACTION_COLUMN + 1)); + UUID gameId = UUID.fromString((String) matchesModel.getValueAt(modelRow, TournamentMatchesTableModel.ACTION_COLUMN + 3)); - // if (state.equals("Finished") && action.equals("Replay")) { // logger.info("Replaying game " + gameId); // session.replayGame(gameId); @@ -127,6 +139,7 @@ public class TournamentPanel extends javax.swing.JPanel { if (this.chatPanel1 != null) { this.chatPanel1.disconnect(); } + } private void saveDividerLocations() { @@ -167,8 +180,7 @@ public class TournamentPanel extends javax.swing.JPanel { startTasks(); this.setVisible(true); this.repaint(); - } - else { + } else { hideTournament(); } @@ -182,12 +194,15 @@ public class TournamentPanel extends javax.swing.JPanel { stopTasks(); this.chatPanel1.disconnect(); this.saveDividerLocations(); + TableUtil.saveColumnWidthAndOrderToPrefs(tablePlayers, KEY_TOURNAMENT_PLAYER_COLUMNS_WIDTH, KEY_TOURNAMENT_PLAYER_COLUMNS_ORDER); + TableUtil.saveColumnWidthAndOrderToPrefs(tableMatches, KEY_TOURNAMENT_MATCH_COLUMNS_WIDTH, KEY_TOURNAMENT_MATCH_COLUMNS_ORDER); + Component c = this.getParent(); while (c != null && !(c instanceof TournamentPane)) { c = c.getParent(); } if (c != null) { - ((TournamentPane)c).removeTournament(); + ((TournamentPane) c).removeTournament(); } } @@ -201,21 +216,21 @@ public class TournamentPanel extends javax.swing.JPanel { c = c.getParent(); } if (c != null) { - ((TournamentPane)c).setTitle("Tournament [" + tournament.getTournamentName() +"]"); + ((TournamentPane) c).setTitle("Tournament [" + tournament.getTournamentName() + "]"); } txtName.setText(tournament.getTournamentName()); txtType.setText(tournament.getTournamentType()); txtStartTime.setText(df.format(tournament.getStartTime())); txtEndTime.setText("running..."); - + firstInitDone = true; } switch (tournament.getTournamentState()) { case "Constructing": String timeLeft = ""; if (tournament.getStepStartTime() != null) { - timeLeft = Format.getDuration(tournament.getConstructionTime() - (tournament.getServerTime().getTime() - tournament.getStepStartTime().getTime())/1000); + timeLeft = Format.getDuration(tournament.getConstructionTime() - (tournament.getServerTime().getTime() - tournament.getStepStartTime().getTime()) / 1000); } txtTournamentState.setText(new StringBuilder(tournament.getTournamentState()).append(" (").append(timeLeft).append(")").toString()); break; @@ -223,7 +238,7 @@ public class TournamentPanel extends javax.swing.JPanel { case "Drafting": String usedTime = ""; if (tournament.getStepStartTime() != null) { - usedTime = Format.getDuration((tournament.getServerTime().getTime() - tournament.getStepStartTime().getTime())/1000); + usedTime = Format.getDuration((tournament.getServerTime().getTime() - tournament.getStepStartTime().getTime()) / 1000); } txtTournamentState.setText(tournament.getTournamentState() + " (" + usedTime + ") " + tournament.getRunningInfo()); break; @@ -238,7 +253,7 @@ public class TournamentPanel extends javax.swing.JPanel { if (txtEndTime.getText().equals("running...") && tournament.getEndTime() != null) { txtEndTime.setText(df.format(tournament.getEndTime())); } - + playersModel.loadData(tournament); matchesModel.loadData(tournament); this.tablePlayers.repaint(); @@ -274,10 +289,10 @@ public class TournamentPanel extends javax.swing.JPanel { } } - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents @@ -505,7 +520,6 @@ public class TournamentPanel extends javax.swing.JPanel { // TODO add your handling code here: }//GEN-LAST:event_txtNameActionPerformed - // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel actionPanel; private javax.swing.JButton btnCloseWindow; @@ -532,7 +546,8 @@ public class TournamentPanel extends javax.swing.JPanel { } class TournamentPlayersTableModel extends AbstractTableModel { - private final String[] columnNames = new String[]{"Player Name", "State", "Points", "Results"}; + + private final String[] columnNames = new String[]{"Loc", "Player Name", "State", "Points", "Results"}; private TournamentPlayerView[] players = new TournamentPlayerView[0]; public void loadData(TournamentView tournament) { @@ -554,12 +569,14 @@ class TournamentPlayersTableModel extends AbstractTableModel { public Object getValueAt(int arg0, int arg1) { switch (arg1) { case 0: - return players[arg0].getName(); + return players[arg0].getFlagName(); case 1: - return players[arg0].getState(); + return players[arg0].getName(); case 2: - return Integer.toString(players[arg0].getPoints()); + return players[arg0].getState(); case 3: + return Integer.toString(players[arg0].getPoints()); + case 4: return players[arg0].getResults(); } return ""; @@ -577,8 +594,13 @@ class TournamentPlayersTableModel extends AbstractTableModel { } @Override - public Class getColumnClass(int columnIndex){ - return String.class; + public Class getColumnClass(int columnIndex) { + switch (columnIndex) { + case 0: + return Icon.class; + default: + return String.class; + } } @Override @@ -599,8 +621,8 @@ class TournamentMatchesTableModel extends AbstractTableModel { public void loadData(TournamentView tournament) { List views = new ArrayList<>(); watchingAllowed = tournament.isWatchingAllowed(); - for (RoundView round: tournament.getRounds()) { - for (TournamentGameView game: round.getGames()) { + for (RoundView round : tournament.getRounds()) { + for (TournamentGameView game : round.getGames()) { views.add(game); } } @@ -660,7 +682,7 @@ class TournamentMatchesTableModel extends AbstractTableModel { } @Override - public Class getColumnClass(int columnIndex){ + public Class getColumnClass(int columnIndex) { return String.class; } @@ -688,7 +710,7 @@ class UpdateTournamentTask extends SwingWorker { @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - this.publish(session.getTournament(tournamentId)); + this.publish(session.getTournament(tournamentId)); Thread.sleep(2000); } return null; @@ -709,7 +731,8 @@ class UpdateTournamentTask extends SwingWorker { logger.fatal("Update Tournament Task error", ex); } catch (ExecutionException ex) { logger.fatal("Update Tournament Task error", ex); - } catch (CancellationException ex) {} + } catch (CancellationException ex) { + } } } diff --git a/Mage.Client/src/main/java/mage/client/util/gui/TableUtil.java b/Mage.Client/src/main/java/mage/client/util/gui/TableUtil.java index 187453aa5e1..3667d86d40a 100644 --- a/Mage.Client/src/main/java/mage/client/util/gui/TableUtil.java +++ b/Mage.Client/src/main/java/mage/client/util/gui/TableUtil.java @@ -8,7 +8,6 @@ package mage.client.util.gui; import javax.swing.JTable; import javax.swing.table.TableColumn; import mage.client.dialog.PreferencesDialog; -import org.mage.card.arcane.Util; /** * @@ -17,25 +16,29 @@ import org.mage.card.arcane.Util; public class TableUtil { /** - * + * * @param table - * @param defaultColumnsWidth - * @param widthPrefKey - * @param orderPrefKey + * @param defaultColumnsWidth + * @param widthPrefKey + * @param orderPrefKey */ static public void setColumnWidthAndOrder(JTable table, int[] defaultColumnsWidth, String widthPrefKey, String orderPrefKey) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - // set the column width from saved value or defaults + // set the column width from saved value or defaults int[] widths = getIntArrayFromString(PreferencesDialog.getCachedValue(widthPrefKey, null)); int i = 0; for (int width : defaultColumnsWidth) { if (widths != null && widths.length > i) { width = widths[i]; } - TableColumn column = table.getColumnModel().getColumn(i++); - column.setWidth(width); - column.setPreferredWidth(width); + if (table.getColumnModel().getColumnCount() >= i) { + TableColumn column = table.getColumnModel().getColumn(i++); + column.setWidth(width); + column.setPreferredWidth(width); + } else { + break; + } } // set the column order @@ -47,7 +50,7 @@ public class TableUtil { } } - + static public void saveColumnWidthAndOrderToPrefs(JTable table, String widthPrefKey, String orderPrefKey) { // Column width StringBuilder columnWidthSettings = new StringBuilder(); @@ -68,8 +71,7 @@ public class TableUtil { PreferencesDialog.saveValue(orderPrefKey, columnOrderSettings.toString()); } - - + public static int[] getIntArrayFromString(String stringData) { int[] intArray = null; if (stringData != null && !stringData.isEmpty()) { @@ -79,9 +81,10 @@ public class TableUtil { for (int i = 0; i < lengthW; i++) { try { intArray[i] = Integer.parseInt(items[i]); - } catch (NumberFormatException nfe) {} + } catch (NumberFormatException nfe) { + } } - } + } return intArray; - } + } } 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 2ee392fe9ea..bd0d0d223a9 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 @@ -25,56 +25,28 @@ * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. */ - package mage.client.util.gui.countryBox; import java.awt.Component; -import java.util.HashMap; -import java.util.Map; -import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; -import org.apache.log4j.Logger; /** * * @author LevelX2 */ public class CountryCellRenderer extends DefaultTableCellRenderer { - - private static final Logger logger = Logger.getLogger(CountryCellRenderer.class); - private final Map flagIconCache = new HashMap<>(); - - private final Map countryMap = new HashMap<>(); - - public CountryCellRenderer() { - for( int i = 0; i <= CountryComboBox.countryList.length - 1; i++) { - countryMap.put(CountryComboBox.countryList[i][1],CountryComboBox.countryList[i][0]); - } - } @Override 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(table.convertColumnIndexToView(0) == column) { - label.setToolTipText(countryMap.get((String)value)); - label.setIcon(getCountryFlagIcon((String)value)); - label.setText(""); - } - return label; - } - - private ImageIcon getCountryFlagIcon(String countryCode) { - ImageIcon flagIcon = flagIconCache.get(countryCode); - if (flagIcon == null) { - flagIcon = new javax.swing.ImageIcon(getClass().getResource("/flags/" + countryCode + (countryCode.endsWith(".png") ? "" :".png"))); - if (flagIcon.getImage() == null) { - logger.warn("Country flag resource not found: " + countryCode); - } else { - flagIconCache.put(countryCode, flagIcon); - } + JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + if (value == null || ((String) value).isEmpty()) { + value = (String) "world"; } - return flagIcon; - } + label.setToolTipText(CountryUtil.getCountryName((String) value)); + label.setIcon(CountryUtil.getCountryFlagIcon((String) value)); + label.setText(""); + return label; + } } diff --git a/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryUtil.java b/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryUtil.java new file mode 100644 index 00000000000..17f8386defa --- /dev/null +++ b/Mage.Client/src/main/java/mage/client/util/gui/countryBox/CountryUtil.java @@ -0,0 +1,49 @@ +/* + * 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.client.util.gui.countryBox; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import javax.swing.ImageIcon; +import org.apache.log4j.Logger; + +/** + * + * @author LevelX2 + */ +public class CountryUtil { + + private static final Logger logger = Logger.getLogger(CountryUtil.class); + private static final Map flagIconCache = new HashMap<>(); + private static final Map countryMap = new HashMap<>(); + + public static ImageIcon getCountryFlagIcon(String countryCode) { + ImageIcon flagIcon = flagIconCache.get(countryCode); + if (flagIcon == null) { + URL url = CountryUtil.class.getResource("/flags/" + countryCode + (countryCode.endsWith(".png") ? "" : ".png")); + if (url != null) { + flagIcon = new javax.swing.ImageIcon(url); + } + if (flagIcon == null || flagIcon.getImage() == null) { + logger.warn("Country flag resource not found: " + countryCode); + flagIconCache.put(countryCode, flagIcon); + } else { + flagIconCache.put(countryCode, flagIcon); + } + } + return flagIcon; + } + + public static String getCountryName(String countryCode) { + if (countryMap.isEmpty()) { + for (int i = 0; i <= CountryComboBox.countryList.length - 1; i++) { + countryMap.put(CountryComboBox.countryList[i][1], CountryComboBox.countryList[i][0]); + } + } + return countryMap.get(countryCode); + } +} diff --git a/Mage.Client/src/main/resources/flags/computer.png b/Mage.Client/src/main/resources/flags/computer.png new file mode 100644 index 00000000000..1c5fd6e3272 Binary files /dev/null and b/Mage.Client/src/main/resources/flags/computer.png differ diff --git a/Mage.Common/src/mage/interfaces/MageServer.java b/Mage.Common/src/mage/interfaces/MageServer.java index fd86ee26645..4d30942a1e5 100644 --- a/Mage.Common/src/mage/interfaces/MageServer.java +++ b/Mage.Common/src/mage/interfaces/MageServer.java @@ -1,31 +1,30 @@ /* -* 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. -*/ - + * 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.interfaces; import java.util.List; @@ -40,14 +39,14 @@ import mage.constants.PlayerAction; import mage.game.GameException; import mage.game.match.MatchOptions; import mage.game.tournament.TournamentOptions; +import mage.players.net.UserData; import mage.utils.MageVersion; import mage.view.DraftPickView; import mage.view.GameView; import mage.view.MatchView; +import mage.view.RoomUsersView; import mage.view.TableView; import mage.view.TournamentView; -import mage.view.UserDataView; -import mage.view.RoomUsersView; import mage.view.UserView; /** @@ -58,22 +57,28 @@ public interface MageServer { // connection methods boolean registerClient(String userName, String sessionId, MageVersion version) throws MageException; + boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException; // Not used // void deregisterClient(String sessionId) throws MageException; // update methods List getMissingExpansionData(List codes); + List getMissingCardsData(List classNames); // user methods - boolean setUserData(String userName, String sessionId, UserDataView userDataView) throws MageException; + boolean setUserData(String userName, String sessionId, UserData userData) throws MageException; + void sendFeedbackMessage(String sessionId, String username, String title, String type, String message, String email) throws MageException; // server state methods ServerState getServerState() throws MageException; + List getRoomUsers(UUID roomId) throws MageException; + List getFinishedMatches(UUID roomId) throws MageException; + Object getServerMessagesCompressed(String sessionId) throws MageException; // messages of the day // ping - extends session @@ -81,27 +86,46 @@ public interface MageServer { //table methods TableView createTable(String sessionId, UUID roomId, MatchOptions matchOptions) throws MageException; + TableView createTournamentTable(String sessionId, UUID roomId, TournamentOptions tournamentOptions) throws MageException; + boolean joinTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException, GameException; + boolean joinTournamentTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException, GameException; + boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException; + void updateDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException; + boolean watchTable(String sessionId, UUID roomId, UUID tableId) throws MageException; + boolean watchTournamentTable(String sessionId, UUID tableId) throws MageException; + boolean leaveTable(String sessionId, UUID roomId, UUID tableId) throws MageException; + void swapSeats(String sessionId, UUID roomId, UUID tableId, int seatNum1, int seatNum2) throws MageException; + void removeTable(String sessionId, UUID roomId, UUID tableId) throws MageException; + boolean isTableOwner(String sessionId, UUID roomId, UUID tableId) throws MageException; + TableView getTable(UUID roomId, UUID tableId) throws MageException; + List getTables(UUID roomId) throws MageException; //chat methods void sendChatMessage(UUID chatId, String userName, String message) throws MageException; + void joinChat(UUID chatId, String sessionId, String userName) throws MageException; + void leaveChat(UUID chatId, String sessionId) throws MageException; + UUID getTableChatId(UUID tableId) throws MageException; + UUID getGameChatId(UUID gameId) throws MageException; + UUID getRoomChatId(UUID roomId) throws MageException; + UUID getTournamentChatId(UUID tournamentId) throws MageException; //room methods @@ -109,50 +133,77 @@ public interface MageServer { //game methods boolean startMatch(String sessionId, UUID roomId, UUID tableId) throws MageException; + void joinGame(UUID gameId, String sessionId) throws MageException; + void watchGame(UUID gameId, String sessionId) throws MageException; + void stopWatching(UUID gameId, String sessionId) throws MageException; + void sendPlayerUUID(UUID gameId, String sessionId, UUID data) throws MageException; + void sendPlayerString(UUID gameId, String sessionId, String data) throws MageException; + void sendPlayerBoolean(UUID gameId, String sessionId, Boolean data) throws MageException; + void sendPlayerInteger(UUID gameId, String sessionId, Integer data) throws MageException; + void sendPlayerManaType(UUID gameId, UUID playerId, String sessionId, ManaType data) throws MageException; + void quitMatch(UUID gameId, String sessionId) throws MageException; + GameView getGameView(UUID gameId, String sessionId, UUID playerId) throws MageException; + // priority, undo, concede, mana pool + void sendPlayerAction(PlayerAction playerAction, UUID gameId, String sessionId, Object data) throws MageException; //tournament methods boolean startTournament(String sessionId, UUID roomId, UUID tableId) throws MageException; + void joinTournament(UUID draftId, String sessionId) throws MageException; + void quitTournament(UUID tournamentId, String sessionId) throws MageException; + TournamentView getTournament(UUID tournamentId) throws MageException; //draft methods void joinDraft(UUID draftId, String sessionId) throws MageException; + void quitDraft(UUID draftId, String sessionId) throws MageException; + DraftPickView sendCardPick(UUID draftId, String sessionId, UUID cardId, Set hiddenCards) throws MageException; + void sendCardMark(UUID draftId, String sessionId, UUID cardId) throws MageException; //challenge methods // void startChallenge(String sessionId, UUID roomId, UUID tableId, UUID challengeId) throws MageException; - //replay methods void replayGame(UUID gameId, String sessionId) throws MageException; + void startReplay(UUID gameId, String sessionId) throws MageException; + void stopReplay(UUID gameId, String sessionId) throws MageException; + void nextPlay(UUID gameId, String sessionId) throws MageException; + void previousPlay(UUID gameId, String sessionId) throws MageException; + void skipForward(UUID gameId, String sessionId, int moves) throws MageException; //test methods void cheat(UUID gameId, String sessionId, UUID playerId, DeckCardLists deckList) throws MageException; + boolean cheat(UUID gameId, String sessionId, UUID playerId, String cardName) throws MageException; //admin methods List getUsers(String sessionId) throws MageException; + void disconnectUser(String sessionId, String userSessionId) throws MageException; + void endUserSession(String sessionId, String userSessionId) throws MageException; + void removeTable(String sessionId, UUID tableId) throws MageException; + void sendBroadcastMessage(String sessionId, String message) throws MageException; } diff --git a/Mage.Common/src/mage/remote/Connection.java b/Mage.Common/src/mage/remote/Connection.java index e8337feacde..0c4e86c827f 100644 --- a/Mage.Common/src/mage/remote/Connection.java +++ b/Mage.Common/src/mage/remote/Connection.java @@ -1,31 +1,30 @@ /* -* Copyright 2011 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. -*/ - + * Copyright 2011 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.remote; import java.net.Inet4Address; @@ -34,8 +33,7 @@ import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; -import mage.players.net.UserSkipPrioritySteps; -import mage.view.UserDataView; +import mage.players.net.UserData; /** * @@ -55,37 +53,36 @@ public class Connection { private int clientCardDatabaseVersion; private boolean forceDBComparison; - private UserDataView userData; - + private UserData userData; + // private int avatarId; // private boolean showAbilityPickerForced; // private boolean allowRequestShowHandCards; // private boolean confirmEmptyManaPool; // private String flagName; // private UserSkipPrioritySteps userSkipPrioritySteps; - - private static final String serialization = "?serializationtype=jboss"; + private static final String serialization = "?serializationtype=jboss"; private static final String transport = "bisocket"; - private final String parameter; - + private final String parameter; + public Connection() { this(""); } - + public Connection(String parameter) { this.parameter = parameter; } - + @Override public int hashCode() { - return (transport + host + Integer.toString(port) + proxyType.toString()).hashCode(); + return (transport + host + Integer.toString(port) + proxyType.toString()).hashCode(); } @Override public boolean equals(Object object) { - if (! (object instanceof Connection)) { - return false; + if (!(object instanceof Connection)) { + return false; } Connection otherConnection = (Connection) object; return hashCode() == otherConnection.hashCode(); @@ -119,6 +116,7 @@ public class Connection { } public enum ProxyType { + SOCKS("Socks"), HTTP("HTTP"), NONE("None"); private final String text; @@ -207,12 +205,12 @@ public class Connection { } public static InetAddress getLocalAddress() throws SocketException { - for (Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) { - NetworkInterface iface = interfaces.nextElement( ); + for (Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) { + NetworkInterface iface = interfaces.nextElement(); if (iface.isLoopback()) { continue; } - for (InterfaceAddress addr: iface.getInterfaceAddresses()) { + for (InterfaceAddress addr : iface.getInterfaceAddresses()) { if (addr != null) { InetAddress iaddr = addr.getAddress(); if (iaddr != null && iaddr instanceof Inet4Address) { @@ -224,11 +222,11 @@ public class Connection { return null; } - public void setUserData(UserDataView userData) { - this.userData= userData; + public void setUserData(UserData userData) { + this.userData = userData; } - - public UserDataView getUserData() { + + public UserData getUserData() { return userData; } diff --git a/Mage.Common/src/mage/remote/SessionImpl.java b/Mage.Common/src/mage/remote/SessionImpl.java index a5bf686b3bc..8017868ba74 100644 --- a/Mage.Common/src/mage/remote/SessionImpl.java +++ b/Mage.Common/src/mage/remote/SessionImpl.java @@ -1,31 +1,30 @@ /* -* 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. -*/ - + * 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.remote; import java.io.IOException; @@ -61,8 +60,8 @@ import mage.interfaces.MageClient; import mage.interfaces.MageServer; import mage.interfaces.ServerState; import mage.interfaces.callback.ClientCallback; +import mage.players.net.UserData; import mage.utils.CompressUtil; -import mage.players.net.UserSkipPrioritySteps; import mage.view.DraftPickView; import mage.view.GameTypeView; import mage.view.MatchView; @@ -70,7 +69,6 @@ import mage.view.RoomUsersView; import mage.view.TableView; import mage.view.TournamentTypeView; import mage.view.TournamentView; -import mage.view.UserDataView; import mage.view.UserView; import org.apache.log4j.Logger; import org.jboss.remoting.CannotConnectException; @@ -106,7 +104,7 @@ public class SessionImpl implements Session { private Connection connection; private final static int PING_CYCLES = 10; private final LinkedList pingTime = new LinkedList<>(); - private String pingInfo = ""; + private String pingInfo = ""; private static boolean debugMode = false; private boolean canceled = false; @@ -123,7 +121,7 @@ public class SessionImpl implements Session { public String getSessionId() { return sessionId; } - + @Override public synchronized boolean connect(Connection connection) { if (isConnected()) { @@ -165,82 +163,88 @@ public class SessionImpl implements Session { break; } InvokerLocator clientLocator = new InvokerLocator(connection.getURI()); - + Map metadata = new HashMap<>(); /* - 5.8.3.1.1. Write timeouts - The socket timeout facility offered by the JDK applies only to read operations on the socket. As of release 2.5.2, - the socket and bisocket (and also sslsocket and sslbisocket) transports offer a write timeout facility. When a client - or server is configured, in any of the usual ways, with the parameter org.jboss.remoting.transport.socket.SocketWrapper.WRITE_TIMEOUT - (actual value "writeTimeout") set to a positive value (in milliseconds), all write operations will time out if they do - not complete within the configured period. When a write operation times out, the socket upon which the write was invoked - will be closed, which is likely to result in a java.net.SocketException. - Note. A SocketException is considered to be a "retriable" exception, so, if the parameter "numberOfCallRetries" is set - to a value greater than 1, an invocation interrupted by a write timeout can be retried. - Note. The write timeout facility applies to writing of both invocations and responses. It applies to push callbacks as well. - */ + 5.8.3.1.1. Write timeouts + The socket timeout facility offered by the JDK applies only to read operations on the socket. As of release 2.5.2, + the socket and bisocket (and also sslsocket and sslbisocket) transports offer a write timeout facility. When a client + or server is configured, in any of the usual ways, with the parameter org.jboss.remoting.transport.socket.SocketWrapper.WRITE_TIMEOUT + (actual value "writeTimeout") set to a positive value (in milliseconds), all write operations will time out if they do + not complete within the configured period. When a write operation times out, the socket upon which the write was invoked + will be closed, which is likely to result in a java.net.SocketException. + Note. A SocketException is considered to be a "retriable" exception, so, if the parameter "numberOfCallRetries" is set + to a value greater than 1, an invocation interrupted by a write timeout can be retried. + Note. The write timeout facility applies to writing of both invocations and responses. It applies to push callbacks as well. + */ metadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); metadata.put("generalizeSocketException", "true"); server = (MageServer) TransporterClient.createTransporterClient(clientLocator.getLocatorURI(), MageServer.class, metadata); // http://docs.jboss.org/jbossremoting/docs/guide/2.5/html_single/#d0e1057 Map clientMetadata = new HashMap<>(); - + clientMetadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); - /* generalizeSocketException - * If set to false, a failed invocation will be retried in the case of - * SocketExceptions. If set to true, a failed invocation will be retried in the case of - * SocketExceptions and also any IOException - * whose message matches the regular expression - * ^.*(?:connection.*reset|connection.*closed|broken.*pipe).*$. - * See also the "numberOfCallRetries" parameter, above. The default value is false.*/ + /* generalizeSocketException + * If set to false, a failed invocation will be retried in the case of + * SocketExceptions. If set to true, a failed invocation will be retried in the case of + * SocketExceptions and also any IOException + * whose message matches the regular expression + * ^.*(?:connection.*reset|connection.*closed|broken.*pipe).*$. + * See also the "numberOfCallRetries" parameter, above. The default value is false.*/ clientMetadata.put("generalizeSocketException", "true"); - - /* A remoting server also has the capability to detect when a client is no longer available. - * This is done by estabilishing a lease with the remoting clients that connect to a server. - * On the client side, an org.jboss.remoting.LeasePinger periodically sends PING messages to - * the server, and on the server side an org.jboss.remoting.Lease informs registered listeners - * if the PING doesn't arrive withing the specified timeout period. */ + + /* A remoting server also has the capability to detect when a client is no longer available. + * This is done by estabilishing a lease with the remoting clients that connect to a server. + * On the client side, an org.jboss.remoting.LeasePinger periodically sends PING messages to + * the server, and on the server side an org.jboss.remoting.Lease informs registered listeners + * if the PING doesn't arrive withing the specified timeout period. */ clientMetadata.put(Client.ENABLE_LEASE, "true"); /* - When the socket client invoker makes its first invocation, it will check to see if there is an available - socket connection in its pool. Since is the first invocation, there will not be and will create a new socket - connection and use it for making the invocation. Then when finished making invocation, will return the still - active socket connection to the pool. As more client invocations are made, is possible for the number of - socket connections to reach the maximum allowed (which is controlled by 'clientMaxPoolSize' property). At this - point, when the next client invocation is made, it will wait up to some configured number of milliseconds, at - which point it will throw an org.jboss.remoting.CannotConnectException. The number of milliseconds is given by - the parameter MicroSocketClientInvoker.CONNECTION_WAIT (actual value "connectionWait"), with a default of - 30000 milliseconds. Note that if more than one call retry is configured (see next paragraph), - the CannotConnectException will be swallowed. - Once the socket client invoker get an available socket connection from the pool, are not out of the woods yet. - For example, a network problem could cause a java.net.SocketException. There is also a possibility that the socket - connection, while still appearing to be valid, has "gone stale" while sitting in the pool. For example, a ServerThread - on the other side of the connection could time out and close its socket. If the attempt to complete an invocation - fails, then MicroSocketClientInvoker will make a number of attempts, according to the parameter "numberOfCallRetries", - with a default value of 3. Once the configured number of retries has been exhausted, - an org.jboss.remoting.InvocationFailureException will be thrown. - */ + When the socket client invoker makes its first invocation, it will check to see if there is an available + socket connection in its pool. Since is the first invocation, there will not be and will create a new socket + connection and use it for making the invocation. Then when finished making invocation, will return the still + active socket connection to the pool. As more client invocations are made, is possible for the number of + socket connections to reach the maximum allowed (which is controlled by 'clientMaxPoolSize' property). At this + point, when the next client invocation is made, it will wait up to some configured number of milliseconds, at + which point it will throw an org.jboss.remoting.CannotConnectException. The number of milliseconds is given by + the parameter MicroSocketClientInvoker.CONNECTION_WAIT (actual value "connectionWait"), with a default of + 30000 milliseconds. Note that if more than one call retry is configured (see next paragraph), + the CannotConnectException will be swallowed. + Once the socket client invoker get an available socket connection from the pool, are not out of the woods yet. + For example, a network problem could cause a java.net.SocketException. There is also a possibility that the socket + connection, while still appearing to be valid, has "gone stale" while sitting in the pool. For example, a ServerThread + on the other side of the connection could time out and close its socket. If the attempt to complete an invocation + fails, then MicroSocketClientInvoker will make a number of attempts, according to the parameter "numberOfCallRetries", + with a default value of 3. Once the configured number of retries has been exhausted, + an org.jboss.remoting.InvocationFailureException will be thrown. + */ clientMetadata.put("numberOfCallRetries", "1"); - /** - * I'll explain the meaning of "secondaryBindPort" and "secondaryConnectPort", and maybe that will help. - * The Remoting bisocket transport creates two ServerSockets on the server. The "primary" ServerSocket is used to create - * connections used for ordinary invocations, e.g., a request to create a JMS consumer, and the "secondary" ServerSocket - * is used to create "control" connections for internal Remoting messages. The port for the primary ServerSocket is configured - * by the "serverBindPort" parameter, and the port for the secondary ServerSocket is, by default, chosen randomly. - * The "secondaryBindPort" parameter can be used to assign a specific port to the secondary ServerSocket. Now, if there is a - * translating firewall between the client and server, the client should be given the value of the port that is translated - * to the actual binding port of the secondary ServerSocket. - * For example, your configuration will tell the secondary ServerSocket to bind to port 14000, and it will tell the client to - * connect to port 14001. It assumes that there is a firewall which will translate 14001 to 14000. Apparently, that's not happening. + * I'll explain the meaning of "secondaryBindPort" and + * "secondaryConnectPort", and maybe that will help. The Remoting + * bisocket transport creates two ServerSockets on the server. The + * "primary" ServerSocket is used to create connections used for + * ordinary invocations, e.g., a request to create a JMS consumer, + * and the "secondary" ServerSocket is used to create "control" + * connections for internal Remoting messages. The port for the + * primary ServerSocket is configured by the "serverBindPort" + * parameter, and the port for the secondary ServerSocket is, by + * default, chosen randomly. The "secondaryBindPort" parameter can + * be used to assign a specific port to the secondary ServerSocket. + * Now, if there is a translating firewall between the client and + * server, the client should be given the value of the port that is + * translated to the actual binding port of the secondary + * ServerSocket. For example, your configuration will tell the + * secondary ServerSocket to bind to port 14000, and it will tell + * the client to connect to port 14001. It assumes that there is a + * firewall which will translate 14001 to 14000. Apparently, that's + * not happening. */ // secondaryBindPort - the port to which the secondary server socket is to be bound. By default, an arbitrary port is selected. - // secondaryConnectPort - the port clients are to use to connect to the secondary server socket. - // By default, the value of secondaryBindPort is used. secondaryConnectPort is useful if the server is behind a translating firewall. - + // By default, the value of secondaryBindPort is used. secondaryConnectPort is useful if the server is behind a translating firewall. // Indicated the max number of threads used within oneway thread pool. clientMetadata.put(Client.MAX_NUM_ONEWAY_THREADS, "10"); clientMetadata.put(Remoting.USE_CLIENT_CONNECTION_IDENTITY, "true"); @@ -269,7 +273,7 @@ public class SessionImpl implements Session { logger.warn("There should be one callback Connector (number existing = " + callbackConnectors.size() + ")"); } - logger.info("Trying to connect as " + (this.getUserName() == null ? "":this.getUserName()) + " to XMAGE server at " + connection.getHost() + ":" + connection.getPort()); + logger.info("Trying to connect as " + (this.getUserName() == null ? "" : this.getUserName()) + " to XMAGE server at " + connection.getHost() + ":" + connection.getPort()); callbackClient.invoke(null); this.sessionId = callbackClient.getSessionId(); @@ -289,15 +293,15 @@ public class SessionImpl implements Session { if (!connection.getUsername().equals("Admin")) { updateDatabase(connection.isForceDBComparison(), serverState); } - logger.info("Connected as " + (this.getUserName() == null ? "":this.getUserName()) + " to MAGE server at " + connection.getHost() + ":" + connection.getPort()); - client.connected(this.getUserName() == null ? "":this.getUserName() +"@" + connection.getHost() + ":" + connection.getPort() +" "); + logger.info("Connected as " + (this.getUserName() == null ? "" : this.getUserName()) + " to MAGE server at " + connection.getHost() + ":" + connection.getPort()); + client.connected(this.getUserName() == null ? "" : this.getUserName() + "@" + connection.getHost() + ":" + connection.getPort() + " "); return true; } disconnect(false); // client.showMessage("Unable to connect to server."); } catch (MalformedURLException ex) { logger.fatal("", ex); - client.showMessage("Unable to connect to server. " + ex.getMessage()); + client.showMessage("Unable to connect to server. " + ex.getMessage()); } catch (UndeclaredThrowableException ex) { String addMessage = ""; if (ex.getCause() instanceof InvocationFailureException) { @@ -311,17 +315,17 @@ public class SessionImpl implements Session { if (addMessage.isEmpty()) { logger.fatal("", ex); } - client.showMessage("Unable to connect to server. " + addMessage + (ex.getMessage() != null ? ex.getMessage():"")); + client.showMessage("Unable to connect to server. " + addMessage + (ex.getMessage() != null ? ex.getMessage() : "")); } catch (IOException ex) { logger.fatal("", ex); String addMessage = ""; if (ex.getMessage() != null && ex.getMessage().startsWith("Unable to perform invocation")) { addMessage = "Maybe the server version is not compatible. "; } - client.showMessage("Unable to connect to server. " + addMessage + ex.getMessage() != null ? ex.getMessage():""); + client.showMessage("Unable to connect to server. " + addMessage + ex.getMessage() != null ? ex.getMessage() : ""); } catch (MageVersionException ex) { if (!canceled) { - client.showMessage("Unable to connect to server. " + ex.getMessage()); + client.showMessage("Unable to connect to server. " + ex.getMessage()); } disconnect(false); } catch (CannotConnectException ex) { @@ -334,12 +338,12 @@ public class SessionImpl implements Session { disconnect(false); StringBuilder sb = new StringBuilder(); sb.append("Unable to connect to server.\n"); - for (StackTraceElement element :t.getStackTrace()) { + for (StackTraceElement element : t.getStackTrace()) { sb.append(element.toString()).append("\n"); } client.showMessage(sb.toString()); } - } + } return false; } @@ -350,8 +354,8 @@ public class SessionImpl implements Session { List cards = server.getMissingCardsData(classNames); CardRepository.instance.addCards(cards); CardRepository.instance.setContentVersion(serverState.getCardsContentVersion()); - logger.info("Updating client cards DB - existing cards: " + classNames.size() + " new cards: " + cards.size() + - " content versions - server: " + serverState.getCardsContentVersion() + " client: " + cardDBVersion); + logger.info("Updating client cards DB - existing cards: " + classNames.size() + " new cards: " + cards.size() + + " content versions - server: " + serverState.getCardsContentVersion() + " client: " + cardDBVersion); } long expansionDBVersion = ExpansionRepository.instance.getContentVersionFromDB(); @@ -362,8 +366,8 @@ public class SessionImpl implements Session { ExpansionRepository.instance.add(expansion); } ExpansionRepository.instance.setContentVersion(serverState.getExpansionsContentVersion()); - logger.info("Updating client expansions DB - existing sets: " + setCodes.size() + " new sets: " + expansions.size()+ - " content versions - server: " + serverState.getExpansionsContentVersion() + " client: " + expansionDBVersion); + logger.info("Updating client expansions DB - existing sets: " + setCodes.size() + " new sets: " + expansions.size() + + " content versions - server: " + serverState.getExpansionsContentVersion() + " client: " + expansionDBVersion); } } @@ -399,7 +403,8 @@ public class SessionImpl implements Session { /** * - * @param askForReconnect - true = connection was lost because of error and ask the user if he want to try to reconnect + * @param askForReconnect - true = connection was lost because of error and + * ask the user if he want to try to reconnect */ @Override public synchronized void disconnect(boolean askForReconnect) { @@ -410,7 +415,7 @@ public class SessionImpl implements Session { if (connection == null || sessionState == SessionState.DISCONNECTED) { return; } - + try { callbackClient.removeListener(callbackHandler); callbackClient.disconnect(); @@ -450,10 +455,11 @@ public class SessionImpl implements Session { } class CallbackHandler implements InvokerCallbackHandler { + @Override public void handleCallback(Callback callback) throws HandleCallbackException { //logger.info("callback handler"); - client.processCallback((ClientCallback)callback.getCallbackObject()); + client.processCallback((ClientCallback) callback.getCallbackObject()); } } @@ -502,7 +508,6 @@ public class SessionImpl implements Session { return serverState.getDraftCubes(); } - @Override public List getTournamentTypes() { return serverState.getTournamentTypes(); @@ -561,7 +566,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return null; } @@ -588,7 +593,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -621,7 +626,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -637,7 +642,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -652,7 +657,7 @@ public class SessionImpl implements Session { handleMageException(ex); throw new MageRemoteException(); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return null; } @@ -667,7 +672,7 @@ public class SessionImpl implements Session { handleMageException(ex); throw new MageRemoteException(); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return null; } @@ -697,7 +702,7 @@ public class SessionImpl implements Session { handleMageException(ex); throw new MageRemoteException(); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return null; } @@ -711,7 +716,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return null; } @@ -726,7 +731,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -741,7 +746,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -756,7 +761,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -771,7 +776,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -800,7 +805,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return null; } @@ -829,7 +834,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -845,7 +850,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); // } finally { // lock.readLock().unlock(); } @@ -863,7 +868,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); // } finally { // lock.readLock().unlock(); } @@ -895,7 +900,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -910,7 +915,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -925,7 +930,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -940,7 +945,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -955,7 +960,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -969,7 +974,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return null; } @@ -983,7 +988,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return null; } @@ -997,7 +1002,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1013,13 +1018,14 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } /** * Remove table - called from admin console + * * @param tableId * @return */ @@ -1033,7 +1039,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1048,7 +1054,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1062,7 +1068,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1088,7 +1094,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1107,7 +1113,6 @@ public class SessionImpl implements Session { // } // return false; // } - @Override public boolean submitDeck(UUID tableId, DeckCardLists deck) { try { @@ -1119,7 +1124,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1136,7 +1141,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1198,7 +1203,7 @@ public class SessionImpl implements Session { } return false; } - + @Override public boolean stopWatching(UUID gameId) { try { @@ -1209,7 +1214,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1224,7 +1229,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1239,7 +1244,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1254,7 +1259,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1269,7 +1274,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1284,7 +1289,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1299,7 +1304,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1313,7 +1318,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return null; } @@ -1342,7 +1347,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } catch (Throwable t) { - handleThrowable(t); + handleThrowable(t); } return false; } @@ -1384,14 +1389,13 @@ public class SessionImpl implements Session { client.showError(ex.getMessage()); } - @Override public String getUserName() { return connection.getUsername(); } @Override - public boolean updatePreferencesForServer(UserDataView userData) { + public boolean updatePreferencesForServer(UserData userData) { try { if (isConnected()) { server.setUserData(connection.getUsername(), sessionId, userData); @@ -1411,26 +1415,26 @@ public class SessionImpl implements Session { if (isConnected()) { long startTime = System.nanoTime(); if (!server.ping(sessionId, pingInfo)) { - logger.error("Ping failed: " + this.getUserName() + " Session: " + sessionId + " to MAGE server at " + connection.getHost() +":" + connection.getPort()); + logger.error("Ping failed: " + this.getUserName() + " Session: " + sessionId + " to MAGE server at " + connection.getHost() + ":" + connection.getPort()); throw new MageException("Ping failed"); } pingTime.add(System.nanoTime() - startTime); long milliSeconds = TimeUnit.MILLISECONDS.convert(pingTime.getLast(), TimeUnit.NANOSECONDS); - String lastPing = milliSeconds > 0 ? milliSeconds+"ms" : "<1ms"; + String lastPing = milliSeconds > 0 ? milliSeconds + "ms" : "<1ms"; if (pingTime.size() > PING_CYCLES) { pingTime.poll(); } long sum = 0; - for (Long time :pingTime) { + for (Long time : pingTime) { sum += time; } milliSeconds = TimeUnit.MILLISECONDS.convert(sum / pingTime.size(), TimeUnit.NANOSECONDS); - pingInfo = lastPing + " (Av: " + (milliSeconds > 0 ? milliSeconds + "ms":"<1ms")+")"; + pingInfo = lastPing + " (Av: " + (milliSeconds > 0 ? milliSeconds + "ms" : "<1ms") + ")"; } return true; } catch (MageException ex) { - handleMageException(ex); - disconnect(true); + handleMageException(ex); + disconnect(true); } catch (Throwable t) { handleThrowable(t); } @@ -1448,7 +1452,6 @@ public class SessionImpl implements Session { } - class MageAuthenticator extends Authenticator { private final String username; @@ -1460,7 +1463,7 @@ class MageAuthenticator extends Authenticator { } @Override - public PasswordAuthentication getPasswordAuthentication () { - return new PasswordAuthentication (username, password.toCharArray()); + public PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password.toCharArray()); } } diff --git a/Mage.Common/src/mage/remote/interfaces/ClientData.java b/Mage.Common/src/mage/remote/interfaces/ClientData.java index 7b4f248d934..741b69b1b54 100644 --- a/Mage.Common/src/mage/remote/interfaces/ClientData.java +++ b/Mage.Common/src/mage/remote/interfaces/ClientData.java @@ -1,33 +1,33 @@ /* -* 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. -*/ + * 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.remote.interfaces; -import mage.view.UserDataView; +import mage.players.net.UserData; /** * @author noxx @@ -36,5 +36,5 @@ public interface ClientData { String getUserName(); - boolean updatePreferencesForServer(UserDataView userData); + boolean updatePreferencesForServer(UserData userData); } diff --git a/Mage.Common/src/mage/view/PlayerView.java b/Mage.Common/src/mage/view/PlayerView.java index 487e84afd26..14c3990eb38 100644 --- a/Mage.Common/src/mage/view/PlayerView.java +++ b/Mage.Common/src/mage/view/PlayerView.java @@ -1,31 +1,30 @@ /* -* 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. -*/ - + * 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.view; import java.io.Serializable; @@ -44,12 +43,14 @@ import mage.game.command.Commander; import mage.game.command.Emblem; import mage.game.permanent.Permanent; import mage.players.Player; +import mage.players.net.UserData; /** * * @author BetaSteward_at_googlemail.com */ public class PlayerView implements Serializable { + private static final long serialVersionUID = 1L; private final UUID playerId; @@ -67,7 +68,7 @@ public class PlayerView implements Serializable { private final CardsView exile = new CardsView(); private final Map battlefield = new LinkedHashMap<>(); private final CardView topCard; - private final UserDataView userDataView; + private final UserData userData; private final List commandList = new ArrayList<>(); private final List attachments = new ArrayList<>(); private final int statesSavedSize; @@ -89,50 +90,49 @@ public class PlayerView implements Serializable { this.isActive = (player.getId().equals(state.getActivePlayerId())); this.hasPriority = player.getId().equals(state.getPriorityPlayerId()); this.priorityTimeLeft = player.getPriorityTimeLeft(); - this.timerActive = (this.hasPriority && player.isGameUnderControl()) || - (player.getPlayersUnderYourControl().contains(state.getPriorityPlayerId())) || - player.getId().equals(game.getState().getChoosingPlayerId()); + this.timerActive = (this.hasPriority && player.isGameUnderControl()) + || (player.getPlayersUnderYourControl().contains(state.getPriorityPlayerId())) + || player.getId().equals(game.getState().getChoosingPlayerId()); this.hasLeft = player.hasLeft(); - for (Card card: player.getGraveyard().getCards(game)) { + for (Card card : player.getGraveyard().getCards(game)) { graveyard.put(card.getId(), new CardView(card, game, false)); } for (ExileZone exileZone : game.getExile().getExileZones()) { for (Card card : exileZone.getCards(game)) { if (player.getId().equals(card.getOwnerId())) { exile.put(card.getId(), new CardView(card, game, false)); // unnown if it's allowed to look under a face down card - } + } } } - for (Permanent permanent: state.getBattlefield().getAllPermanents()) { + for (Permanent permanent : state.getBattlefield().getAllPermanents()) { if (showInBattlefield(permanent, state)) { PermanentView view = new PermanentView(permanent, game.getCard(permanent.getId()), createdForPlayerId, game); battlefield.put(view.getId(), view); } } - this.topCard = player.isTopCardRevealed() && player.getLibrary().size() > 0 ? - new CardView(player.getLibrary().getFromTop(game)) : null; + this.topCard = player.isTopCardRevealed() && player.getLibrary().size() > 0 + ? new CardView(player.getLibrary().getFromTop(game)) : null; if (player.getUserData() != null) { - this.userDataView = new UserDataView(player.getUserData()); + this.userData = player.getUserData(); } else { - this.userDataView = UserDataView.getDefaultUserDataView(); + this.userData = UserData.getDefaultUserDataView(); } - + for (CommandObject commandObject : game.getState().getCommand()) { if (commandObject instanceof Emblem) { Emblem emblem = (Emblem) commandObject; if (emblem.getControllerId().equals(this.playerId)) { - Card sourceCard = game.getCard(((CommandObject)emblem).getSourceId()); + Card sourceCard = game.getCard(((CommandObject) emblem).getSourceId()); if (sourceCard != null) { commandList.add(new EmblemView(emblem, sourceCard)); } } - } - else if(commandObject instanceof Commander){ - Commander commander = (Commander)commandObject; - if(commander.getControllerId().equals(this.playerId)){ + } else if (commandObject instanceof Commander) { + Commander commander = (Commander) commandObject; + if (commander.getControllerId().equals(this.playerId)) { Card sourceCard = game.getCard(commander.getSourceId()); - if(sourceCard != null){ + if (sourceCard != null) { commandList.add(new CommanderView(commander, sourceCard, game)); } } @@ -157,13 +157,11 @@ public class PlayerView implements Serializable { //show permanents controlled by player or attachments to permanents controlled by player if (permanent.getAttachedTo() == null) { return permanent.getControllerId().equals(playerId); - } - else { + } else { Permanent attachedTo = state.getPermanent(permanent.getAttachedTo()); if (attachedTo != null) { return attachedTo.getControllerId().equals(playerId); - } - else { + } else { return permanent.getControllerId().equals(playerId); } } @@ -221,8 +219,8 @@ public class PlayerView implements Serializable { return this.topCard; } - public UserDataView getUserData() { - return this.userDataView; + public UserData getUserData() { + return this.userData; } public List getCommadObjectList() { diff --git a/Mage.Common/src/mage/view/SeatView.java b/Mage.Common/src/mage/view/SeatView.java index 7a9f2badf12..f8f79a397e2 100644 --- a/Mage.Common/src/mage/view/SeatView.java +++ b/Mage.Common/src/mage/view/SeatView.java @@ -1,31 +1,30 @@ /* -* 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. -*/ - + * 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.view; import java.io.Serializable; @@ -37,16 +36,23 @@ import mage.game.Seat; * @author BetaSteward_at_googlemail.com */ public class SeatView implements Serializable { + private static final long serialVersionUID = 1L; + private final String flagName; private UUID playerId; - private String playerName; - private String playerType; + private final String playerName; + private final String playerType; public SeatView(Seat seat) { if (seat.getPlayer() != null) { this.playerId = seat.getPlayer().getId(); this.playerName = seat.getPlayer().getName(); + this.flagName = seat.getPlayer().getUserData().getFlagName(); + } else { + // Empty seat + this.playerName = ""; + this.flagName = ""; } this.playerType = seat.getPlayerType(); } @@ -63,4 +69,8 @@ public class SeatView implements Serializable { return playerType; } + public String getFlagName() { + return flagName; + } + } diff --git a/Mage.Common/src/mage/view/TournamentPlayerView.java b/Mage.Common/src/mage/view/TournamentPlayerView.java index 8a1bcc22954..2c488cd6921 100644 --- a/Mage.Common/src/mage/view/TournamentPlayerView.java +++ b/Mage.Common/src/mage/view/TournamentPlayerView.java @@ -1,16 +1,16 @@ /* * Copyright 2011 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.view; import java.io.Serializable; @@ -35,9 +34,11 @@ import mage.game.tournament.TournamentPlayer; * * @author BetaSteward_at_googlemail.com */ -public class TournamentPlayerView implements Serializable, Comparable{ +public class TournamentPlayerView implements Serializable, Comparable { + private static final long serialVersionUID = 1L; + private final String flagName; private final String name; private final String state; private final String results; @@ -46,7 +47,7 @@ public class TournamentPlayerView implements Serializable, Comparable{ TournamentPlayerView(TournamentPlayer tournamentPlayer) { this.name = tournamentPlayer.getPlayer().getName(); - StringBuilder sb = new StringBuilder(tournamentPlayer.getState().toString()); + StringBuilder sb = new StringBuilder(tournamentPlayer.getState().toString()); String stateInfo = tournamentPlayer.getStateInfo(); if (!stateInfo.isEmpty()) { sb.append(" (").append(stateInfo).append(")"); @@ -56,6 +57,7 @@ public class TournamentPlayerView implements Serializable, Comparable{ this.points = tournamentPlayer.getPoints(); this.results = tournamentPlayer.getResults(); this.quit = !tournamentPlayer.isInTournament(); + this.flagName = tournamentPlayer.getPlayer().getUserData().getFlagName(); } public String getName() { @@ -83,4 +85,7 @@ public class TournamentPlayerView implements Serializable, Comparable{ return ((TournamentPlayerView) t).getPoints() - this.getPoints(); } + public String getFlagName() { + return flagName; + } } diff --git a/Mage.Common/src/mage/view/UserDataView.java b/Mage.Common/src/mage/view/UserDataView.java index 40171cbe315..cc313936a9e 100644 --- a/Mage.Common/src/mage/view/UserDataView.java +++ b/Mage.Common/src/mage/view/UserDataView.java @@ -2,6 +2,7 @@ package mage.view; import java.io.Serializable; import mage.players.net.UserData; +import mage.players.net.UserGroup; import mage.players.net.UserSkipPrioritySteps; /** @@ -20,11 +21,11 @@ public class UserDataView implements Serializable { String flagName; protected boolean askMoveToGraveOrder; - static UserDataView getDefaultUserDataView() { - return new UserDataView(0, false, false, true, null,"world.png", false); + static UserData getDefaultUserDataView() { + return new UserData(UserGroup.DEFAULT, 0, false, false, true, null, "world.png", false); } - - public UserDataView(int avatarId, boolean showAbilityPickerForced, boolean allowRequestShowHandCards, + + public UserDataView(int avatarId, boolean showAbilityPickerForced, boolean allowRequestShowHandCards, boolean confirmEmptyManaPool, UserSkipPrioritySteps userSkipPrioritySteps, String flagName, boolean askMoveToGraveOrder) { this.avatarId = avatarId; this.showAbilityPickerForced = showAbilityPickerForced; @@ -33,7 +34,7 @@ public class UserDataView implements Serializable { this.confirmEmptyManaPool = confirmEmptyManaPool; this.flagName = flagName; this.askMoveToGraveOrder = askMoveToGraveOrder; - + } public UserDataView(UserData userData) { @@ -74,5 +75,5 @@ public class UserDataView implements Serializable { public boolean askMoveToGraveOrder() { return askMoveToGraveOrder; } - + } 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 0f7fe7b3832..4fc02a780e1 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 @@ -1,31 +1,30 @@ /* -* 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. -*/ - + * 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.player.ai; import java.io.IOException; @@ -150,7 +149,6 @@ import mage.util.Copier; import mage.util.TreeNode; import org.apache.log4j.Logger; - /** * * suitable for two player games and some multiplayer games @@ -160,10 +158,10 @@ import org.apache.log4j.Logger; public class ComputerPlayer extends PlayerImpl implements Player { private transient final static Logger log = Logger.getLogger(ComputerPlayer.class); - + protected int PASSIVITY_PENALTY = 5; // Penalty value for doing nothing if some actions are availble - protected boolean ALLOW_INTERRUPT = true; // change this for test purposes to switch off interrupts while debugging - + protected boolean ALLOW_INTERRUPT = true; // change this for test purposes to switch off interrupts while debugging + private transient Map unplayable = new TreeMap<>(); private transient List playableNonInstant = new ArrayList<>(); private transient List playableInstant = new ArrayList<>(); @@ -172,8 +170,10 @@ public class ComputerPlayer extends PlayerImpl implements Player { private transient List chosenColors; private transient ManaCost currentUnpaidMana; + public ComputerPlayer(String name, RangeOfInfluence range) { super(name, range); + flagName = "computer"; human = false; userData = new UserData(UserGroup.COMPUTER, 64, false, true, false, null, "Computer.png", false); pickedCards = new ArrayList<>(); @@ -212,7 +212,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { UUID abilityControllerId = playerId; if (target.getTargetController() != null && target.getAbilityController() != null) { abilityControllerId = target.getAbilityController(); - } + } UUID opponentId = game.getOpponents(abilityControllerId).iterator().next(); if (target instanceof TargetPlayer) { if (outcome.isGood()) { @@ -293,7 +293,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { targets = threats(abilityControllerId, sourceId, ((TargetPermanent) target).getFilter(), game, target.getTargets()); } else { targets = threats(opponentId, sourceId, ((TargetPermanent) target).getFilter(), game, target.getTargets()); - } + } } } for (Permanent permanent : targets) { @@ -306,13 +306,13 @@ public class ComputerPlayer extends PlayerImpl implements Player { } if (target instanceof TargetCardInHand) { List cards = new ArrayList<>(); - for (UUID cardId: ((TargetCardInHand)target).possibleTargets(sourceId, this.getId(), game)) { + for (UUID cardId : ((TargetCardInHand) target).possibleTargets(sourceId, this.getId(), game)) { Card card = game.getCard(cardId); if (card != null) { cards.add(card); } - } - while((outcome.isGood() ? target.getTargets().size() < target.getMaxNumberOfTargets() : !target.isChosen()) + } + while ((outcome.isGood() ? target.getTargets().size() < target.getMaxNumberOfTargets() : !target.isChosen()) && !cards.isEmpty()) { Card pick = pickTarget(cards, outcome, target, null, game); if (pick != null) { @@ -391,7 +391,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { if (target.canTarget(opponentId, null, game)) { target.add(opponentId, game); return true; - } + } if (target.canTarget(abilityControllerId, null, game)) { target.add(abilityControllerId, game); return true; @@ -400,7 +400,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { targets = opponentTargets; } else { targets = ownedTargets; - } + } for (Permanent permanent : targets) { List alreadyTargetted = target.getTargets(); if (t.canTarget(permanent.getId(), game)) { @@ -409,19 +409,19 @@ public class ComputerPlayer extends PlayerImpl implements Player { return true; } } - } + } return false; } if (target instanceof TargetCardInGraveyard) { List cards = new ArrayList<>(); - for (Player player: game.getPlayers().values()) { - for (Card card: player.getGraveyard().getCards(game)) { + for (Player player : game.getPlayers().values()) { + for (Card card : player.getGraveyard().getCards(game)) { if (target.canTarget(card.getId(), game)) { cards.add(card); } } } - for (Card card: cards) { + for (Card card : cards) { target.add(card.getId(), game); if (target.isChosen()) { return true; @@ -433,7 +433,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { if (target instanceof TargetCardInYourGraveyard) { List alreadyTargetted = target.getTargets(); List cards = new ArrayList<>(game.getPlayer(abilityControllerId).getGraveyard().getCards(game)); - while(!cards.isEmpty()) { + while (!cards.isEmpty()) { Card card = pickTarget(cards, outcome, target, null, game); if (card != null && alreadyTargetted != null && !alreadyTargetted.contains(card.getId())) { target.add(card.getId(), game); @@ -476,7 +476,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { UUID abilityControllerId = playerId; if (target.getAbilityController() != null) { abilityControllerId = target.getAbilityController(); - } + } UUID opponentId = game.getOpponents(abilityControllerId).iterator().next(); if (target instanceof TargetPlayer) { if (outcome.isGood()) { @@ -490,8 +490,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { return true; } } - } - else { + } else { if (target.canTarget(abilityControllerId, opponentId, source, game)) { target.addTarget(opponentId, source, game); return true; @@ -520,8 +519,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } } - } - else { + } else { findPlayables(game); if (unplayable.size() > 0) { for (int i = unplayable.size() - 1; i >= 0; i--) { @@ -548,12 +546,12 @@ public class ComputerPlayer extends PlayerImpl implements Player { } if (target instanceof TargetControlledPermanent) { List targets; - targets = threats(abilityControllerId, source.getSourceId(), ((TargetControlledPermanent)target).getFilter(), game, target.getTargets()); + targets = threats(abilityControllerId, source.getSourceId(), ((TargetControlledPermanent) target).getFilter(), game, target.getTargets()); if (!outcome.isGood()) { Collections.reverse(targets); } - for (Permanent permanent: targets) { - if (((TargetControlledPermanent)target).canTarget(abilityControllerId, permanent.getId(), source, game)) { + for (Permanent permanent : targets) { + if (((TargetControlledPermanent) target).canTarget(abilityControllerId, permanent.getId(), source, game)) { target.addTarget(permanent.getId(), source, game); if (target.getNumberOfTargets() <= target.getTargets().size() && (!outcome.isGood() || target.getMaxNumberOfTargets() <= target.getTargets().size())) { return true; @@ -567,19 +565,18 @@ public class ComputerPlayer extends PlayerImpl implements Player { List targets; boolean outcomeTargets = true; if (outcome.isGood()) { - targets = threats(abilityControllerId, source == null?null:source.getSourceId(), ((TargetPermanent)target).getFilter(), game, target.getTargets()); + targets = threats(abilityControllerId, source == null ? null : source.getSourceId(), ((TargetPermanent) target).getFilter(), game, target.getTargets()); + } else { + targets = threats(opponentId, source == null ? null : source.getSourceId(), ((TargetPermanent) target).getFilter(), game, target.getTargets()); } - else { - targets = threats(opponentId, source == null?null:source.getSourceId(), ((TargetPermanent)target).getFilter(), game, target.getTargets()); - } if (targets.isEmpty() && target.isRequired(source)) { - targets = threats(null, source == null?null:source.getSourceId(), ((TargetPermanent)target).getFilter(), game, target.getTargets()); + targets = threats(null, source == null ? null : source.getSourceId(), ((TargetPermanent) target).getFilter(), game, target.getTargets()); Collections.reverse(targets); outcomeTargets = false; //targets = game.getBattlefield().getActivePermanents(((TargetPermanent)target).getFilter(), playerId, game); } - for (Permanent permanent: targets) { - if (((TargetPermanent)target).canTarget(abilityControllerId, permanent.getId(), source, game)) { + for (Permanent permanent : targets) { + if (((TargetPermanent) target).canTarget(abilityControllerId, permanent.getId(), source, game)) { target.addTarget(permanent.getId(), source, game); if (!outcomeTargets || target.getMaxNumberOfTargets() <= target.getTargets().size()) { return true; @@ -590,12 +587,11 @@ public class ComputerPlayer extends PlayerImpl implements Player { } if (target instanceof TargetCreatureOrPlayer) { List targets; - TargetCreatureOrPlayer t = ((TargetCreatureOrPlayer)target); + TargetCreatureOrPlayer t = ((TargetCreatureOrPlayer) target); if (outcome.isGood()) { - targets = threats(abilityControllerId, source.getSourceId(), ((FilterCreatureOrPlayer)t.getFilter()).getCreatureFilter(), game, target.getTargets()); - } - else { - targets = threats(opponentId, source.getSourceId(), ((FilterCreatureOrPlayer)t.getFilter()).getCreatureFilter(), game, target.getTargets()); + targets = threats(abilityControllerId, source.getSourceId(), ((FilterCreatureOrPlayer) t.getFilter()).getCreatureFilter(), game, target.getTargets()); + } else { + targets = threats(opponentId, source.getSourceId(), ((FilterCreatureOrPlayer) t.getFilter()).getCreatureFilter(), game, target.getTargets()); } if (targets.isEmpty()) { @@ -604,8 +600,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { target.addTarget(abilityControllerId, source, game); return true; } - } - else { + } else { if (target.canTarget(getId(), opponentId, source, game)) { target.addTarget(opponentId, source, game); return true; @@ -614,7 +609,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } if (targets.isEmpty() && target.isRequired(source)) { - targets = game.getBattlefield().getActivePermanents(((FilterCreatureOrPlayer)t.getFilter()).getCreatureFilter(), playerId, game); + targets = game.getBattlefield().getActivePermanents(((FilterCreatureOrPlayer) t.getFilter()).getCreatureFilter(), playerId, game); } for (Permanent permanent : targets) { List alreadyTargetted = target.getTargets(); @@ -627,24 +622,23 @@ public class ComputerPlayer extends PlayerImpl implements Player { } if (outcome.isGood()) { - if (target.canTarget(getId(),abilityControllerId, source, game)) { + if (target.canTarget(getId(), abilityControllerId, source, game)) { target.addTarget(abilityControllerId, source, game); return true; } - } - else { - if (target.canTarget(getId(),opponentId, source, game)) { + } else { + if (target.canTarget(getId(), opponentId, source, game)) { target.addTarget(opponentId, source, game); return true; } } //if (!target.isRequired()) - return false; + return false; } if (target instanceof TargetCardInGraveyard) { List cards = new ArrayList<>(); - for (Player player: game.getPlayers().values()) { + for (Player player : game.getPlayers().values()) { cards.addAll(player.getGraveyard().getCards(game)); } Card card = pickTarget(cards, outcome, target, source, game); @@ -653,7 +647,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { return true; } //if (!target.isRequired()) - return false; + return false; } if (target instanceof TargetCardInLibrary) { List cards = new ArrayList<>(game.getPlayer(abilityControllerId).getLibrary().getCards(game)); @@ -666,7 +660,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } if (target instanceof TargetCardInYourGraveyard) { List cards = new ArrayList<>(game.getPlayer(abilityControllerId).getGraveyard().getCards(game)); - while(!target.isChosen() && !cards.isEmpty()) { + while (!target.isChosen() && !cards.isEmpty()) { Card card = pickTarget(cards, outcome, target, source, game); if (card != null) { target.addTarget(card.getId(), source, game); @@ -677,7 +671,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { if (target instanceof TargetCardInHand) { List cards = new ArrayList<>(); cards.addAll(this.hand.getCards(game)); - while(!target.isChosen() && !cards.isEmpty()) { + while (!target.isChosen() && !cards.isEmpty()) { Card pick = pickTarget(cards, outcome, target, source, game); if (pick != null) { target.addTarget(pick.getId(), source, game); @@ -697,36 +691,35 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } return false; - } + } if (target instanceof TargetSpellOrPermanent) { List targets; boolean outcomeTargets = true; if (outcome.isGood()) { - targets = threats(abilityControllerId, source == null?null:source.getSourceId(), ((TargetSpellOrPermanent)target).getPermanentFilter(), game, target.getTargets()); + targets = threats(abilityControllerId, source == null ? null : source.getSourceId(), ((TargetSpellOrPermanent) target).getPermanentFilter(), game, target.getTargets()); + } else { + targets = threats(opponentId, source == null ? null : source.getSourceId(), ((TargetSpellOrPermanent) target).getPermanentFilter(), game, target.getTargets()); } - else { - targets = threats(opponentId, source == null?null:source.getSourceId(), ((TargetSpellOrPermanent)target).getPermanentFilter(), game, target.getTargets()); - } if (targets.isEmpty() && target.isRequired(source)) { - targets = threats(null, source == null?null:source.getSourceId(), ((TargetSpellOrPermanent)target).getPermanentFilter(), game, target.getTargets()); + targets = threats(null, source == null ? null : source.getSourceId(), ((TargetSpellOrPermanent) target).getPermanentFilter(), game, target.getTargets()); Collections.reverse(targets); outcomeTargets = false; //targets = game.getBattlefield().getActivePermanents(((TargetPermanent)target).getFilter(), playerId, game); } - for (Permanent permanent: targets) { - if (((TargetPermanent)target).canTarget(abilityControllerId, permanent.getId(), source, game)) { + for (Permanent permanent : targets) { + if (((TargetPermanent) target).canTarget(abilityControllerId, permanent.getId(), source, game)) { target.addTarget(permanent.getId(), source, game); if (!outcomeTargets || target.getMaxNumberOfTargets() <= target.getTargets().size()) { return true; } } - } + } if (game.getStack().size() > 0) { Iterator it = game.getStack().iterator(); while (it.hasNext()) { StackObject stackObject = it.next(); if (stackObject instanceof Spell && source != null && !source.getId().equals(stackObject.getStackAbility().getId())) { - if (((TargetSpellOrPermanent)target).getFilter().match(stackObject, game)) { + if (((TargetSpellOrPermanent) target).getFilter().match(stackObject, game)) { target.addTarget(stackObject.getId(), source, game); return true; } @@ -737,7 +730,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } if (target instanceof TargetCardInOpponentsGraveyard) { List cards = new ArrayList<>(); - for (UUID uuid: game.getOpponents(abilityControllerId)) { + for (UUID uuid : game.getOpponents(abilityControllerId)) { Player player = game.getPlayer(uuid); if (player != null) { cards.addAll(player.getGraveyard().getCards(game)); @@ -749,15 +742,15 @@ public class ComputerPlayer extends PlayerImpl implements Player { return true; } //if (!target.isRequired()) - return false; + return false; } if (target instanceof TargetDefender) { // TODO: Improve, now planeswalker is always chosen if it exits - List targets ; + List targets; targets = game.getBattlefield().getActivePermanents(new FilterPlaneswalkerPermanent(), opponentId, game); if (targets != null && !targets.isEmpty()) { - for (Permanent planeswalker: targets) { - if (target.canTarget(getId(),planeswalker.getId(), source, game)) { + for (Permanent planeswalker : targets) { + if (target.canTarget(getId(), planeswalker.getId(), source, game)) { target.addTarget(planeswalker.getId(), source, game); } if (target.isChosen()) { @@ -766,7 +759,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } if (!target.isChosen()) { - if (target.canTarget(getId() ,opponentId, source, game)) { + if (target.canTarget(getId(), opponentId, source, game)) { target.addTarget(opponentId, source, game); } } @@ -775,10 +768,10 @@ public class ComputerPlayer extends PlayerImpl implements Player { if (target instanceof TargetCardInASingleGraveyard) { List cards = new ArrayList<>(); - for (Player player: game.getPlayers().values()) { + for (Player player : game.getPlayers().values()) { cards.addAll(player.getGraveyard().getCards(game)); } - while(!target.isChosen() && !cards.isEmpty()) { + while (!target.isChosen() && !cards.isEmpty()) { Card pick = pickTarget(cards, outcome, target, source, game); if (pick != null) { target.addTarget(pick.getId(), source, game); @@ -789,13 +782,13 @@ public class ComputerPlayer extends PlayerImpl implements Player { if (target instanceof TargetCardInExile) { List cards = new ArrayList<>(); - for (UUID uuid: ((TargetCardInExile) target).possibleTargets(source.getSourceId(), source.getControllerId(), game)) { + for (UUID uuid : ((TargetCardInExile) target).possibleTargets(source.getSourceId(), source.getControllerId(), game)) { Card card = game.getCard(uuid); if (card != null) { cards.add(card); } } - while(!target.isChosen() && !cards.isEmpty()) { + while (!target.isChosen() && !cards.isEmpty()) { Card pick = pickTarget(cards, outcome, target, source, game); if (pick != null) { target.addTarget(pick.getId(), source, game); @@ -804,7 +797,6 @@ public class ComputerPlayer extends PlayerImpl implements Player { return target.isChosen(); } - throw new IllegalStateException("Target wasn't handled. class:" + target.getClass().toString()); } @@ -813,16 +805,14 @@ public class ComputerPlayer extends PlayerImpl implements Player { while (!cards.isEmpty()) { if (outcome.isGood()) { card = pickBestCard(cards, null, target, source, game); - } - else { + } else { card = pickWorstCard(cards, null, target, source, game); } if (source != null) { if (target.canTarget(getId(), card.getId(), source, game)) { return card; } - } - else { + } else { return card; } cards.remove(card); @@ -844,12 +834,11 @@ public class ComputerPlayer extends PlayerImpl implements Player { List targets; if (outcome.isGood()) { targets = threats(playerId, source.getSourceId(), new FilterCreaturePermanent(), game, target.getTargets()); - } - else { + } else { targets = threats(opponentId, source.getSourceId(), new FilterCreaturePermanent(), game, target.getTargets()); } - for (Permanent permanent: targets) { - if (target.canTarget(getId() ,permanent.getId(), source, game)) { + for (Permanent permanent : targets) { + if (target.canTarget(getId(), permanent.getId(), source, game)) { if (permanent.getToughness().getValue() <= target.getAmountRemaining()) { target.addTarget(permanent.getId(), permanent.getToughness().getValue(), source, game); return true; @@ -859,7 +848,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { if (outcome.isGood() && target.canTarget(getId(), getId(), source, game)) { target.addTarget(opponentId, target.getAmountRemaining(), source, game); return true; - } else if (target.canTarget(getId(), opponentId, source, game)){ + } else if (target.canTarget(getId(), opponentId, source, game)) { // no permanent target so take opponent target.addTarget(opponentId, target.getAmountRemaining(), source, game); return true; @@ -896,7 +885,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { case PRECOMBAT_MAIN: findPlayables(game); if (playableAbilities.size() > 0) { - for (ActivatedAbility ability: playableAbilities) { + for (ActivatedAbility ability : playableAbilities) { if (ability.canActivate(playerId, game)) { if (ability.getEffects().hasOutcome(Outcome.PutLandInPlay)) { if (this.activateAbility(ability, game)) { @@ -927,7 +916,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { findPlayables(game); if (game.getStack().isEmpty()) { if (playableNonInstant.size() > 0) { - for (Card card: playableNonInstant) { + for (Card card : playableNonInstant) { if (card.getSpellAbility().canActivate(playerId, game)) { if (this.activateAbility(card.getSpellAbility(), game)) { return true; @@ -936,7 +925,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } if (playableAbilities.size() > 0) { - for (ActivatedAbility ability: playableAbilities) { + for (ActivatedAbility ability : playableAbilities) { if (ability.canActivate(playerId, game)) { if (!(ability.getEffects().get(0) instanceof BecomesCreatureSourceEffect)) { if (this.activateAbility(ability, game)) { @@ -949,8 +938,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } break; } - } - else { + } else { //respond to opponent events switch (game.getTurn().getStepType()) { case UPKEEP: @@ -967,15 +955,15 @@ public class ComputerPlayer extends PlayerImpl implements Player { break; } } - pass(game); + pass(game); return true; } @Override public boolean activateAbility(ActivatedAbility ability, Game game) { if (!isTestMode()) { // Test player already sends target event as he selects the target - for (Target target: ability.getModes().getMode().getTargets()) { - for (UUID targetId: target.getTargets()) { + for (Target target : ability.getModes().getMode().getTargets()) { + for (UUID targetId : target.getTargets()) { game.fireEvent(GameEvent.getEvent(EventType.TARGETED, targetId, ability.getId(), ability.getControllerId())); } } @@ -986,7 +974,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { protected void playLand(Game game) { log.debug("playLand"); Set lands = new LinkedHashSet<>(); - for (Card landCard: hand.getCards(new FilterLandCard(), game)) { + for (Card landCard : hand.getCards(new FilterLandCard(), game)) { // remove lands that can not be played if (game.getContinuousEffects().preventedByRuleModification(GameEvent.getEvent(GameEvent.EventType.PLAY_LAND, landCard.getId(), landCard.getId(), playerId), null, game, true)) { break; @@ -996,8 +984,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { while (lands.size() > 0 && this.canPlayLand()) { if (lands.size() == 1) { this.playLand(lands.iterator().next(), game); - } - else { + } else { playALand(lands, game); } } @@ -1006,10 +993,10 @@ public class ComputerPlayer extends PlayerImpl implements Player { protected void playALand(Set lands, Game game) { log.debug("playALand"); //play a land that will allow us to play an unplayable - for (Mana mana: unplayable.keySet()) { - for (Card card: lands) { - for (ManaAbility ability: card.getAbilities().getManaAbilities(Zone.BATTLEFIELD)) { - for (Mana netMana: ability.getNetMana(game)) { + for (Mana mana : unplayable.keySet()) { + for (Card card : lands) { + for (ManaAbility ability : card.getAbilities().getManaAbilities(Zone.BATTLEFIELD)) { + for (Mana netMana : ability.getNetMana(game)) { if (netMana.enough(mana)) { this.playLand(card, game); lands.remove(card); @@ -1020,10 +1007,10 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } //play a land that will get us closer to playing an unplayable - for (Mana mana: unplayable.keySet()) { - for (Card card: lands) { - for (ManaAbility ability: card.getAbilities().getManaAbilities(Zone.BATTLEFIELD)) { - for (Mana netMana: ability.getNetMana(game)) { + for (Mana mana : unplayable.keySet()) { + for (Card card : lands) { + for (ManaAbility ability : card.getAbilities().getManaAbilities(Zone.BATTLEFIELD)) { + for (Mana netMana : ability.getNetMana(game)) { if (mana.contains(netMana)) { this.playLand(card, game); lands.remove(card); @@ -1047,30 +1034,28 @@ public class ComputerPlayer extends PlayerImpl implements Player { ManaOptions available = getManaAvailable(game); available.addMana(manaPool.getMana()); - for (Card card: nonLands) { + for (Card card : nonLands) { ManaOptions options = card.getManaCost().getOptions(); if (card.getManaCost().getVariableCosts().size() > 0) { //don't use variable mana costs unless there is at least 3 extra mana for X - for (Mana option: options) { + for (Mana option : options) { option.add(Mana.ColorlessMana(3)); } } - for (Mana mana: options) { - for (Mana avail: available) { + for (Mana mana : options) { + for (Mana avail : available) { if (mana.enough(avail)) { SpellAbility ability = card.getSpellAbility(); - if (ability != null && ability.canActivate(playerId, game) && - game.getContinuousEffects().preventedByRuleModification(GameEvent.getEvent(GameEvent.EventType.CAST_SPELL, ability.getSourceId(), ability.getSourceId(), playerId), ability, game, true)) { + if (ability != null && ability.canActivate(playerId, game) + && game.getContinuousEffects().preventedByRuleModification(GameEvent.getEvent(GameEvent.EventType.CAST_SPELL, ability.getSourceId(), ability.getSourceId(), playerId), ability, game, true)) { if (card.getCardType().contains(CardType.INSTANT) || card.hasAbility(FlashAbility.getInstance().getId(), game)) { playableInstant.add(card); - } - else { + } else { playableNonInstant.add(card); } } - } - else { + } else { if (!playableInstant.contains(card) && !playableNonInstant.contains(card)) { unplayable.put(mana.needed(avail), card); } @@ -1078,8 +1063,8 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } } - for (Permanent permanent: game.getBattlefield().getAllActivePermanents(playerId)) { - for (ActivatedAbility ability: permanent.getAbilities().getActivatedAbilities(Zone.BATTLEFIELD)) { + for (Permanent permanent : game.getBattlefield().getAllActivePermanents(playerId)) { + for (ActivatedAbility ability : permanent.getAbilities().getActivatedAbilities(Zone.BATTLEFIELD)) { if (!(ability instanceof ManaAbility) && ability.canActivate(playerId, game)) { if (ability instanceof EquipAbility && permanent.getAttachedTo() != null) { continue; @@ -1087,16 +1072,15 @@ public class ComputerPlayer extends PlayerImpl implements Player { ManaOptions abilityOptions = ability.getManaCosts().getOptions(); if (ability.getManaCosts().getVariableCosts().size() > 0) { //don't use variable mana costs unless there is at least 3 extra mana for X - for (Mana option: abilityOptions) { + for (Mana option : abilityOptions) { option.add(Mana.ColorlessMana(3)); } } if (abilityOptions.size() == 0) { playableAbilities.add(ability); - } - else { - for (Mana mana: abilityOptions) { - for (Mana avail: available) { + } else { + for (Mana mana : abilityOptions) { + for (Mana avail : available) { if (mana.enough(avail)) { playableAbilities.add(ability); } @@ -1106,16 +1090,15 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } } - for (Card card: graveyard.getCards(game)) { - for (ActivatedAbility ability: card.getAbilities().getActivatedAbilities(Zone.GRAVEYARD)) { + for (Card card : graveyard.getCards(game)) { + for (ActivatedAbility ability : card.getAbilities().getActivatedAbilities(Zone.GRAVEYARD)) { if (ability.canActivate(playerId, game)) { ManaOptions abilityOptions = ability.getManaCosts().getOptions(); if (abilityOptions.size() == 0) { playableAbilities.add(ability); - } - else { - for (Mana mana: abilityOptions) { - for (Mana avail: available) { + } else { + for (Mana mana : abilityOptions) { + for (Mana avail : available) { if (mana.enough(avail)) { playableAbilities.add(ability); } @@ -1126,16 +1109,16 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } if (log.isDebugEnabled()) { - log.debug("findPlayables: " + playableInstant.toString() + "---" + playableNonInstant.toString() + "---" + playableAbilities.toString() ); + log.debug("findPlayables: " + playableInstant.toString() + "---" + playableNonInstant.toString() + "---" + playableAbilities.toString()); } } - + @Override public boolean playMana(ManaCost unpaid, String promptText, Game game) { payManaMode = true; - currentUnpaidMana = unpaid; + currentUnpaidMana = unpaid; boolean result = playManaHandling(unpaid, game); - currentUnpaidMana = null; + currentUnpaidMana = null; payManaMode = false; return result; } @@ -1145,19 +1128,18 @@ public class ComputerPlayer extends PlayerImpl implements Player { ManaCost cost; List producers; if (unpaid instanceof ManaCosts) { - cost = ((ManaCosts)unpaid).get(0); - producers = getSortedProducers((ManaCosts)unpaid, game); - } - else { + cost = ((ManaCosts) unpaid).get(0); + producers = getSortedProducers((ManaCosts) unpaid, game); + } else { cost = unpaid; producers = this.getAvailableManaProducers(game); producers.addAll(this.getAvailableManaProducersWithCost(game)); } - for (Permanent perm: producers) { + for (Permanent perm : producers) { // pay all colored costs first - for (ManaAbility ability: perm.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { + for (ManaAbility ability : perm.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { if (cost instanceof ColoredManaCost) { - for (Mana netMana: ability.getNetMana(game)) { + for (Mana netMana : ability.getNetMana(game)) { if (cost.testPay(netMana)) { if (activateAbility(ability, game)) { return true; @@ -1167,9 +1149,9 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } // then pay hybrid - for (ManaAbility ability: perm.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { + for (ManaAbility ability : perm.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { if (cost instanceof HybridManaCost) { - for (Mana netMana: ability.getNetMana(game)) { + for (Mana netMana : ability.getNetMana(game)) { if (cost.testPay(netMana)) { if (activateAbility(ability, game)) { return true; @@ -1179,9 +1161,9 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } // then pay mono hybrid - for (ManaAbility ability: perm.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { + for (ManaAbility ability : perm.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { if (cost instanceof MonoHybridManaCost) { - for (Mana netMana: ability.getNetMana(game)) { + for (Mana netMana : ability.getNetMana(game)) { if (cost.testPay(netMana)) { if (activateAbility(ability, game)) { return true; @@ -1191,9 +1173,9 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } // finally pay generic - for (ManaAbility ability: perm.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { + for (ManaAbility ability : perm.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { if (cost instanceof GenericManaCost) { - for (Mana netMana: ability.getNetMana(game)) { + for (Mana netMana : ability.getNetMana(game)) { if (cost.testPay(netMana)) { if (activateAbility(ability, game)) { return true; @@ -1214,11 +1196,13 @@ public class ComputerPlayer extends PlayerImpl implements Player { /** * - * returns a list of Permanents that produce mana sorted by the number of mana the Permanent produces - * that match the unpaid costs in ascending order + * returns a list of Permanents that produce mana sorted by the number of + * mana the Permanent produces that match the unpaid costs in ascending + * order * - * the idea is that we should pay costs first from mana producers that produce only one type of mana - * and save the multi-mana producers for those costs that can't be paid by any other producers + * the idea is that we should pay costs first from mana producers that + * produce only one type of mana and save the multi-mana producers for those + * costs that can't be paid by any other producers * * @param unpaid - the amount of unpaid mana costs * @param game @@ -1228,12 +1212,12 @@ public class ComputerPlayer extends PlayerImpl implements Player { List unsorted = this.getAvailableManaProducers(game); unsorted.addAll(this.getAvailableManaProducersWithCost(game)); Map scored = new HashMap<>(); - for (Permanent permanent: unsorted) { + for (Permanent permanent : unsorted) { int score = 0; - for (ManaCost cost: unpaid) { + for (ManaCost cost : unpaid) { Abilities: - for (ManaAbility ability: permanent.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { - for (Mana netMana: ability.getNetMana(game)) { + for (ManaAbility ability : permanent.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game)) { + for (Mana netMana : ability.getNetMana(game)) { if (cost.testPay(netMana)) { score++; break Abilities; @@ -1245,10 +1229,9 @@ public class ComputerPlayer extends PlayerImpl implements Player { score += permanent.getAbilities().getAvailableManaAbilities(Zone.BATTLEFIELD, game).size(); score += permanent.getAbilities().getActivatedAbilities(Zone.BATTLEFIELD).size(); if (!permanent.getCardType().contains(CardType.LAND)) { - score+=2; - } - else if(permanent.getCardType().contains(CardType.CREATURE)) { - score+=2; + score += 2; + } else if (permanent.getCardType().contains(CardType.CREATURE)) { + score += 2; } } scored.put(permanent, score); @@ -1286,14 +1269,13 @@ public class ComputerPlayer extends PlayerImpl implements Player { public int announceXCost(int min, int max, String message, Game game, Ability ability, VariableCost variablCost) { log.debug("announceXMana"); //TODO: improve this - int value = new Random().nextInt(max+1); + int value = new Random().nextInt(max + 1); if (value < max) { value++; } return value; } - @Override public void abort() { abort = true; @@ -1320,7 +1302,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { chooseCreatureType(outcome, choice, game); } // choose the correct color to pay a spell - if(outcome.equals(Outcome.PutManaInPool) && choice instanceof ChoiceColor && currentUnpaidMana != null) { + if (outcome.equals(Outcome.PutManaInPool) && choice instanceof ChoiceColor && currentUnpaidMana != null) { if (currentUnpaidMana.containsColor(ColoredManaSymbol.W) && choice.getChoices().contains("White")) { choice.setChoice("White"); return true; @@ -1344,7 +1326,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } // choose by random if (!choice.isChosen()) { - int choiceIdx = (int) (Math.random()*choice.getChoices().size()+1); + int choiceIdx = (int) (Math.random() * choice.getChoices().size() + 1); for (String next : choice.getChoices()) { if (--choiceIdx > 0) { continue; @@ -1361,8 +1343,8 @@ public class ComputerPlayer extends PlayerImpl implements Player { protected boolean chooseCreatureType(Outcome outcome, Choice choice, Game game) { if (outcome.equals(Outcome.Detriment)) { // choose a creature type of opponent on battlefield or graveyard - for (Permanent permanent :game.getBattlefield().getActivePermanents(this.getId(), game)) { - if(game.getOpponents(this.getId()).contains(permanent.getControllerId()) + for (Permanent permanent : game.getBattlefield().getActivePermanents(this.getId(), game)) { + if (game.getOpponents(this.getId()).contains(permanent.getControllerId()) && permanent.getCardType().contains(CardType.CREATURE) && permanent.getSubtype().size() > 0) { if (choice.getChoices().contains(permanent.getSubtype().get(0))) { @@ -1373,7 +1355,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } // or in opponent graveyard if (!choice.isChosen()) { - for (UUID opponentId :game.getOpponents(this.getId())) { + for (UUID opponentId : game.getOpponents(this.getId())) { Player opponent = game.getPlayer(opponentId); for (Card card : opponent.getGraveyard().getCards(game)) { if (card != null && card.getCardType().contains(CardType.CREATURE) && card.getSubtype().size() > 0) { @@ -1390,7 +1372,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } else { // choose a creature type of hand or library - for (UUID cardId :this.getHand()) { + for (UUID cardId : this.getHand()) { Card card = game.getCard(cardId); if (card != null && card.getCardType().contains(CardType.CREATURE) && card.getSubtype().size() > 0) { if (choice.getChoices().contains(card.getSubtype().get(0))) { @@ -1413,8 +1395,9 @@ public class ComputerPlayer extends PlayerImpl implements Player { } return choice.isChosen(); } + @Override - public boolean chooseTarget(Outcome outcome, Cards cards, TargetCard target, Ability source, Game game) { + public boolean chooseTarget(Outcome outcome, Cards cards, TargetCard target, Ability source, Game game) { log.debug("chooseTarget"); if (cards == null || cards.isEmpty()) { return target.isRequired(source); @@ -1438,7 +1421,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } @Override - public boolean choose(Outcome outcome, Cards cards, TargetCard target, Game game) { + public boolean choose(Outcome outcome, Cards cards, TargetCard target, Game game) { log.debug("choose 2"); if (cards == null || cards.isEmpty()) { return true; @@ -1476,19 +1459,17 @@ public class ComputerPlayer extends PlayerImpl implements Player { List actualAttackers = new ArrayList<>(); if (blockers.isEmpty()) { actualAttackers = attackers.getAttackers(); - } - else if (attackers.size() - blockers.size() >= game.getPlayer(opponentId).getLife()) { + } else if (attackers.size() - blockers.size() >= game.getPlayer(opponentId).getLife()) { actualAttackers = attackers.getAttackers(); - } - else { + } else { CombatSimulator combat = simulateAttack(attackers, blockers, opponentId, game); if (combat.rating > 2) { - for (CombatGroupSimulator group: combat.groups) { + for (CombatGroupSimulator group : combat.groups) { this.declareAttacker(group.attackers.get(0).id, group.defenderId, game, false); } } } - for (Permanent attacker: actualAttackers) { + for (Permanent attacker : actualAttackers) { this.declareAttacker(attacker.getId(), opponentId, game, false); } } @@ -1502,8 +1483,8 @@ public class ComputerPlayer extends PlayerImpl implements Player { CombatSimulator sim = simulateBlock(CombatSimulator.load(game), blockers, game); List groups = game.getCombat().getGroups(); - for (int i = 0; i< groups.size(); i++) { - for (CreatureSimulator creature: sim.groups.get(i).blockers) { + for (int i = 0; i < groups.size(); i++) { + for (CreatureSimulator creature : sim.groups.get(i).blockers) { groups.get(i).addBlocker(creature.id, playerId, game); } } @@ -1518,7 +1499,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { @Override public SpellAbility chooseSpellAbilityForCast(SpellAbility ability, Game game, boolean noMana) { - switch(ability.getSpellAbilityType()) { + switch (ability.getSpellAbilityType()) { case SPLIT: case SPLIT_FUSED: MageObject object = game.getObject(ability.getSourceId()); @@ -1544,7 +1525,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { return modes.getMode(); } //TODO: improve this; - for (Mode mode: modes.values()) { + for (Mode mode : modes.values()) { if (!modes.getSelectedModes().contains(mode.getId()) // select only modes not already selected && mode.getTargets().canChoose(source.getSourceId(), source.getControllerId(), game)) { // and where targets are available return mode; @@ -1578,7 +1559,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } //TODO: improve this if (min < max && min == 0) { - return new Random().nextInt(max+1); + return new Random().nextInt(max + 1); } return min; } @@ -1590,7 +1571,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } @Override - public UUID chooseBlockerOrder(List blockers, CombatGroup combatGroup, List blockerOrder, Game game) { + public UUID chooseBlockerOrder(List blockers, CombatGroup combatGroup, List blockerOrder, Game game) { //TODO: improve this return blockers.iterator().next().getId(); } @@ -1608,10 +1589,10 @@ public class ComputerPlayer extends PlayerImpl implements Player { private static void addBasicLands(Deck deck, String landName, int number) { Random random = new Random(); - Set landSets = new HashSet<>(); + Set landSets = new HashSet<>(); // decide from which sets basic lands are taken from - for (String setCode :deck.getExpansionSetCodes()) { + for (String setCode : deck.getExpansionSetCodes()) { ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode); if (expansionInfo.hasBasicLands()) { landSets.add(expansionInfo.getCode()); @@ -1620,10 +1601,10 @@ public class ComputerPlayer extends PlayerImpl implements Player { // if sets have no basic land, take land from block if (landSets.isEmpty()) { - for (String setCode :deck.getExpansionSetCodes()) { + for (String setCode : deck.getExpansionSetCodes()) { ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode); List blockSets = ExpansionRepository.instance.getSetsFromBlock(expansionInfo.getBlockName()); - for (ExpansionInfo blockSet: blockSets) { + for (ExpansionInfo blockSet : blockSets) { if (blockSet.hasBasicLands()) { landSets.add(blockSet.getCode()); } @@ -1653,7 +1634,10 @@ public class ComputerPlayer extends PlayerImpl implements Player { List cards = CardRepository.instance.findCards(criteria); if (cards.isEmpty()) { - return; + criteria = new CardCriteria(); + criteria.rarities(Rarity.LAND).name(landName); + criteria.setCodes("M15"); + cards = CardRepository.instance.findCards(criteria); } for (int i = 0; i < number; i++) { @@ -1685,7 +1669,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { // add basic lands // TODO: compensate for non basic lands Mana mana = new Mana(); - for (Card card: deck.getCards()) { + for (Card card : deck.getCards()) { mana.add(card.getManaCost().getMana()); } double total = mana.getBlack() + mana.getBlue() + mana.getGreen() + mana.getRed() + mana.getWhite(); @@ -1735,10 +1719,10 @@ public class ComputerPlayer extends PlayerImpl implements Player { @Override public void construct(Tournament tournament, Deck deck) { - if (deck != null && deck.getCards().size() < 40 && deck.getSideboard().size() > 0 ) { + if (deck != null && deck.getCards().size() < 40 && deck.getSideboard().size() > 0) { //pick the top 23 cards if (chosenColors == null) { - for (Card card: deck.getSideboard()) { + for (Card card : deck.getSideboard()) { rememberPick(card, RateCard.rateCard(card, null)); } chosenColors = chooseDeckColorsIfPossible(); @@ -1857,11 +1841,10 @@ public class ComputerPlayer extends PlayerImpl implements Player { // take it! if (counterPickScore >= 8) { bestCard = counterPick; - maxScore = RateCard.rateCard(bestCard, chosenColors); + maxScore = RateCard.rateCard(bestCard, chosenColors); } } - String colors = "not chosen yet"; // remember card if colors are not chosen yet if (chosenColors == null) { @@ -1877,7 +1860,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { log.debug("[DEBUG] AI picked: " + bestCard.getName() + ", score=" + maxScore + ", deck colors=" + colors); draft.addPick(playerId, bestCard.getId(), null); } catch (Exception e) { - log.debug("Exception during AI pick card for draft playerId= " +getId()); + log.debug("Exception during AI pick card for draft playerId= " + getId()); draft.addPick(playerId, cards.get(0).getId(), null); } } @@ -1893,11 +1876,11 @@ public class ComputerPlayer extends PlayerImpl implements Player { } /** - * Choose 2 deck colors for draft: - * 1. there should be at least 3 cards in card pool - * 2. at least 2 cards should have different colors - * 3. get card colors as chosen starting from most rated card - * @return + * Choose 2 deck colors for draft: 1. there should be at least 3 cards in + * card pool 2. at least 2 cards should have different colors 3. get card + * colors as chosen starting from most rated card + * + * @return */ protected List chooseDeckColorsIfPossible() { if (pickedCards.size() > 2) { @@ -1929,7 +1912,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } // only two or three color decks are allowed - if (chosenSymbols.size() > 1 && chosenSymbols.size() < 4) { + if (chosenSymbols.size() > 1 && chosenSymbols.size() < 4) { List colorsChosen = new ArrayList<>(); for (String symbol : chosenSymbols) { ColoredManaSymbol manaSymbol = ColoredManaSymbol.lookup(symbol.charAt(0)); @@ -1949,10 +1932,13 @@ public class ComputerPlayer extends PlayerImpl implements Player { } private class PickedCard { + public Card card; public Integer score; + public PickedCard(Card card, int score) { - this.card = card; this.score = score; + this.card = card; + this.score = score; } } @@ -1960,7 +1946,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { log.debug("getAvailableAttackers"); Attackers attackers = new Attackers(); List creatures = super.getAvailableAttackers(game); - for (Permanent creature: creatures) { + for (Permanent creature : creatures) { int potential = combatPotential(creature, game); if (potential > 0 && creature.getPower().getValue() > 0) { List l = attackers.get(potential); @@ -1969,7 +1955,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } l.add(creature); } - } + } return attackers; } @@ -1981,9 +1967,9 @@ public class ComputerPlayer extends PlayerImpl implements Player { int potential = creature.getPower().getValue(); potential += creature.getAbilities().getEvasionAbilities().size(); potential += creature.getAbilities().getProtectionAbilities().size(); - potential += creature.getAbilities().containsKey(FirstStrikeAbility.getInstance().getId())?1:0; - potential += creature.getAbilities().containsKey(DoubleStrikeAbility.getInstance().getId())?2:0; - potential += creature.getAbilities().containsKey(TrampleAbility.getInstance().getId())?1:0; + potential += creature.getAbilities().containsKey(FirstStrikeAbility.getInstance().getId()) ? 1 : 0; + potential += creature.getAbilities().containsKey(DoubleStrikeAbility.getInstance().getId()) ? 2 : 0; + potential += creature.getAbilities().containsKey(TrampleAbility.getInstance().getId()) ? 1 : 0; return potential; } @@ -2002,7 +1988,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { int powerElements = (int) Math.pow(2, attackersList.size()); for (int i = 1; i < powerElements; i++) { String binary = Integer.toBinaryString(i); - while(binary.length() < attackersList.size()) { + while (binary.length() < attackersList.size()) { binary = "0" + binary; } List trialAttackers = new ArrayList<>(); @@ -2012,7 +1998,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { } } CombatSimulator combat = new CombatSimulator(); - for (Permanent permanent: trialAttackers) { + for (Permanent permanent : trialAttackers) { combat.groups.add(new CombatGroupSimulator(opponentId, Arrays.asList(permanent.getId()), new ArrayList(), game)); } CombatSimulator test = simulateBlock(combat, blockers, game); @@ -2041,7 +2027,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { protected void addBlockSimulations(List blockers, TreeNode node, Game game) { int numGroups = node.getData().groups.size(); Copier copier = new Copier<>(); - for (Permanent blocker: blockers) { + for (Permanent blocker : blockers) { List subList = remove(blockers, blocker); for (int i = 0; i < numGroups; i++) { if (node.getData().groups.get(i).canBlock(blocker, game)) { @@ -2058,7 +2044,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { protected List remove(List source, Permanent element) { List newList = new ArrayList<>(); - for (Permanent permanent: source) { + for (Permanent permanent : source) { if (!permanent.equals(element)) { newList.add(permanent); } @@ -2069,7 +2055,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { protected CombatSimulator getBestSimulation(TreeNode simulations) { CombatSimulator best = simulations.getData(); int bestResult = best.evaluate(); - for (TreeNode node: simulations.getChildren()) { + for (TreeNode node : simulations.getChildren()) { CombatSimulator bestSub = getBestSimulation(node); if (bestSub.evaluate() > bestResult) { best = node.getData(); @@ -2082,7 +2068,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { protected CombatSimulator getWorstSimulation(TreeNode simulations) { CombatSimulator worst = simulations.getData(); int worstResult = worst.evaluate(); - for (TreeNode node: simulations.getChildren()) { + for (TreeNode node : simulations.getChildren()) { CombatSimulator worstSub = getWorstSimulation(node); if (worstSub.evaluate() < worstResult) { worst = node.getData(); @@ -2100,7 +2086,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { FilterPermanent filterCopy = filter.copy(); filterCopy.add(new ControllerIdPredicate(playerId)); threats = game.getBattlefield().getActivePermanents(filter, this.getId(), sourceId, game); - } + } Iterator it = threats.iterator(); while (it.hasNext()) { // remove permanents already targeted Permanent test = it.next(); @@ -2122,7 +2108,7 @@ public class ComputerPlayer extends PlayerImpl implements Player { protected void logList(String message, List list) { StringBuilder sb = new StringBuilder(); sb.append(message).append(": "); - for (MageObject object: list) { + for (MageObject object : list) { sb.append(object.getName()).append(","); } log.info(sb.toString()); @@ -2131,17 +2117,17 @@ public class ComputerPlayer extends PlayerImpl implements Player { protected void logAbilityList(String message, List list) { StringBuilder sb = new StringBuilder(); sb.append(message).append(": "); - for (Ability ability: list) { + for (Ability ability : list) { sb.append(ability.getRule()).append(","); } log.debug(sb.toString()); } private void playRemoval(List creatures, Game game) { - for (UUID creatureId: creatures) { - for (Card card: this.playableInstant) { + for (UUID creatureId : creatures) { + for (Card card : this.playableInstant) { if (card.getSpellAbility().canActivate(playerId, game)) { - for (Effect effect: card.getSpellAbility().getEffects()) { + for (Effect effect : card.getSpellAbility().getEffects()) { if (effect.getOutcome().equals(Outcome.DestroyPermanent) || effect.getOutcome().equals(Outcome.ReturnToHand)) { if (card.getSpellAbility().getTargets().get(0).canTarget(creatureId, card.getSpellAbility(), game)) { if (this.activateAbility(card.getSpellAbility(), game)) { @@ -2156,14 +2142,14 @@ public class ComputerPlayer extends PlayerImpl implements Player { } private void playDamage(List creatures, Game game) { - for (UUID creatureId: creatures) { + for (UUID creatureId : creatures) { Permanent creature = game.getPermanent(creatureId); - for (Card card: this.playableInstant) { + for (Card card : this.playableInstant) { if (card.getSpellAbility().canActivate(playerId, game)) { - for (Effect effect: card.getSpellAbility().getEffects()) { + for (Effect effect : card.getSpellAbility().getEffects()) { if (effect instanceof DamageTargetEffect) { if (card.getSpellAbility().getTargets().get(0).canTarget(creatureId, card.getSpellAbility(), game)) { - if (((DamageTargetEffect)effect).getAmount() > (creature.getPower().getValue() - creature.getDamage())) { + if (((DamageTargetEffect) effect).getAmount() > (creature.getPower().getValue() - creature.getDamage())) { if (this.activateAbility(card.getSpellAbility(), game)) { return; } @@ -2189,8 +2175,6 @@ public class ComputerPlayer extends PlayerImpl implements Player { super.cleanUpOnMatchEnd(); //To change body of generated methods, choose Tools | Templates. } - - @Override public ComputerPlayer copy() { return new ComputerPlayer(this); diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java index 7ddf83a1530..46c6ce0aadb 100644 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -1,31 +1,30 @@ /* -* 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. -*/ - + * 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.server; import java.util.ArrayList; @@ -52,6 +51,7 @@ import mage.interfaces.ActionWithResult; import mage.interfaces.MageServer; import mage.interfaces.ServerState; import mage.interfaces.callback.ClientCallback; +import mage.players.net.UserData; import mage.remote.MageVersionException; import mage.server.draft.CubeFactory; import mage.server.draft.DraftManager; @@ -83,7 +83,6 @@ import mage.view.MatchView; import mage.view.RoomUsersView; import mage.view.TableView; import mage.view.TournamentView; -import mage.view.UserDataView; import mage.view.UserView; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.log4j.Logger; @@ -117,7 +116,7 @@ public class MageServerImpl implements MageServer { return SessionManager.getInstance().registerUser(sessionId, userName); } catch (MageException ex) { if (ex instanceof MageVersionException) { - throw (MageVersionException)ex; + throw (MageVersionException) ex; } handleException(ex); } @@ -125,11 +124,11 @@ public class MageServerImpl implements MageServer { } @Override - public boolean setUserData(final String userName, final String sessionId, final UserDataView userDataView) throws MageException { + public boolean setUserData(final String userName, final String sessionId, final UserData userData) throws MageException { return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { @Override public Boolean execute() throws MageException { - return SessionManager.getInstance().setUserData(userName, sessionId, userDataView); + return SessionManager.getInstance().setUserData(userName, sessionId, userData); } }); } @@ -162,7 +161,7 @@ public class MageServerImpl implements MageServer { if (user != null) { logger.debug("TABLE created - tableId: " + table.getTableId() + " " + table.getTableName()); logger.debug("- " + user.getName() + " userId: " + user.getId()); - logger.debug("- chatId: " + TableManager.getInstance().getChatId(table.getTableId())); + logger.debug("- chatId: " + TableManager.getInstance().getChatId(table.getTableId())); } } LogServiceImpl.instance.log(LogKeys.KEY_TABLE_CREATED, sessionId, userId.toString(), table.getTableId().toString()); @@ -229,7 +228,7 @@ public class MageServerImpl implements MageServer { if (userId == null) { logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); return false; - } + } boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password); return ret; } @@ -247,11 +246,11 @@ public class MageServerImpl implements MageServer { if (user != null) { logger.trace("join tourn. tableId: " + tableId + " " + name); } - } + } if (userId == null) { logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); return false; - } + } boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password); return ret; } @@ -293,8 +292,7 @@ public class MageServerImpl implements MageServer { } else { return null; } - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -310,8 +308,7 @@ public class MageServerImpl implements MageServer { } else { return null; } - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -326,8 +323,7 @@ public class MageServerImpl implements MageServer { } else { return null; } - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -343,8 +339,7 @@ public class MageServerImpl implements MageServer { } else { return null; } - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -365,7 +360,6 @@ public class MageServerImpl implements MageServer { // } // }); // } - @Override public boolean startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { @@ -391,7 +385,6 @@ public class MageServerImpl implements MageServer { // } // }); // } - @Override public boolean startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { @@ -412,8 +405,7 @@ public class MageServerImpl implements MageServer { public TournamentView getTournament(UUID tournamentId) throws MageException { try { return TournamentManager.getInstance().getTournamentView(tournamentId); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -424,15 +416,14 @@ 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); + new Runnable() { + @Override + public void run() { + ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE); + } } - } ); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } } @@ -464,8 +455,7 @@ public class MageServerImpl implements MageServer { public UUID getMainRoomId() throws MageException { try { return GamesRoomManager.getInstance().getMainRoomId(); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -476,8 +466,7 @@ public class MageServerImpl implements MageServer { public UUID getRoomChatId(UUID roomId) throws MageException { try { return GamesRoomManager.getInstance().getRoom(roomId).getChatId(); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -527,8 +516,7 @@ public class MageServerImpl implements MageServer { public UUID getTableChatId(UUID tableId) throws MageException { try { return TableManager.getInstance().getChatId(tableId); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -572,8 +560,7 @@ public class MageServerImpl implements MageServer { public UUID getGameChatId(UUID gameId) throws MageException { try { return GameManager.getInstance().getChatId(gameId); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -584,8 +571,7 @@ public class MageServerImpl implements MageServer { public UUID getTournamentChatId(UUID tournamentId) throws MageException { try { return TournamentManager.getInstance().getChatId(tournamentId); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -602,7 +588,7 @@ public class MageServerImpl implements MageServer { user.sendPlayerUUID(gameId, data); } else { logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + } } }); } @@ -617,7 +603,7 @@ public class MageServerImpl implements MageServer { user.sendPlayerString(gameId, data); } else { logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + } } }); } @@ -647,7 +633,7 @@ public class MageServerImpl implements MageServer { user.sendPlayerBoolean(gameId, data); } else { logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + } } }); } @@ -675,8 +661,8 @@ public class MageServerImpl implements MageServer { Session session = SessionManager.getInstance().getSession(sessionId); if (session != null) { return DraftManager.getInstance().sendCardPick(draftId, session.getUserId(), cardPick, hiddenCards); - } else{ - logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); + } else { + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); } return null; } @@ -691,8 +677,8 @@ public class MageServerImpl implements MageServer { 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); + } else { + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); } } }); @@ -706,8 +692,8 @@ public class MageServerImpl implements MageServer { 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); + } else { + logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); } } }); @@ -721,8 +707,8 @@ public class MageServerImpl implements MageServer { 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); + } else { + logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId); } } }); @@ -735,7 +721,7 @@ public class MageServerImpl implements MageServer { public void execute() { Session session = SessionManager.getInstance().getSession(sessionId); if (session == null) { - logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); return; } UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); @@ -755,14 +741,14 @@ public class MageServerImpl implements MageServer { public void execute() { Session session = SessionManager.getInstance().getSession(sessionId); if (session == null) { - logger.error("Session not found sessionId: "+ sessionId + " gameId:" + gameId); + logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); return; } GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); } }); } - + @Override public boolean watchTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { @@ -893,8 +879,7 @@ public class MageServerImpl implements MageServer { CardRepository.instance.getContentVersionConstant(), ExpansionRepository.instance.getContentVersionConstant() ); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } return null; @@ -925,7 +910,7 @@ public class MageServerImpl implements MageServer { return false; } }); - } + } public void handleException(Exception ex) throws MageException { if (!ex.getMessage().equals("No message")) { @@ -936,12 +921,12 @@ public class MageServerImpl implements MageServer { @Override public GameView getGameView(final UUID gameId, final String sessionId, final UUID playerId) throws MageException { - return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { - @Override - public GameView execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - return GameManager.getInstance().getGameView(gameId, userId, playerId); - } + return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { + @Override + public GameView execute() throws MageException { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + return GameManager.getInstance().getGameView(gameId, userId, playerId); + } }); } @@ -988,11 +973,11 @@ public class MageServerImpl implements MageServer { } /** - * Admin console - Remove table - * + * Admin console - Remove table + * * @param sessionId * @param tableId - * @throws MageException + * @throws MageException */ @Override public void removeTable(final String sessionId, final UUID tableId) throws MageException { @@ -1009,9 +994,9 @@ public class MageServerImpl implements MageServer { public Object getServerMessagesCompressed(String sessionId) throws MageException { return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { @Override - public Object execute() throws MageException { - return CompressUtil.compress(ServerMessagesUtil.getInstance().getMessages()); - } + public Object execute() throws MageException { + return CompressUtil.compress(ServerMessagesUtil.getInstance().getMessages()); + } }); } @@ -1028,7 +1013,7 @@ public class MageServerImpl implements MageServer { }); } } - + @Override public void sendBroadcastMessage(final String sessionId, final String message) throws MageException { if (message != null) { @@ -1061,23 +1046,22 @@ 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); + new Runnable() { + @Override + public void run() { + if (SessionManager.getInstance().isValidSession(sessionId)) { + try { + action.execute(); + } catch (MageException me) { + throw new RuntimeException(me); + } + } else { + LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION_INTERNAL, actionName, sessionId); } - } else { - LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION_INTERNAL, actionName, sessionId); } } - } ); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(ex); } } else { diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 5bfe452d51c..d3d2bc5aa10 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -1,31 +1,30 @@ /* -* 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. -*/ - + * 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.server; import java.util.Date; @@ -42,7 +41,6 @@ import mage.players.net.UserData; import mage.players.net.UserGroup; import mage.server.game.GamesRoomManager; import mage.server.util.ConfigSettings; -import mage.view.UserDataView; import org.apache.log4j.Logger; import org.jboss.remoting.callback.AsynchInvokerCallbackHandler; import org.jboss.remoting.callback.Callback; @@ -124,7 +122,7 @@ public class Session { } if (!UserManager.getInstance().connectToSession(sessionId, user.getId())) { return new StringBuilder("Error connecting ").append(userName).toString(); - } + } this.userId = user.getId(); if (reconnect) { // must be connected to receive the message UUID chatId = GamesRoomManager.getInstance().getRoom(GamesRoomManager.getInstance().getMainRoomId()).getChatId(); @@ -132,7 +130,7 @@ public class Session { ChatManager.getInstance().joinChat(chatId, userId); } ChatManager.getInstance().sendReconnectMessage(userId); - } + } return null; } @@ -144,75 +142,45 @@ public class Session { } user.setUserData(new UserData(UserGroup.ADMIN, 0, false, false, false, null, "world.png", false)); if (!UserManager.getInstance().connectToSession(sessionId, user.getId())) { - logger.info("Error connecting Admin!"); - } + logger.info("Error connecting Admin!"); + } this.userId = user.getId(); } - public boolean setUserData(String userName, UserDataView userDataView) { + public boolean setUserData(String userName, UserData userData) { User user = UserManager.getInstance().findUser(userName); if (user != null) { - UserData userData = user.getUserData(); - if (userData == null) { - userData = new UserData(UserGroup.PLAYER, userDataView.getAvatarId(), - userDataView.isShowAbilityPickerForced(), userDataView.allowRequestShowHandCards(), - userDataView.confirmEmptyManaPool(), userDataView.getUserSkipPrioritySteps(), - userDataView.getFlagName(), userDataView.askMoveToGraveOrder()); + if (user.getUserData() == null || user.getUserData().getGroupId() == UserGroup.DEFAULT.getGroupId()) { user.setUserData(userData); } else { - if (userDataView.getAvatarId() == 51) { // Update special avatar if first avatar is selected - updateAvatar(userName, userData); - } - userData.setAvatarId(userDataView.getAvatarId()); - userData.setShowAbilityPickerForced(userDataView.isShowAbilityPickerForced()); - userData.setAllowRequestShowHandCards(userDataView.allowRequestShowHandCards()); - userData.setUserSkipPrioritySteps(userDataView.getUserSkipPrioritySteps()); - userData.setConfirmEmptyManaPool(userDataView.confirmEmptyManaPool()); - userData.setAskMoveToGraveOrder(userDataView.askMoveToGraveOrder()); + user.getUserData().update(userData); + } + if (user.getUserData().getAvatarId() == 51) { + user.getUserData().setAvatarId(updateAvatar(user.getName())); } return true; } return false; } - private void updateAvatar(String userName, UserData userData) { + private int updateAvatar(String userName) { //TODO: move to separate class //TODO: add for checking for private key switch (userName) { case "nantuko": - userData.setAvatarId(1000); - break; - case "i_no_k": - userData.setAvatarId(1002); - break; - case "Askael": - userData.setAvatarId(1004); - break; + return 1000; case "North": - userData.setAvatarId(1006); - break; + return 1006; case "BetaSteward": - userData.setAvatarId(1008); - break; - case "Arching": - userData.setAvatarId(1010); - break; + return 1008; case "loki": - userData.setAvatarId(1012); - break; - case "Alive": - userData.setAvatarId(1014); - break; - case "Rahan": - userData.setAvatarId(1016); - break; + return 1012; case "Ayrat": - userData.setAvatarId(1018); - break; + return 1018; case "Bandit": - userData.setAvatarId(1020); - break; + return 1020; } + return 51; } public String getId() { @@ -220,10 +188,10 @@ public class Session { } // because different threads can activate this - public void userLostConnection() { + public void userLostConnection() { boolean lockSet = false; try { - if(lock.tryLock(5000, TimeUnit.MILLISECONDS)) { + if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) { lockSet = true; logger.debug("SESSION LOCK SET sessionId: " + sessionId); } else { @@ -243,9 +211,8 @@ public class Session { } catch (InterruptedException ex) { logger.error("SESSION LOCK lost connection - userId: " + userId, ex); - } - finally { - if (lockSet) { + } finally { + if (lockSet) { lock.unlock(); logger.trace("SESSION LOCK UNLOCK sessionId: " + sessionId); } @@ -256,18 +223,17 @@ public class Session { public void kill(DisconnectReason reason) { boolean lockSet = false; try { - if(lock.tryLock(5000, TimeUnit.MILLISECONDS)) { + if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) { lockSet = true; - logger.debug("SESSION LOCK SET sessionId: " + sessionId); + logger.debug("SESSION LOCK SET sessionId: " + sessionId); } else { logger.error("SESSION LOCK - kill: userId " + userId); } UserManager.getInstance().removeUser(userId, reason); } catch (InterruptedException ex) { logger.error("SESSION LOCK - kill: userId " + userId, ex); - } - finally { - if (lockSet) { + } finally { + if (lockSet) { lock.unlock(); logger.debug("SESSION LOCK UNLOCK sessionId: " + sessionId); @@ -282,7 +248,7 @@ public class Session { callbackHandler.handleCallbackOneway(new Callback(call)); } catch (HandleCallbackException ex) { User user = UserManager.getInstance().getUser(userId); - logger.warn("SESSION CALLBACK EXCEPTION - " + (user != null ? user.getName():"") + " userId " + userId); + logger.warn("SESSION CALLBACK EXCEPTION - " + (user != null ? user.getName() : "") + " userId " + userId); logger.warn(" - method: " + call.getMethod()); logger.warn(" - cause: " + getBasicCause(ex).toString()); logger.trace("Stack trace:", ex); diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index 2bf3e9e4fc7..d7a6db388e2 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -31,9 +31,9 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import mage.MageException; +import mage.players.net.UserData; import mage.server.services.LogKeys; import mage.server.services.impl.LogServiceImpl; -import mage.view.UserDataView; import org.apache.log4j.Logger; import org.jboss.remoting.callback.InvokerCallbackHandler; @@ -73,7 +73,7 @@ public class SessionManager { public boolean registerUser(String sessionId, String userName) throws MageException { Session session = sessions.get(sessionId); if (session != null) { - String returnMessage = session.registerUser(userName); + String returnMessage = session.registerUser(userName); if (returnMessage == null) { LogServiceImpl.instance.log(LogKeys.KEY_USER_CONNECTED, userName, session.getHost(), sessionId); @@ -102,24 +102,24 @@ public class SessionManager { return false; } - public boolean setUserData(String userName, String sessionId, UserDataView userDataView) throws MageException { + public boolean setUserData(String userName, String sessionId, UserData userData) throws MageException { Session session = sessions.get(sessionId); if (session != null) { - session.setUserData(userName, userDataView); + session.setUserData(userName, userData); return true; } return false; } public void disconnect(String sessionId, DisconnectReason reason) { - Session session = sessions.get(sessionId); + Session session = sessions.get(sessionId); if (session != null) { if (!reason.equals(DisconnectReason.AdminDisconnect)) { if (!sessions.containsKey(sessionId)) { // session was removed meanwhile by another thread so we can return return; } - logger.debug("DISCONNECT " + reason.toString() + " - sessionId: "+ sessionId); + logger.debug("DISCONNECT " + reason.toString() + " - sessionId: " + sessionId); sessions.remove(sessionId); switch (reason) { case Disconnected: @@ -135,13 +135,13 @@ public class SessionManager { LogServiceImpl.instance.log(LogKeys.KEY_SESSION_DISCONNECTED, sessionId); break; default: - logger.error("endSession: unexpected reason " + reason.toString() + " - sessionId: "+ sessionId); + logger.error("endSession: unexpected reason " + reason.toString() + " - sessionId: " + sessionId); } } else { sessions.remove(sessionId); session.kill(reason); } - } + } } @@ -155,6 +155,7 @@ public class SessionManager { /** * Admin requested the disconnect of a user + * * @param sessionId * @param userSessionId */ @@ -163,12 +164,12 @@ public class SessionManager { User userAdmin, user; if ((userAdmin = getUserFromSession(sessionId)) != null) { if ((user = getUserFromSession(userSessionId)) != null) { - user.showUserMessage("Admin operation","Your session was disconnected by Admin."); + user.showUserMessage("Admin operation", "Your session was disconnected by Admin."); userAdmin.showUserMessage("Admin action", "User" + user.getName() + " was disconnected."); disconnect(userSessionId, DisconnectReason.AdminDisconnect); LogServiceImpl.instance.log(LogKeys.KEY_SESSION_DISCONNECTED_BY_ADMIN, sessionId, userSessionId); } else { - userAdmin.showUserMessage("Admin operation","User with sessionId " + userSessionId + " could not be found!"); + userAdmin.showUserMessage("Admin operation", "User with sessionId " + userSessionId + " could not be found!"); } } } @@ -203,7 +204,7 @@ public class SessionManager { public User getUser(String sessionId) { Session session = sessions.get(sessionId); - if (session != null) { + if (session != null) { return UserManager.getInstance().getUser(sessions.get(sessionId).getUserId()); } return null; diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index 4e5eceec45e..be401c7ffe8 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -1,31 +1,30 @@ /* -* 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. -*/ - + * 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.server; import java.util.Map; @@ -91,7 +90,7 @@ public class TableController { private Match match; private MatchOptions options; private Tournament tournament; - + private ScheduledFuture futureTimeout; protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); @@ -103,12 +102,11 @@ public class TableController { User user = UserManager.getInstance().getUser(userId); // TODO: Handle if user == null controllerName = user.getName(); - } - else { + } else { controllerName = "System"; } table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), match); - chatId = ChatManager.getInstance().createChatSession("Match Table " + table.getId()); + chatId = ChatManager.getInstance().createChatSession("Match Table " + table.getId()); init(); } @@ -123,30 +121,29 @@ public class TableController { } else { controllerName = user.getName(); } - } - else { + } else { controllerName = "System"; } table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), tournament); - chatId = ChatManager.getInstance().createChatSession("Tourn. table " + table.getId()); + chatId = ChatManager.getInstance().createChatSession("Tourn. table " + table.getId()); } 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; + new Listener() { + @Override + public void event(TableEvent 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); } } - } ); } @@ -171,13 +168,13 @@ public class TableController { return false; } } - if (userPlayerMap.containsKey(userId) && playerType.equals("Human")){ + if (userPlayerMap.containsKey(userId) && playerType.equals("Human")) { user.showUserMessage("Join Table", new StringBuilder("You can join a table only one time.").toString()); return false; } Deck deck = null; if (!table.getTournament().getTournamentType().isLimited()) { - if (deckList != null) { + if (deckList != null) { deck = Deck.load(deckList, false, false); } else { user.showUserMessage("Join Table", "No valid deck selected!"); @@ -208,9 +205,9 @@ public class TableController { TournamentPlayer tournamentPlayer = tournament.getPlayer(player.getId()); if (deck != null && tournamentPlayer != null) { tournamentPlayer.submitDeck(deck); - } - table.joinTable(player, seat); - logger.debug("Player " + player.getName() + " id: "+ player.getId() + " joined tableId: " + table.getId()); + } + table.joinTable(player, seat); + logger.debug("Player " + player.getName() + " id: " + player.getId() + " joined tableId: " + table.getId()); //only inform human players and add them to sessionPlayerMap if (seat.getPlayer().isHuman()) { seat.getPlayer().setUserData(user.getUserData()); @@ -235,12 +232,12 @@ public class TableController { return false; } TournamentPlayer oldTournamentPlayer = tournament.getPlayer(oldPlayer.getId()); - tournament.removePlayer(oldPlayer.getId()); + tournament.removePlayer(oldPlayer.getId()); tournament.addPlayer(newPlayer, playerType); - TournamentPlayer newTournamentPlayer = tournament.getPlayer(newPlayer.getId()); + TournamentPlayer newTournamentPlayer = tournament.getPlayer(newPlayer.getId()); newTournamentPlayer.setState(oldTournamentPlayer.getState()); - + DraftManager.getInstance().getController(table.getId()).replacePlayer(oldPlayer, newPlayer); return true; } @@ -250,7 +247,7 @@ public class TableController { if (user == null) { return false; } - if (userPlayerMap.containsKey(userId) && playerType.equals("Human")){ + if (userPlayerMap.containsKey(userId) && playerType.equals("Human")) { user.showUserMessage("Join Table", new StringBuilder("You can join a table only one time.").toString()); return false; } @@ -289,7 +286,7 @@ public class TableController { if (player == null) { String message = new StringBuilder("Could not create player ").append(name).append(" of type ").append(seat.getPlayerType()).toString(); logger.warn(new StringBuilder("User: ").append(user.getName()).append(" => ").append(message).toString()); - user.showUserMessage("Join Table",message); + user.showUserMessage("Join Table", message); return false; } logger.debug("DECK validated: " + table.getValidator().getName() + " " + player.getName() + " " + deck.getName()); @@ -312,7 +309,7 @@ public class TableController { return true; } - public void addPlayer(UUID userId, Player player, String playerType, Deck deck) throws GameException { + public void addPlayer(UUID userId, Player player, String playerType, Deck deck) throws GameException { if (table.getState() != TableState.WAITING) { return; } @@ -378,8 +375,7 @@ public class TableController { if (table.getState() == TableState.SIDEBOARDING) { match.submitDeck(playerId, deck); UserManager.getInstance().getUser(userId).removeSideboarding(table.getId()); - } - else { + } else { TournamentManager.getInstance().submitDeck(tournament.getId(), playerId, deck); UserManager.getInstance().getUser(userId).removeConstructing(playerId); } @@ -390,7 +386,7 @@ public class TableController { if (tournament != null) { TournamentManager.getInstance().updateDeck(tournament.getId(), playerId, deck); } else { - logger.fatal("Tournament == null table: " + table.getId() +" userId: " + userId); + logger.fatal("Tournament == null table: " + table.getId() + " userId: " + userId); } } else { if (TableState.SIDEBOARDING.equals(table.getState())) { @@ -427,13 +423,11 @@ public class TableController { // ReplayManager.getInstance().replayGame(table.getId(), userId); // return true; // } - private Player createPlayer(String name, String playerType, int skill) { Player player; if (options == null) { player = PlayerFactory.getInstance().createPlayer(playerType, name, RangeOfInfluence.ALL, skill); - } - else { + } else { player = PlayerFactory.getInstance().createPlayer(playerType, name, options.getRange(), skill); } if (player != null) { @@ -443,12 +437,12 @@ public class TableController { } public void leaveTableAll() { - for (UUID leavingUserId: userPlayerMap.keySet()) { + for (UUID leavingUserId : userPlayerMap.keySet()) { leaveTable(leavingUserId); } closeTable(); } - + public synchronized void leaveTable(UUID userId) { if (table == null) { logger.error("No table object - userId: " + userId); @@ -488,19 +482,19 @@ public class TableController { if (table.isTournament()) { logger.debug("Quit tournament sub tables for userId: " + userId); TableManager.getInstance().userQuitTournamentSubTables(tournament.getId(), userId); - logger.debug("Quit tournament Id: " + table.getTournament().getId() + "(" +table.getTournament().getTournamentState() + ")"); + logger.debug("Quit tournament Id: " + table.getTournament().getId() + "(" + table.getTournament().getTournamentState() + ")"); TournamentManager.getInstance().quit(tournament.getId(), userId); } else { MatchPlayer matchPlayer = match.getPlayer(playerId); if (matchPlayer != null && !match.hasEnded() && !matchPlayer.hasQuit()) { Game game = match.getGame(); - if (game != null && !game.hasEnded()){ + if (game != null && !game.hasEnded()) { Player player = match.getPlayer(playerId).getPlayer(); if (player != null && player.isInGame()) { GameManager.getInstance().quitMatch(game.getId(), userId); } match.quitMatch(playerId); - } else { + } else { if (table.getState().equals(TableState.SIDEBOARDING)) { if (!matchPlayer.isDoneSideboarding()) { // submit deck to finish sideboarding and trigger match start / end @@ -520,7 +514,7 @@ public class TableController { /** * Used from non tournament match to start - * + * * @param userId owner of the tabel */ public synchronized void startMatch(UUID userId) { @@ -536,7 +530,7 @@ public class TableController { logger.info("Tourn. match started id:" + match.getId() + " tournId: " + table.getTournament().getId()); } else { User user = UserManager.getInstance().getUser(userId); - logger.info("MATCH started [" + match.getName() + "] " + match.getId() + "(" + user.getName() +")"); + logger.info("MATCH started [" + match.getName() + "] " + match.getId() + "(" + user.getName() + ")"); logger.debug("- " + match.getOptions().getGameType() + " - " + match.getOptions().getDeckType()); } match.startMatch(); @@ -558,12 +552,12 @@ public class TableController { GameManager.getInstance().createGameSession(match.getGame(), userPlayerMap, table.getId(), choosingPlayerId, gameOptions); String creator = null; StringBuilder opponent = new StringBuilder(); - for (Entry entry: userPlayerMap.entrySet()) { // no AI players + for (Entry entry : userPlayerMap.entrySet()) { // no AI players if (!match.getPlayer(entry.getValue()).hasQuit()) { User user = UserManager.getInstance().getUser(entry.getKey()); if (user != null) { user.ccGameStarted(match.getGame().getId(), entry.getValue()); - + if (creator == null) { creator = user.getName(); } else { @@ -582,7 +576,7 @@ public class TableController { } } // Append AI opponents to the log file - for (MatchPlayer mPlayer :match.getPlayers()) { + for (MatchPlayer mPlayer : match.getPlayers()) { if (!mPlayer.getPlayer().isHuman()) { if (opponent.length() > 0) { opponent.append(" - "); @@ -592,9 +586,8 @@ public class TableController { } ServerMessagesUtil.getInstance().incGamesStarted(); - // log about game started - logger.info("GAME started " + match.getGame().getId() + " [" + match.getName() +"] "+ creator + " - " + opponent.toString()); + logger.info("GAME started " + match.getGame().getId() + " [" + match.getName() + "] " + creator + " - " + opponent.toString()); logger.debug("- matchId: " + match.getId() + " [" + match.getName() + "]"); if (match.getGame() != null) { logger.debug("- chatId: " + GameManager.getInstance().getChatId(match.getGame().getId())); @@ -602,8 +595,7 @@ public class TableController { logger.debug("- no valid game object"); } LogServiceImpl.instance.log(LogKeys.KEY_GAME_STARTED, String.valueOf(userPlayerMap.size()), creator, opponent.toString()); - } - catch (Exception ex) { + } catch (Exception ex) { logger.fatal("Error starting game", ex); if (table != null) { TableManager.getInstance().removeTable(table.getId()); @@ -618,11 +610,11 @@ public class TableController { } public synchronized void startTournament(UUID userId) { - try { + try { if (userId.equals(this.userId) && table.getState().equals(TableState.STARTING)) { tournament.setStartTime(); TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId()); - for (Entry entry: userPlayerMap.entrySet()) { + for (Entry entry : userPlayerMap.entrySet()) { User user = UserManager.getInstance().getUser(entry.getKey()); if (user != null) { logger.info(new StringBuilder("User ").append(user.getName()).append(" tournament started: ").append(tournament.getId()).append(" userId: ").append(user.getId())); @@ -631,8 +623,7 @@ public class TableController { } ServerMessagesUtil.getInstance().incTournamentsStarted(); } - } - catch (Exception ex) { + } catch (Exception ex) { logger.fatal("Error starting tournament", ex); TableManager.getInstance().removeTable(table.getId()); TournamentManager.getInstance().quit(tournament.getId(), userId); @@ -642,7 +633,7 @@ public class TableController { public void startDraft(Draft draft) { table.initDraft(); DraftManager.getInstance().createDraftSession(draft, userPlayerMap, table.getId()); - for (Entry entry: userPlayerMap.entrySet()) { + for (Entry entry : userPlayerMap.entrySet()) { User user = UserManager.getInstance().getUser(entry.getKey()); if (user != null) { logger.info(new StringBuilder("User ").append(user.getName()).append(" draft started: ").append(draft.getId()).append(" userId: ").append(user.getId())); @@ -654,7 +645,7 @@ public class TableController { } private void sideboard(UUID playerId, Deck deck) throws MageException { - for (Entry entry: userPlayerMap.entrySet()) { + for (Entry entry : userPlayerMap.entrySet()) { if (entry.getValue().equals(playerId)) { User user = UserManager.getInstance().getUser(entry.getKey()); int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS); @@ -668,7 +659,7 @@ public class TableController { public int getRemainingTime() { return (int) futureTimeout.getDelay(TimeUnit.SECONDS); - } + } public void construct() { table.construct(); @@ -715,8 +706,7 @@ public class TableController { } else { closeTable(); } - } - else { + } else { closeTable(); } } catch (GameException ex) { @@ -729,7 +719,7 @@ public class TableController { table.sideboard(); setupTimeout(Match.SIDEBOARD_TIME); if (table.isTournamentSubTable()) { - for (MatchPlayer matchPlayer :match.getPlayers()) { + for (MatchPlayer matchPlayer : match.getPlayers()) { if (!matchPlayer.hasQuit()) { TournamentPlayer tournamentPlayer = table.getTournament().getPlayer(matchPlayer.getPlayer().getId()); if (tournamentPlayer != null) { @@ -741,7 +731,7 @@ public class TableController { match.sideboard(); cancelTimeout(); if (table.isTournamentSubTable()) { - for (MatchPlayer matchPlayer :match.getPlayers()) { + for (MatchPlayer matchPlayer : match.getPlayers()) { TournamentPlayer tournamentPlayer = table.getTournament().getPlayer(matchPlayer.getPlayer().getId()); if (tournamentPlayer != null && tournamentPlayer.getStateInfo().equals("sideboarding")) { tournamentPlayer.setStateInfo(""); @@ -749,10 +739,11 @@ public class TableController { } } } + /** - * Tables of normal matches or tournament sub tables are no longer - * needed, if the match ends. - * + * Tables of normal matches or tournament sub tables are no longer needed, + * if the match ends. + * */ private void closeTable() { this.matchEnd(); @@ -761,11 +752,11 @@ public class TableController { private void matchEnd() { if (match != null) { - for (Entry entry: userPlayerMap.entrySet()) { + for (Entry entry : userPlayerMap.entrySet()) { MatchPlayer matchPlayer = match.getPlayer(entry.getValue()); // opponent(s) left during sideboarding if (matchPlayer != null) { - if(!matchPlayer.hasQuit()) { + if (!matchPlayer.hasQuit()) { User user = UserManager.getInstance().getUser(entry.getKey()); if (user != null) { if (table.getState().equals(TableState.SIDEBOARDING)) { @@ -801,13 +792,13 @@ public class TableController { cancelTimeout(); if (seconds > 0) { futureTimeout = timeoutExecutor.schedule( - new Runnable() { - @Override - public void run() { - autoSideboard(); - } - }, - seconds, TimeUnit.SECONDS + new Runnable() { + @Override + public void run() { + autoSideboard(); + } + }, + seconds, TimeUnit.SECONDS ); } } @@ -819,7 +810,7 @@ public class TableController { } private void autoSideboard() { - for (MatchPlayer player: match.getPlayers()) { + for (MatchPlayer player : match.getPlayers()) { if (!player.isDoneSideboarding()) { match.submitDeck(player.getPlayer().getId(), player.generateDeck()); } @@ -828,7 +819,7 @@ public class TableController { public void endDraft(Draft draft) { if (!draft.isAbort()) { - for (DraftPlayer player: draft.getPlayers()) { + for (DraftPlayer player : draft.getPlayers()) { player.prepareDeck(); tournament.getPlayer(player.getPlayer().getId()).setDeck(player.getDeck()); } @@ -871,7 +862,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().equals(TableState.WAITING) && !table.getState().equals(TableState.READY_TO_START) && !table.getState().equals(TableState.STARTING)) { TournamentController tournamentController = TournamentManager.getInstance().getTournamentController(table.getTournament().getId()); if (tournamentController != null) { return tournamentController.isTournamentStillValid(table.getState()); @@ -888,7 +879,7 @@ public class TableController { } public UUID getUserId(UUID playerId) { - for (Map.Entry entry: userPlayerMap.entrySet()) { + for (Map.Entry entry : userPlayerMap.entrySet()) { if (entry.getValue().equals(playerId)) { return entry.getKey(); } @@ -900,7 +891,7 @@ public class TableController { // check only normal match table with state != Finished if (!table.isTournament()) { int humanPlayers = 0; - int aiPlayers = 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 (match == null) { @@ -917,7 +908,7 @@ public class TableController { } } // check for active players - for(Map.Entry userPlayerEntry: userPlayerMap.entrySet()) { + for (Map.Entry userPlayerEntry : userPlayerMap.entrySet()) { MatchPlayer matchPlayer = match.getPlayer(userPlayerEntry.getValue()); if (matchPlayer == null) { logger.debug("- Match player not found:"); @@ -927,12 +918,12 @@ public class TableController { continue; } if (matchPlayer.getPlayer().isHuman()) { - humanPlayers++; - if ((table.getState().equals(TableState.WAITING) || - table.getState().equals(TableState.STARTING) || - table.getState().equals(TableState.READY_TO_START)) || - !match.isDoneSideboarding() || - (!matchPlayer.hasQuit() && match.getGame() != null && matchPlayer.getPlayer().isInGame())) { + humanPlayers++; + if ((table.getState().equals(TableState.WAITING) + || table.getState().equals(TableState.STARTING) + || table.getState().equals(TableState.READY_TO_START)) + || !match.isDoneSideboarding() + || (!matchPlayer.hasQuit() && match.getGame() != null && matchPlayer.getPlayer().isInGame())) { User user = UserManager.getInstance().getUser(userPlayerEntry.getKey()); if (user == null) { logger.debug("- Active user of match is missing: " + matchPlayer.getName()); @@ -953,10 +944,10 @@ public class TableController { } return true; } - + void cleanUp() { if (!table.isTournamentSubTable()) { - for(Map.Entry entry: userPlayerMap.entrySet()) { + for (Map.Entry entry : userPlayerMap.entrySet()) { User user = UserManager.getInstance().getUser(entry.getKey()); if (user != null) { user.removeTable(entry.getValue()); @@ -969,11 +960,11 @@ public class TableController { public synchronized TableState getTableState() { return getTable().getState(); } - + public synchronized boolean changeTableState(TableState newTableState) { switch (newTableState) { case WAITING: - if (getTable().getState().equals(TableState.STARTING)){ + if (getTable().getState().equals(TableState.STARTING)) { // tournament already started return false; } diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java index 2fc65355e97..b8003da32d0 100644 --- a/Mage.Server/src/main/java/mage/server/User.java +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -104,8 +104,6 @@ public class User { this.watchedGames = new ArrayList<>(); this.tablesToDelete = new ArrayList<>(); this.sessionId = ""; - // default these to avaiod NPE -> will be updated from client short after - this.userData = new UserData(UserGroup.PLAYER, 0, false, false, false, null, "world.png", false); } public String getName() { @@ -393,10 +391,17 @@ public class User { } public void setUserData(UserData userData) { - this.userData = userData; + if (this.userData != null) { + this.userData.update(userData); + } else { + this.userData = userData; + } } public UserData getUserData() { + if (userData == null) {// default these to avaiod NPE -> will be updated from client short after + return new UserData(UserGroup.DEFAULT, 0, false, false, false, null, "world.png", false); + } return this.userData; } 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 2136cd33465..fa26d966f17 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -1,31 +1,30 @@ /* -* Copyright 2011 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. -*/ - + * Copyright 2011 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.server.tournament; import java.util.Map.Entry; @@ -63,7 +62,6 @@ import mage.view.ChatMessage.SoundToPlay; import mage.view.TournamentView; import org.apache.log4j.Logger; - /** * * @author BetaSteward_at_googlemail.com @@ -89,57 +87,57 @@ 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); - 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 END: - endTournament(); - break; - } - } - } - ); - tournament.addPlayerQueryEventListener( - new Listener () { - @Override - public void event(PlayerQueryEvent event) { - try { - switch (event.getQueryType()) { + 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); + 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 END: + endTournament(); break; } - } catch (MageException ex) { - logger.fatal("Player event listener error", ex); } } - } ); - for (TournamentPlayer player: tournament.getPlayers()) { + tournament.addPlayerQueryEventListener( + new Listener() { + @Override + public void event(PlayerQueryEvent 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()) { player.setJoined(); logger.debug("player " + player.getPlayer().getId() + " has joined tournament " + tournament.getId()); @@ -163,7 +161,7 @@ public class TournamentController { if (tournamentSessions.containsKey(playerId)) { logger.debug("player reopened tournament panel userId: " + userId + " tournamentId: " + tournament.getId()); return; - } + } // first join of player TournamentSession tournamentSession = new TournamentSession(tournament, userId, tableId, playerId); tournamentSessions.put(playerId, tournamentSession); @@ -172,22 +170,22 @@ public class TournamentController { user.addTournament(playerId, tournament.getId()); TournamentPlayer player = tournament.getPlayer(playerId); player.setJoined(); - logger.debug("player " +player.getPlayer().getName() + " - client has joined tournament " + tournament.getId()); + logger.debug("player " + player.getPlayer().getName() + " - client has joined tournament " + tournament.getId()); ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getLogName() + " has joined the tournament", MessageColor.BLACK, true, MessageType.STATUS); checkStart(); } else { - logger.error("User not found userId: " + userId + " tournamentId: " + tournament.getId()); + logger.error("User not found userId: " + userId + " tournamentId: " + tournament.getId()); } } public void rejoin(UUID playerId) { TournamentSession tournamentSession = tournamentSessions.get(playerId); if (tournamentSession == null) { - logger.fatal("Tournament session not found - playerId:" + playerId + " tournamentId " + tournament.getId()); + logger.fatal("Tournament session not found - playerId:" + playerId + " tournamentId " + tournament.getId()); return; } if (!tournamentSession.init()) { - logger.fatal("Unable to initialize client userId: " + tournamentSession.userId + " tournamentId " + tournament.getId()); + logger.fatal("Unable to initialize client userId: " + tournamentSession.userId + " tournamentId " + tournament.getId()); return; } tournamentSession.update(); @@ -196,12 +194,12 @@ public class TournamentController { private void checkStart() { if (!started && allJoined()) { ThreadExecutor.getInstance().getCallExecutor().execute( - new Runnable() { - @Override - public void run() { - startTournament(); - } - }); + new Runnable() { + @Override + public void run() { + startTournament(); + } + }); } } @@ -209,7 +207,7 @@ public class TournamentController { if (!tournament.allJoined()) { return false; } - for (TournamentPlayer player: tournament.getPlayers()) { + for (TournamentPlayer player : tournament.getPlayers()) { if (player.getPlayer().isHuman() && tournamentSessions.get(player.getPlayer().getId()) == null) { return false; } @@ -218,9 +216,9 @@ public class TournamentController { } private synchronized void startTournament() { - for (final TournamentSession tournamentSession: tournamentSessions.values()) { + for (final TournamentSession tournamentSession : tournamentSessions.values()) { if (!tournamentSession.init()) { - logger.fatal("Unable to initialize client userId: " + tournamentSession.userId + " tournamentId " + tournament.getId()); + logger.fatal("Unable to initialize client userId: " + tournamentSession.userId + " tournamentId " + tournament.getId()); //TODO: generate client error message return; } @@ -231,10 +229,10 @@ public class TournamentController { } private void endTournament() { - for (TournamentPlayer player: tournament.getPlayers()) { + for (TournamentPlayer player : tournament.getPlayers()) { player.setStateAtTournamentEnd(); } - for (final TournamentSession tournamentSession: tournamentSessions.values()) { + for (final TournamentSession tournamentSession : tournamentSessions.values()) { tournamentSession.tournamentOver(); } this.tournamentSessions.clear(); @@ -296,8 +294,8 @@ public class TournamentController { TournamentPlayer player = tournament.getPlayer(playerId); if (player != null && !player.hasQuit()) { tournamentSessions.get(playerId).submitDeck(deck); - ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getLogName() + " has submitted his tournament deck", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerSubmittedDeck); - } + ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getLogName() + " has submitted his tournament deck", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerSubmittedDeck); + } } } @@ -387,7 +385,7 @@ public class TournamentController { private boolean checkToReplaceDraftPlayerByAi(UUID userId, TournamentPlayer leavingPlayer) { int humans = 0; - for (TournamentPlayer tPlayer :tournament.getPlayers()) { + for (TournamentPlayer tPlayer : tournament.getPlayers()) { if (tPlayer.getPlayer().isHuman()) { humans++; } @@ -415,7 +413,7 @@ public class TournamentController { } private UUID getPlayerUserId(UUID playerId) { - for (Entry entry: userPlayerMap.entrySet()) { + for (Entry entry : userPlayerMap.entrySet()) { if (entry.getValue().equals(playerId)) { return entry.getKey(); } @@ -437,7 +435,7 @@ public class TournamentController { } private void checkPlayersState() { - for (TournamentPlayer tournamentPlayer: tournament.getPlayers()) { + for (TournamentPlayer tournamentPlayer : tournament.getPlayers()) { if (!tournamentPlayer.isEliminated() && tournamentPlayer.getPlayer().isHuman()) { if (tournamentSessions.containsKey(tournamentPlayer.getPlayer().getId())) { if (tournamentSessions.get(tournamentPlayer.getPlayer().getId()).isKilled()) { @@ -452,22 +450,22 @@ public class TournamentController { } } - + public void cleanUpOnRemoveTournament() { ChatManager.getInstance().destroyChatSession(chatId); } /** - * Check tournaments that are not already finished, if they are in a still valid state + * Check tournaments that are not already finished, if they are in a still + * valid state * * @param tableState state of the tournament table - * @return true - if tournament is valid - * false - if tournament is not valid and should be removed + * @return true - if tournament is valid false - if tournament is not valid + * and should be removed */ - public boolean isTournamentStillValid(TableState tableState) { int activePlayers = 0; - for (Entry entry: userPlayerMap.entrySet()) { + for (Entry entry : userPlayerMap.entrySet()) { TournamentPlayer tournamentPlayer = tournament.getPlayer(entry.getValue()); if (tournamentPlayer != null) { if (!tournamentPlayer.hasQuit()) { @@ -480,14 +478,14 @@ public class TournamentController { } else { activePlayers++; } - } - } + } + } } else { // tournament player is missing logger.debug("Tournament player is missing - tournamentId: " + tournament.getId() + " state: " + tableState.toString()); } } - for(TournamentPlayer tournamentPlayer: tournament.getPlayers()) { + for (TournamentPlayer tournamentPlayer : tournament.getPlayers()) { if (!tournamentPlayer.getPlayer().isHuman()) { if (!tournamentPlayer.hasQuit()) { activePlayers++; diff --git a/Mage.Tests/src/test/java/org/mage/test/player/TestPlayer.java b/Mage.Tests/src/test/java/org/mage/test/player/TestPlayer.java index 9fe14c7e861..e694401346b 100644 --- a/Mage.Tests/src/test/java/org/mage/test/player/TestPlayer.java +++ b/Mage.Tests/src/test/java/org/mage/test/player/TestPlayer.java @@ -99,8 +99,6 @@ import mage.target.common.TargetCreaturePermanentAmount; import mage.target.common.TargetPermanentOrPlayer; import org.junit.Ignore; - - /** * * @author BetaSteward_at_googlemail.com @@ -119,7 +117,6 @@ public class TestPlayer implements Player { private final ComputerPlayer computerPlayer; - public TestPlayer(ComputerPlayer computerPlayer) { this.computerPlayer = computerPlayer; AIPlayer = false; @@ -156,13 +153,14 @@ public class TestPlayer implements Player { } /** - * - * @param maxCallsWithoutAction max number of priority passes a player may have for this test (default = 100) - */ + * + * @param maxCallsWithoutAction max number of priority passes a player may + * have for this test (default = 100) + */ public void setMaxCallsWithoutAction(int maxCallsWithoutAction) { this.maxCallsWithoutAction = maxCallsWithoutAction; } - + protected Permanent findPermanent(FilterPermanent filter, UUID controllerId, Game game) { List permanents = game.getBattlefield().getAllActivePermanents(filter, controllerId, game); if (permanents.size() > 0) { @@ -427,7 +425,7 @@ public class TestPlayer implements Player { if (numberOfActions == actions.size()) { foundNoAction++; if (foundNoAction > maxCallsWithoutAction) { - throw new AssertionError("More priority calls to " +getName() + " and doing no action than allowed (" + maxCallsWithoutAction +")"); + throw new AssertionError("More priority calls to " + getName() + " and doing no action than allowed (" + maxCallsWithoutAction + ")"); } } else { foundNoAction = 0; @@ -609,13 +607,13 @@ public class TestPlayer implements Player { if (target instanceof TargetCardInGraveyard) { TargetCardInGraveyard targetCardInGraveyard = ((TargetCardInGraveyard) target); Set possibleTargets = new HashSet<>(); - for(UUID playerId: this.getInRange()) { + for (UUID playerId : this.getInRange()) { Player player = game.getPlayer(playerId); if (player != null) { possibleTargets.addAll(player.getGraveyard()); } } - + for (String choose2 : choices) { String[] targetList = choose2.split("\\^"); boolean targetFound = false; @@ -643,7 +641,7 @@ public class TestPlayer implements Player { } } } - } + } if (target instanceof TargetSource) { Set possibleTargets; TargetSource t = ((TargetSource) target); @@ -812,7 +810,7 @@ public class TestPlayer implements Player { @Override public int announceXMana(int min, int max, String message, Game game, Ability ability) { if (!choices.isEmpty()) { - for(String choice: choices) { + for (String choice : choices) { if (choice.startsWith("X=")) { int xValue = Integer.parseInt(choice.substring(2)); choices.remove(choice); @@ -1131,12 +1129,12 @@ public class TestPlayer implements Player { public void lookAtCards(String name, Cards cards, Game game) { computerPlayer.lookAtCards(name, cards, game); } - + @Override public void lookAtCards(String name, Card card, Game game) { computerPlayer.lookAtCards(name, card, game); } - + @Override public void phasing(Game game) { computerPlayer.phasing(game); diff --git a/Mage/src/mage/cards/decks/Deck.java b/Mage/src/mage/cards/decks/Deck.java index 74ea98b86f9..7d2dff0e14a 100644 --- a/Mage/src/mage/cards/decks/Deck.java +++ b/Mage/src/mage/cards/decks/Deck.java @@ -1,36 +1,33 @@ /* -* 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. -*/ - + * 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.decks; import java.io.Serializable; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; @@ -61,7 +58,7 @@ public class Deck implements Serializable { Deck deck = new Deck(); deck.setName(deckCardLists.getName()); List deckCardNames = new ArrayList<>(); - for (DeckCardInfo deckCardInfo: deckCardLists.getCards()) { + for (DeckCardInfo deckCardInfo : deckCardLists.getCards()) { Card card = createCard(deckCardInfo, mockCards); if (card != null) { deck.cards.add(card); @@ -71,7 +68,7 @@ public class Deck implements Serializable { } } List sbCardNames = new ArrayList<>(); - for (DeckCardInfo deckCardInfo: deckCardLists.getSideboard()) { + for (DeckCardInfo deckCardInfo : deckCardLists.getSideboard()) { Card card = createCard(deckCardInfo, mockCards); if (card != null) { deck.sideboard.add(card); @@ -97,9 +94,9 @@ public class Deck implements Serializable { } private static GameException createCardNotFoundGameException(DeckCardInfo deckCardInfo, String deckName) { - return new GameException("Card not found - " + deckCardInfo.getCardName() + " - " + deckCardInfo.getSetCode() + " for deck - " + deckName + "\n" + - "Possible reason is, that you use cards in your deck, that are only supported in newer versions of the server.\n" + - "So it can help to use the same card from another set, that's already supported from this server." ); + return new GameException("Card not found - " + deckCardInfo.getCardName() + " - " + deckCardInfo.getSetCode() + " for deck - " + deckName + "\n" + + "Possible reason is, that you use cards in your deck, that are only supported in newer versions of the server.\n" + + "So it can help to use the same card from another set, that's already supported from this server."); } private static Card createCard(DeckCardInfo deckCardInfo, boolean mockCards) { @@ -119,11 +116,11 @@ public class Deck implements Serializable { DeckCardLists deckCardLists = new DeckCardLists(); deckCardLists.setName(name); - for (Card card: cards) { + for (Card card : cards) { deckCardLists.getCards().add(new DeckCardInfo(card.getName(), card.getCardNumber(), card.getExpansionSetCode())); } - for (Card card: sideboard) { + for (Card card : sideboard) { deckCardLists.getSideboard().add(new DeckCardInfo(card.getName(), card.getCardNumber(), card.getExpansionSetCode())); } diff --git a/Mage/src/mage/players/Player.java b/Mage/src/mage/players/Player.java index c369e8f045e..b6e8fe3d776 100644 --- a/Mage/src/mage/players/Player.java +++ b/Mage/src/mage/players/Player.java @@ -1,31 +1,30 @@ /* -* 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. -*/ - + * 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.players; import java.io.Serializable; @@ -35,7 +34,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; - import mage.MageItem; import mage.MageObject; import mage.abilities.Abilities; @@ -84,104 +82,170 @@ import mage.util.Copyable; public interface Player extends MageItem, Copyable { boolean isHuman(); + String getName(); + String getLogName(); + RangeOfInfluence getRange(); + Library getLibrary(); + Cards getSideboard(); + Graveyard getGraveyard(); + Abilities getAbilities(); + void addAbility(Ability ability); + Counters getCounters(); + int getLife(); + void initLife(int life); + void setLife(int life, Game game); + int loseLife(int amount, Game game); + int gainLife(int amount, Game game); + int damage(int damage, UUID sourceId, Game game, boolean combatDamage, boolean preventable); + int damage(int damage, UUID sourceId, Game game, boolean combatDamage, boolean preventable, ArrayList appliedEffects); - + // to handle rule changing effects (613.10) boolean isCanLoseLife(); - void setCanLoseLife(boolean canLoseLife); + + void setCanLoseLife(boolean canLoseLife); + void setCanGainLife(boolean canGainLife); + boolean isCanGainLife(); + void setCanPayLifeCost(boolean canPayLifeCost); + boolean canPayLifeCost(); - void setCanPaySacrificeCost(boolean canPaySacrificeCost); + + void setCanPaySacrificeCost(boolean canPaySacrificeCost); + boolean canPaySacrificeCost(); + void setLifeTotalCanChange(boolean lifeTotalCanChange); - boolean isLifeTotalCanChange(); + + boolean isLifeTotalCanChange(); + void setLoseByZeroOrLessLife(boolean loseByZeroOrLessLife); + boolean canLoseByZeroOrLessLife(); + void setPlayCardsFromGraveyard(boolean playCardsFromGraveyard); + boolean canPlayCardsFromGraveyard(); /** * Returns alternative casting costs a player can cast spells for - * - * @return + * + * @return */ List getAlternativeSourceCosts(); - - + Cards getHand(); + int getLandsPlayed(); + int getLandsPerTurn(); + void setLandsPerTurn(int landsPerTurn); + int getLoyaltyUsePerTurn(); + void setLoyaltyUsePerTurn(int loyaltyUsePerTurn); + int getMaxHandSize(); + void setMaxHandSize(int maxHandSize); + int getMaxAttackedBy(); + void setMaxAttackedBy(int maxAttackedBy); + boolean isPassed(); + boolean isEmptyDraw(); + void pass(Game game); + void resetPassed(); boolean getPassedTurn(); + boolean getPassedUntilEndOfTurn(); + boolean getPassedUntilNextMain(); + boolean getPassedUntilStackResolved(); + boolean getPassedAllTurns(); boolean hasLost(); + boolean hasWon(); + boolean hasQuit(); + void quit(Game game); + boolean hasTimerTimeout(); + void timerTimeout(Game game); + boolean hasIdleTimeout(); + void idleTimeout(Game game); + boolean hasLeft(); + /** * Player is still active in game (has not left, lost or won the game). + * * @return */ boolean isInGame(); + /** * Called if other player left the game + * * @param game */ void otherPlayerLeftGame(Game game); - + ManaPool getManaPool(); + Set getInRange(); + boolean isTopCardRevealed(); + void setTopCardRevealed(boolean topCardRevealed); + /** - * Get data from the client Preferences (e.g. avatarId or showAbilityPickerForce) - * @return + * Get data from the client Preferences (e.g. avatarId or + * showAbilityPickerForce) + * + * @return */ UserData getUserData(); + void setUserData(UserData userData); + boolean canLose(Game game); + boolean autoLoseGame(); /** - * Returns a set of players which turns under you control. - * Doesn't include yourself. + * Returns a set of players which turns under you control. Doesn't include + * yourself. * * @return */ @@ -189,6 +253,7 @@ public interface Player extends MageItem, Copyable { /** * Defines player whose turn this player controls at the moment. + * * @param game * @param playerId */ @@ -211,7 +276,8 @@ public interface Player extends MageItem, Copyable { /** * Returns false in case player don't control the game. * - * Note: For effects like "You control target player during that player's next turn". + * Note: For effects like "You control target player during that player's + * next turn". * * @return */ @@ -220,103 +286,165 @@ public interface Player extends MageItem, Copyable { /** * Returns false in case you don't control the game. * - * Note: For effects like "You control target player during that player's next turn". + * Note: For effects like "You control target player during that player's + * next turn". * * @param value */ void setGameUnderYourControl(boolean value); boolean isTestMode(); + void setTestMode(boolean value); + void addAction(String action); + int getActionCount(); + void setAllowBadMoves(boolean allowBadMoves); void init(Game game); + void init(Game game, boolean testMode); + void useDeck(Deck deck, Game game); - + /** - * Called before each applyEffects, to rest all what can be applyed by continuous effects + * Called before each applyEffects, to rest all what can be applyed by + * continuous effects */ void reset(); - + void shuffleLibrary(Game game); + int drawCards(int num, Game game); + int drawCards(int num, Game game, ArrayList appliedEffects); + boolean cast(SpellAbility ability, Game game, boolean noMana); + SpellAbility chooseSpellAbilityForCast(SpellAbility ability, Game game, boolean noMana); + boolean putInHand(Card card, Game game); + boolean removeFromHand(Card card, Game game); + boolean removeFromBattlefield(Permanent permanent, Game game); + boolean putInGraveyard(Card card, Game game, boolean fromBattlefield); + boolean removeFromGraveyard(Card card, Game game); + boolean removeFromLibrary(Card card, Game game); + boolean searchLibrary(TargetCardInLibrary target, Game game); + /** - * - * @param target - * @param game - * @param targetPlayerId player whose library will be searched - * @return true if search was successful - */ + * + * @param target + * @param game + * @param targetPlayerId player whose library will be searched + * @return true if search was successful + */ boolean searchLibrary(TargetCardInLibrary target, Game game, UUID targetPlayerId); + boolean canPlayLand(); + boolean playLand(Card card, Game game); + boolean activateAbility(ActivatedAbility ability, Game game); + boolean triggerAbility(TriggeredAbility ability, Game game); + boolean canBeTargetedBy(MageObject source, UUID sourceControllerId, Game game); + boolean hasProtectionFrom(MageObject source, Game game); + boolean flipCoin(Game game); + boolean flipCoin(Game game, ArrayList appliedEffects); + @Deprecated void discard(int amount, Ability source, Game game); + Card discardOne(boolean random, Ability source, Game game); + Cards discard(int amount, boolean random, Ability source, Game game); + void discardToMax(Game game); + boolean discard(Card card, Ability source, Game game); + void lost(Game game); + void lostForced(Game game); + void won(Game game); + void leave(); + void concede(Game game); + void abort(); + void abortReset(); + void skip(); // priority, undo, ... void sendPlayerAction(PlayerAction passPriorityAction, Game game); - + int getStoredBookmark(); + void setStoredBookmark(int bookmark); + void resetStoredBookmark(Game game); void revealCards(String name, Cards cards, Game game); + void revealCards(String name, Cards cards, Game game, boolean postToLog); + void lookAtCards(String name, Card card, Game game); + void lookAtCards(String name, Cards cards, Game game); @Override Player copy(); + void restore(Player player); void setResponseString(String responseString); + void setResponseUUID(UUID responseUUID); + void setResponseBoolean(Boolean responseBoolean); + void setResponseInteger(Integer data); + void setResponseManaType(UUID manaTypePlayerId, ManaType responseManaType); boolean priority(Game game); + boolean choose(Outcome outcome, Target target, UUID sourceId, Game game); + boolean choose(Outcome outcome, Target target, UUID sourceId, Game game, Map options); + boolean choose(Outcome outcome, Cards cards, TargetCard target, Game game); + boolean chooseTarget(Outcome outcome, Target target, Ability source, Game game); + boolean chooseTarget(Outcome outcome, Cards cards, TargetCard target, Ability source, Game game); + boolean chooseTargetAmount(Outcome outcome, TargetAmount target, Ability source, Game game); + boolean chooseMulligan(Game game); + boolean chooseUse(Outcome outcome, String message, Game game); + boolean choose(Outcome outcome, Choice choice, Game game); + boolean choosePile(Outcome outcome, String message, List pile1, List pile2, Game game); + boolean playMana(ManaCost unpaid, String promptText, Game game); /** @@ -348,13 +476,20 @@ public interface Player extends MageItem, Copyable { int announceXCost(int min, int max, String message, Game game, Ability ability, VariableCost variableCost); int chooseReplacementEffect(Map abilityMap, Game game); + TriggeredAbility chooseTriggeredAbility(List abilities, Game game); + Mode chooseMode(Modes modes, Ability source, Game game); + void selectAttackers(Game game, UUID attackingPlayerId); + void selectBlockers(Game game, UUID defendingPlayerId); + UUID chooseAttackerOrder(List attacker, Game game); + /** * Choose the order in which blockers get damage assigned to + * * @param blockers list of blockers where to choose the next one from * @param combatGroup the concerning combat group * @param blockerOrder the already set order of blockers @@ -362,35 +497,52 @@ public interface Player extends MageItem, Copyable { * @return blocker next to add to the blocker order */ UUID chooseBlockerOrder(List blockers, CombatGroup combatGroup, List blockerOrder, Game game); + void assignDamage(int damage, List targets, String singleTargetName, UUID sourceId, Game game); + int getAmount(int min, int max, String message, Game game); + void sideboard(Match match, Deck deck); + void construct(Tournament tournament, Deck deck); + void pickCard(List cards, Deck deck, Draft draft); void declareAttacker(UUID attackerId, UUID defenderId, Game game, boolean allowUndo); + void declareBlocker(UUID defenderId, UUID blockerId, UUID attackerId, Game game); + List getAvailableAttackers(Game game); + List getAvailableAttackers(UUID defenderId, Game game); + List getAvailableBlockers(Game game); void beginTurn(Game game); + void endOfTurn(Game game); + void phasing(Game game); + void untap(Game game); ManaOptions getManaAvailable(Game game); + List getPlayable(Game game, boolean hidden); + List getPlayableOptions(Ability ability, Game game); - Set getPlayableInHand(Game game); + LinkedHashMap getUseableActivatedAbilities(MageObject object, Zone zone, Game game); - + void addCounters(Counter counter, Game game); + List getAttachments(); + boolean addAttachment(UUID permanentId, Game game); - boolean removeAttachment(Permanent permanent, Game game); + + boolean removeAttachment(Permanent permanent, Game game); /** * Signals that the player becomes active player in this turn. @@ -422,10 +574,13 @@ public interface Player extends MageItem, Copyable { int getPriorityTimeLeft(); void setReachedNextTurnAfterLeaving(boolean reachedNextTurnAfterLeaving); + boolean hasReachedNextTurnAfterLeaving(); + /** - * Checks if a AI player is able to join a table - * i.e. Draft - bot can not enter a table with constructed format + * Checks if a AI player is able to join a table i.e. Draft - bot can not + * enter a table with constructed format + * * @param table * @return */ @@ -433,34 +588,38 @@ public interface Player extends MageItem, Copyable { /** * Set the commanderId of the player + * * @param commanderId */ void setCommanderId(UUID commanderId); /** * Get the commanderId of the player - * @return + * + * @return */ UUID getCommanderId(); /** - * Moves cards from one zone to another - * + * Moves cards from one zone to another + * * @param cards * @param fromZone * @param toZone * @param source * @param game - * @return + * @return */ boolean moveCards(Cards cards, Zone fromZone, Zone toZone, Ability source, Game game); + boolean moveCards(List cards, Zone fromZone, Zone toZone, Ability source, Game game); + boolean moveCards(Card card, Zone fromZone, Zone toZone, Ability source, Game game); - + /** * Uses card.moveToZone and posts a inform message about moving the card * into the game log - * + * * @param card * @param sourceId * @param game @@ -468,7 +627,7 @@ public interface Player extends MageItem, Copyable { * @return */ boolean moveCardToHandWithInfo(Card card, UUID sourceId, Game game, Zone fromZone); - + /** * @param card * @param sourceId @@ -476,12 +635,13 @@ public interface Player extends MageItem, Copyable { * @param withName show the card name in the log * @param fromZone * @return - * */ + * + */ boolean moveCardToHandWithInfo(Card card, UUID sourceId, Game game, Zone fromZone, boolean withName); /** - * Uses card.moveToExile and posts a inform message about moving the card to exile - * into the game log + * Uses card.moveToExile and posts a inform message about moving the card to + * exile into the game log * * @param card * @param exileId exile zone id (optional) @@ -495,8 +655,8 @@ public interface Player extends MageItem, Copyable { boolean moveCardToExileWithInfo(Card card, UUID exileId, String exileName, UUID sourceId, Game game, Zone fromZone, boolean withName); /** - * Uses card.moveToZone and posts a inform message about moving the card to graveyard - * into the game log + * Uses card.moveToZone and posts a inform message about moving the card to + * graveyard into the game log * * @param card * @param sourceId @@ -506,10 +666,8 @@ public interface Player extends MageItem, Copyable { */ boolean moveCardToGraveyardWithInfo(Card card, UUID sourceId, Game game, Zone fromZone); - /** - * Internal used to move cards - * Use commonly player.moveCards() + * Internal used to move cards Use commonly player.moveCards() * * @param cards * @param source @@ -520,8 +678,8 @@ public interface Player extends MageItem, Copyable { boolean moveCardsToGraveyardWithInfo(List cards, Ability source, Game game, Zone fromZone); /** - * Uses card.moveToZone and posts a inform message about moving the card to graveyard - * into the game log + * Uses card.moveToZone and posts a inform message about moving the card to + * graveyard into the game log * * @param card * @param sourceId @@ -533,9 +691,9 @@ public interface Player extends MageItem, Copyable { */ boolean moveCardToLibraryWithInfo(Card card, UUID sourceId, Game game, Zone fromZone, boolean toTop, boolean withName); - /** - * Uses putOntoBattlefield and posts also a info message about in the game log + * Uses putOntoBattlefield and posts also a info message about in the game + * log * * @param card * @param game @@ -544,9 +702,10 @@ public interface Player extends MageItem, Copyable { * @return */ boolean putOntoBattlefieldWithInfo(Card card, Game game, Zone fromZone, UUID sourceId); - + /** - * Uses putOntoBattlefield and posts also a info message about in the game log + * Uses putOntoBattlefield and posts also a info message about in the game + * log * * @param card * @param game @@ -558,7 +717,8 @@ public interface Player extends MageItem, Copyable { boolean putOntoBattlefieldWithInfo(Card card, Game game, Zone fromZone, UUID sourceId, boolean tapped); /** - * Uses putOntoBattlefield and posts also a info message about in the game log + * Uses putOntoBattlefield and posts also a info message about in the game + * log * * @param card * @param game @@ -569,10 +729,10 @@ public interface Player extends MageItem, Copyable { * @return */ boolean putOntoBattlefieldWithInfo(Card card, Game game, Zone fromZone, UUID sourceId, boolean tapped, boolean facedown); - + /** * Checks if the playerToCheckId is from an opponent in range - * + * * @param playerToCheckId * @param game * @return true if playerToCheckId belongs to an opponent @@ -580,30 +740,38 @@ public interface Player extends MageItem, Copyable { boolean hasOpponent(UUID playerToCheckId, Game game); /** - * Free resources on match end + * Free resources on match end */ void cleanUpOnMatchEnd(); /** - * If the next cast spell has the set sourceId, the spell will - * be cast without mana. + * If the next cast spell has the set sourceId, the spell will be cast + * without mana. * * @param sourceId the source that can be cast without mana - * @param manaCosts alternate ManaCost, null if it can be cast without mana cost + * @param manaCosts alternate ManaCost, null if it can be cast without mana + * cost */ void setCastSourceIdWithAlternateMana(UUID sourceId, ManaCosts manaCosts); + UUID getCastSourceIdWithAlternateMana(); + ManaCosts getCastSourceIdManaCosts(); // permission handling to show hand cards void addPermissionToShowHandCards(UUID watcherUserId); + boolean hasUserPermissionToSeeHand(UUID userId); + void revokePermissionToSeeHandCards(); + boolean isRequestToShowHandCardsAllowed(); + Set getUsersAllowedToSeeHandCards(); boolean isInPayManaMode(); void setMatchPlayer(MatchPlayer matchPlayer); + MatchPlayer getMatchPlayer(); } diff --git a/Mage/src/mage/players/PlayerImpl.java b/Mage/src/mage/players/PlayerImpl.java index d87e64e5401..fdbfe6d6db5 100644 --- a/Mage/src/mage/players/PlayerImpl.java +++ b/Mage/src/mage/players/PlayerImpl.java @@ -227,6 +227,8 @@ public abstract class PlayerImpl implements Player, Serializable { protected UserData userData; protected MatchPlayer matchPlayer; + protected String flagName; + /** * During some steps we can't play anything */ @@ -571,7 +573,9 @@ public abstract class PlayerImpl implements Player, Serializable { } /** - * returns true if the player has the control itself - false if the player is controlled by another player + * returns true if the player has the control itself - false if the player + * is controlled by another player + * * @return */ @Override @@ -701,7 +705,7 @@ public abstract class PlayerImpl implements Player, Serializable { if (random) { for (int i = 0; i < amount; i++) { Card card = this.getHand().getRandom(game); - if(card != null) { + if (card != null) { discardedCards.add(card); discard(card, source, game); } @@ -917,7 +921,6 @@ public abstract class PlayerImpl implements Player, Serializable { return castSourceIdManaCosts; } - @Override public boolean isInPayManaMode() { return payManaMode; @@ -939,7 +942,7 @@ public abstract class PlayerImpl implements Player, Serializable { // some effects set sourceId to cast without paying mana costs if (ability.getSourceId().equals(getCastSourceIdWithAlternateMana())) { ManaCosts alternateCosts = getCastSourceIdManaCosts(); - Ability spellAbility = spell.getSpellAbility(); + Ability spellAbility = spell.getSpellAbility(); if (alternateCosts == null) { noMana = true; } else { @@ -1096,7 +1099,6 @@ public abstract class PlayerImpl implements Player, Serializable { } if (ability instanceof PlayLandAbility) { - Card card = game.getCard(ability.getSourceId()); result = playLand(card, game); } else { @@ -1338,7 +1340,7 @@ public abstract class PlayerImpl implements Player, Serializable { game.getState().getLookedAt(this.playerId).add(name, card); game.fireUpdatePlayersEvent(); } - + @Override public void lookAtCards(String name, Cards cards, Game game) { game.getState().getLookedAt(this.playerId).add(name, cards); @@ -1679,7 +1681,7 @@ public abstract class PlayerImpl implements Player, Serializable { } else if (source instanceof Card) { sourceAbilities = ((Card) source).getAbilities(game); sourceControllerId = ((Card) source).getOwnerId(); - } else if (source instanceof CommandObject){ + } else if (source instanceof CommandObject) { sourceControllerId = ((CommandObject) source).getControllerId(); sourceAbilities = ((CommandObject) source).getAbilities(); } @@ -2033,7 +2035,7 @@ public abstract class PlayerImpl implements Player, Serializable { } Permanent attacker = game.getPermanent(attackerId); if (attacker != null && attacker.canAttack(defenderId, game) && attacker.getControllerId().equals(playerId)) { - if(!game.getCombat().declareAttacker(attackerId, defenderId, playerId, game)) { + if (!game.getCombat().declareAttacker(attackerId, defenderId, playerId, game)) { game.undo(playerId); } } @@ -2285,64 +2287,64 @@ public abstract class PlayerImpl implements Player, Serializable { } protected boolean canPlayCardByAlternateCost(Card sourceObject, ManaOptions available, Ability ability, Game game) { - if (sourceObject != null && !(sourceObject instanceof Permanent)) { - for (Ability alternateSourceCostsAbility : sourceObject.getAbilities()) { - // if cast for noMana no Alternative costs are allowed - if (alternateSourceCostsAbility instanceof AlternativeSourceCosts) { - if (((AlternativeSourceCosts) alternateSourceCostsAbility).isAvailable(ability, game)) { - if (alternateSourceCostsAbility.getCosts().canPay(ability, playerId, playerId, game)) { - ManaCostsImpl manaCosts = new ManaCostsImpl(); - for (Cost cost : alternateSourceCostsAbility.getCosts()) { - if (cost instanceof ManaCost) { - manaCosts.add((ManaCost) cost); - } - } + if (sourceObject != null && !(sourceObject instanceof Permanent)) { + for (Ability alternateSourceCostsAbility : sourceObject.getAbilities()) { + // if cast for noMana no Alternative costs are allowed + if (alternateSourceCostsAbility instanceof AlternativeSourceCosts) { + if (((AlternativeSourceCosts) alternateSourceCostsAbility).isAvailable(ability, game)) { + if (alternateSourceCostsAbility.getCosts().canPay(ability, playerId, playerId, game)) { + ManaCostsImpl manaCosts = new ManaCostsImpl(); + for (Cost cost : alternateSourceCostsAbility.getCosts()) { + if (cost instanceof ManaCost) { + manaCosts.add((ManaCost) cost); + } + } - if (manaCosts.size() == 0) { - return true; - } else { - for (Mana mana : manaCosts.getOptions()) { - for (Mana avail : available) { - if (mana.enough(avail)) { - return true; - } - } - } - } - } - } - } - } + if (manaCosts.size() == 0) { + return true; + } else { + for (Mana mana : manaCosts.getOptions()) { + for (Mana avail : available) { + if (mana.enough(avail)) { + return true; + } + } + } + } + } + } + } + } - // controller specific alternate spell costs - for (AlternativeSourceCosts alternateSourceCosts: getAlternativeSourceCosts()) { - if (alternateSourceCosts instanceof Ability) { - if (alternateSourceCosts.isAvailable(ability, game)) { - if (((Ability) alternateSourceCosts).getCosts().canPay(ability, playerId, playerId, game)) { - ManaCostsImpl manaCosts = new ManaCostsImpl(); - for (Cost cost : ((Ability) alternateSourceCosts).getCosts()) { - if (cost instanceof ManaCost) { - manaCosts.add((ManaCost) cost); - } - } + // controller specific alternate spell costs + for (AlternativeSourceCosts alternateSourceCosts : getAlternativeSourceCosts()) { + if (alternateSourceCosts instanceof Ability) { + if (alternateSourceCosts.isAvailable(ability, game)) { + if (((Ability) alternateSourceCosts).getCosts().canPay(ability, playerId, playerId, game)) { + ManaCostsImpl manaCosts = new ManaCostsImpl(); + for (Cost cost : ((Ability) alternateSourceCosts).getCosts()) { + if (cost instanceof ManaCost) { + manaCosts.add((ManaCost) cost); + } + } - if (manaCosts.size() == 0) { - return true; - } else { - for (Mana mana : manaCosts.getOptions()) { - for (Mana avail : available) { - if (mana.enough(avail)) { - return true; - } - } - } - } - } - } - } - } - } - return false; + if (manaCosts.size() == 0) { + return true; + } else { + for (Mana mana : manaCosts.getOptions()) { + for (Mana avail : available) { + if (mana.enough(avail)) { + return true; + } + } + } + } + } + } + } + } + } + return false; } protected boolean canLandPlayAlternateSourceCostsAbility(Card sourceObject, ManaOptions available, Ability ability, Game game) { @@ -2847,7 +2849,7 @@ public abstract class PlayerImpl implements Player, Serializable { @Override public boolean moveCards(Cards cards, Zone fromZone, Zone toZone, Ability source, Game game) { ArrayList cardList = new ArrayList<>(); - for (UUID cardId: cards) { + for (UUID cardId : cards) { if (fromZone.equals(Zone.BATTLEFIELD)) { Permanent permanent = game.getPermanent(cardId); if (permanent != null) { @@ -2857,7 +2859,7 @@ public abstract class PlayerImpl implements Player, Serializable { Card card = game.getCard(cardId); if (card != null) { cardList.add(card); - } + } } } return moveCards(cardList, fromZone, toZone, source, game); @@ -2878,10 +2880,10 @@ public abstract class PlayerImpl implements Player, Serializable { return true; } game.fireEvent(new ZoneChangeGroupEvent(cards, source == null ? null : source.getSourceId(), this.getId(), fromZone, toZone)); - switch(toZone) { + switch (toZone) { case EXILED: boolean result = false; - for(Card card: cards) { + for (Card card : cards) { result |= moveCardToExileWithInfo(card, null, "", source == null ? null : source.getSourceId(), game, fromZone, true); } return result; @@ -2889,7 +2891,7 @@ public abstract class PlayerImpl implements Player, Serializable { return moveCardsToGraveyardWithInfo(cards, source, game, fromZone); case HAND: result = false; - for(Card card: cards) { + for (Card card : cards) { result |= moveCardToHandWithInfo(card, source == null ? null : source.getSourceId(), game, fromZone); } return result; @@ -2912,7 +2914,7 @@ public abstract class PlayerImpl implements Player, Serializable { } if (!game.isSimulation()) { StringBuilder sb = new StringBuilder(this.getLogName()).append(" puts ").append(withName ? card.getLogName() : "a face down card"); - switch(fromZone) { + switch (fromZone) { case EXILED: sb.append(" from exile zone "); break; @@ -3051,8 +3053,8 @@ public abstract class PlayerImpl implements Player, Serializable { if (card instanceof PermanentCard) { card = game.getCard(card.getId()); } - game.informPlayers(this.getLogName() + " moves " + (withName ? card.getLogName() : "a card face down") + " " + - (fromZone != null ? "from " + fromZone.toString().toLowerCase(Locale.ENGLISH) + " " : "") + "to the exile zone"); + game.informPlayers(this.getLogName() + " moves " + (withName ? card.getLogName() : "a card face down") + " " + + (fromZone != null ? "from " + fromZone.toString().toLowerCase(Locale.ENGLISH) + " " : "") + "to the exile zone"); } result = true; } @@ -3075,7 +3077,7 @@ public abstract class PlayerImpl implements Player, Serializable { if (card.putOntoBattlefield(game, fromZone, sourceId, this.getId(), tapped, facedown)) { if (!game.isSimulation()) { game.informPlayers(new StringBuilder(this.getLogName()) - .append(" puts ").append(facedown ? "a card face down ":card.getLogName()) + .append(" puts ").append(facedown ? "a card face down " : card.getLogName()) .append(" from ").append(fromZone.toString().toLowerCase(Locale.ENGLISH)).append(" ") .append("onto the Battlefield").toString()); } @@ -3129,7 +3131,6 @@ public abstract class PlayerImpl implements Player, Serializable { usersAllowedToSeeHandCards.add(watcherUserId); } - @Override public boolean isRequestToShowHandCardsAllowed() { return userData.isAllowRequestShowHandCards(); diff --git a/Mage/src/mage/players/net/UserData.java b/Mage/src/mage/players/net/UserData.java index 101325ec660..ca11e192381 100644 --- a/Mage/src/mage/players/net/UserData.java +++ b/Mage/src/mage/players/net/UserData.java @@ -18,7 +18,7 @@ public class UserData implements Serializable { protected String flagName; protected boolean askMoveToGraveOrder; - public UserData(UserGroup userGroup, int avatarId, boolean showAbilityPickerForced, + public UserData(UserGroup userGroup, int avatarId, boolean showAbilityPickerForced, boolean allowRequestShowHandCards, boolean confirmEmptyManaPool, UserSkipPrioritySteps userSkipPrioritySteps, String flagName, boolean askMoveToGraveOrder) { this.groupId = userGroup.getGroupId(); @@ -31,6 +31,21 @@ public class UserData implements Serializable { this.askMoveToGraveOrder = askMoveToGraveOrder; } + public void update(UserData userData) { + this.groupId = userData.groupId; + this.avatarId = userData.avatarId; + this.showAbilityPickerForced = userData.showAbilityPickerForced; + this.allowRequestShowHandCards = userData.allowRequestShowHandCards; + this.userSkipPrioritySteps = userData.userSkipPrioritySteps; + this.confirmEmptyManaPool = userData.confirmEmptyManaPool; + this.flagName = userData.flagName; + this.askMoveToGraveOrder = userData.askMoveToGraveOrder; + } + + public static UserData getDefaultUserDataView() { + return new UserData(UserGroup.DEFAULT, 0, false, false, true, null, "world.png", false); + } + public void setGroupId(int groupId) { this.groupId = groupId; } @@ -90,5 +105,5 @@ public class UserData implements Serializable { public void setAskMoveToGraveOrder(boolean askMoveToGraveOrder) { this.askMoveToGraveOrder = askMoveToGraveOrder; } - + } diff --git a/Mage/src/mage/players/net/UserGroup.java b/Mage/src/mage/players/net/UserGroup.java index 97a39da1513..58a61d3dff4 100644 --- a/Mage/src/mage/players/net/UserGroup.java +++ b/Mage/src/mage/players/net/UserGroup.java @@ -7,6 +7,7 @@ public enum UserGroup { COMPUTER(0), PLAYER(1), + DEFAULT(2), MAGE(3), ADMIN(7), OWNER(15);