Some changes to userData handling. Added country flag to some dialogs. Saved and restored some more table columns width and order information.

This commit is contained in:
LevelX2 2015-06-28 00:10:38 +02:00
parent cb3b5f895b
commit 87f3978589
32 changed files with 1982 additions and 1699 deletions

View file

@ -142,6 +142,7 @@ public class ChatPanel extends javax.swing.JPanel {
*/
/**
* Creates new form ChatPanel
*
* @param addPlayersTab
*/
public ChatPanel(boolean addPlayersTab) {
@ -262,6 +263,7 @@ public class ChatPanel extends javax.swing.JPanel {
sb.append("</font>");
return sb.toString();
}
public String getText() {
return txtConversation.getText();
}
@ -326,7 +328,7 @@ 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<RoomUsersView> roomUserInfoList) throws MageRemoteException {
@ -337,9 +339,9 @@ public class ChatPanel extends javax.swing.JPanel {
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();
}
@ -397,8 +399,6 @@ public class ChatPanel extends javax.swing.JPanel {
return false;
}
}
public void clear() {

View file

@ -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<String> 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);
@ -129,7 +134,11 @@ public class AddLandDialog extends MageDialog {
criteria.rarities(Rarity.LAND).name(landName);
List<CardInfo> 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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
@ -324,7 +333,9 @@ public class AddLandDialog extends MageDialog {
int white = 0;
Set<Card> 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();
@ -335,13 +346,17 @@ public class AddLandDialog extends MageDialog {
}
int total = red + green + black + blue + white;
int redcards = Math.round(land_number * ((float) red / (float) total));
total -= red; land_number -= redcards;
total -= red;
land_number -= redcards;
int greencards = Math.round(land_number * ((float) green / (float) total));
total -= green; land_number -= greencards;
total -= green;
land_number -= greencards;
int blackcards = Math.round(land_number * ((float) black / (float) total));
total -= black; land_number -= blackcards;
total -= black;
land_number -= blackcards;
int bluecards = Math.round(land_number * ((float) blue / (float) total));
total -= blue; land_number -= bluecards;
total -= blue;
land_number -= bluecards;
int whitecards = land_number;
spnMountain.setValue(redcards);
spnForest.setValue(greencards);

View file

@ -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;
/**
@ -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";
@ -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";
@ -238,7 +247,6 @@ public class PreferencesDialog extends javax.swing.JDialog {
public static final String KEY_CONNECT_AUTO_CONNECT = "autoConnect";
public static final String KEY_CONNECT_FLAG = "connectFlag";
private static final Map<String, String> cache = new HashMap<>();
private static final Boolean UPDATE_CACHE_POLICY = Boolean.TRUE;
@ -280,6 +288,7 @@ public class PreferencesDialog extends javax.swing.JDialog {
}
private final JFileChooser fc_i = new JFileChooser();
{
fc_i.setAcceptAllFileFilterUsed(false);
fc_i.addChoosableFileFilter(new ImageFileFilter());
@ -294,8 +303,8 @@ public class PreferencesDialog extends javax.swing.JDialog {
return true;
}
if (filename != null) {
if(filename.endsWith(".jpg") || filename.endsWith(".jpeg") ||
filename.endsWith(".png") || filename.endsWith(".bmp")){
if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")
|| filename.endsWith(".png") || filename.endsWith(".bmp")) {
return true;
}
}
@ -308,8 +317,6 @@ public class PreferencesDialog extends javax.swing.JDialog {
}
}
/**
* Creates new form PreferencesDialog
*
@ -327,10 +334,10 @@ public class PreferencesDialog extends javax.swing.JDialog {
}
/** 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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
@ -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);
}
@ -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();
@ -2301,6 +2305,7 @@ public class PreferencesDialog extends javax.swing.JDialog {
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) {
@ -2416,8 +2421,8 @@ public class PreferencesDialog extends javax.swing.JDialog {
}
}
public static UserDataView getUserData(){
return new UserDataView(
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"),

View file

@ -31,20 +31,24 @@
*
* 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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
@ -248,8 +267,7 @@ public class TableWaitingDialog extends MageDialog {
if (session.startMatch(roomId, tableId)) {
closeDialog();
}
}
else {
} else {
if (session.startTournament(roomId, tableId)) {
closeDialog();
}
@ -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();
}
}
@ -351,8 +370,13 @@ class TableWaitModel extends AbstractTableModel {
@Override
public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case 1:
return Icon.class;
default:
return String.class;
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
@ -422,7 +446,6 @@ class UpdateSeatsTask extends SwingWorker<Void, TableView> {
return playerCount;
}
@Override
protected void done() {
try {
@ -431,7 +454,8 @@ class UpdateSeatsTask extends SwingWorker<Void, TableView> {
logger.fatal("Update Seats Task error", ex);
} catch (ExecutionException ex) {
logger.fatal("Update Seats Task error", ex);
} catch (CancellationException ex) {}
} catch (CancellationException ex) {
}
}
}

View file

@ -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;
@ -80,7 +79,9 @@ public class PlayAreaPanel extends javax.swing.JPanel {
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
@ -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();
}
@ -110,7 +111,6 @@ public class PlayAreaPanel extends javax.swing.JPanel {
battlefieldPanel.cleanUp();
playerPanel.cleanUp();
for (ActionListener al : btnCheat.getActionListeners()) {
btnCheat.removeActionListener(al);
}
@ -187,7 +187,6 @@ 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);
@ -364,8 +363,6 @@ public class PlayAreaPanel extends javax.swing.JPanel {
}
JMenu concedeMenu = new JMenu("Concede");
concedeMenu.setMnemonic(KeyEvent.VK_C);
popupMenu.add(concedeMenu);
@ -406,7 +403,6 @@ public class PlayAreaPanel extends javax.swing.JPanel {
concedeMenu.add(menuItem);
menuItem.addActionListener(concedeListener);
battlefieldPanel.getMainPanel().addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent Me) {
@ -461,6 +457,7 @@ 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) {
@ -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());
}
}
@ -525,7 +521,6 @@ 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()
@ -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));

View file

@ -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;

View file

@ -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();
@ -88,16 +99,18 @@ public class TournamentPanel extends javax.swing.JPanel {
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)
{
public void actionPerformed(ActionEvent e) {
int modelRow = Integer.valueOf(e.getActionCommand());
String state = (String) tableMatches.getValueAt(modelRow, 2);
@ -105,7 +118,6 @@ public class TournamentPanel extends javax.swing.JPanel {
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,6 +194,9 @@ 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();
@ -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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//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 "";
@ -578,8 +595,13 @@ class TournamentPlayersTableModel extends AbstractTableModel {
@Override
public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Icon.class;
default:
return String.class;
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
@ -709,7 +731,8 @@ class UpdateTournamentTask extends SwingWorker<Void, TournamentView> {
logger.fatal("Update Tournament Task error", ex);
} catch (ExecutionException ex) {
logger.fatal("Update Tournament Task error", ex);
} catch (CancellationException ex) {}
} catch (CancellationException ex) {
}
}
}

View file

@ -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;
/**
*
@ -33,9 +32,13 @@ public class TableUtil {
if (widths != null && widths.length > i) {
width = widths[i];
}
if (table.getColumnModel().getColumnCount() >= i) {
TableColumn column = table.getColumnModel().getColumn(i++);
column.setWidth(width);
column.setPreferredWidth(width);
} else {
break;
}
}
// set the column order
@ -69,7 +72,6 @@ public class TableUtil {
}
public static int[] getIntArrayFromString(String stringData) {
int[] intArray = null;
if (stringData != null && !stringData.isEmpty()) {
@ -79,7 +81,8 @@ 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;

View file

@ -25,17 +25,12 @@
* 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;
/**
*
@ -43,38 +38,15 @@ import org.apache.log4j.Logger;
*/
public class CountryCellRenderer extends DefaultTableCellRenderer {
private static final Logger logger = Logger.getLogger(CountryCellRenderer.class);
private final Map<String, ImageIcon> flagIconCache = new HashMap<>();
private final Map<String, String> 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("");
if (value == null || ((String) value).isEmpty()) {
value = (String) "world";
}
label.setToolTipText(CountryUtil.getCountryName((String) value));
label.setIcon(CountryUtil.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);
}
}
return flagIcon;
}
}

View file

@ -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<String, ImageIcon> flagIconCache = new HashMap<>();
private static final Map<String, String> 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);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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<ExpansionInfo> getMissingExpansionData(List<String> codes);
List<CardInfo> getMissingCardsData(List<String> 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<RoomUsersView> getRoomUsers(UUID roomId) throws MageException;
List<MatchView> 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<TableView> 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<UUID> 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<UserView> 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;
}

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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,7 +53,7 @@ public class Connection {
private int clientCardDatabaseVersion;
private boolean forceDBComparison;
private UserDataView userData;
private UserData userData;
// private int avatarId;
// private boolean showAbilityPickerForced;
@ -63,7 +61,6 @@ public class Connection {
// private boolean confirmEmptyManaPool;
// private String flagName;
// private UserSkipPrioritySteps userSkipPrioritySteps;
private static final String serialization = "?serializationtype=jboss";
private static final String transport = "bisocket";
@ -119,6 +116,7 @@ public class Connection {
}
public enum ProxyType {
SOCKS("Socks"), HTTP("HTTP"), NONE("None");
private final String text;
@ -224,11 +222,11 @@ public class Connection {
return null;
}
public void setUserData(UserDataView userData) {
public void setUserData(UserData userData) {
this.userData = userData;
}
public UserDataView getUserData() {
public UserData getUserData() {
return userData;
}

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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;
@ -223,24 +221,30 @@ public class SessionImpl implements Session {
*/
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.
// 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");
@ -350,8 +354,8 @@ public class SessionImpl implements Session {
List<CardInfo> 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) {
@ -450,6 +455,7 @@ public class SessionImpl implements Session {
}
class CallbackHandler implements InvokerCallbackHandler {
@Override
public void handleCallback(Callback callback) throws HandleCallbackException {
//logger.info("callback handler");
@ -502,7 +508,6 @@ public class SessionImpl implements Session {
return serverState.getDraftCubes();
}
@Override
public List<TournamentTypeView> getTournamentTypes() {
return serverState.getTournamentTypes();
@ -1020,6 +1025,7 @@ public class SessionImpl implements Session {
/**
* Remove table - called from admin console
*
* @param tableId
* @return
*/
@ -1107,7 +1113,6 @@ public class SessionImpl implements Session {
// }
// return false;
// }
@Override
public boolean submitDeck(UUID tableId, DeckCardLists deck) {
try {
@ -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);
@ -1448,7 +1452,6 @@ public class SessionImpl implements Session {
}
class MageAuthenticator extends Authenticator {
private final String username;

View file

@ -27,7 +27,7 @@
*/
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);
}

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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<UUID, PermanentView> battlefield = new LinkedHashMap<>();
private final CardView topCard;
private final UserDataView userDataView;
private final UserData userData;
private final List<CommandObjectView> commandList = new ArrayList<>();
private final List<UUID> attachments = new ArrayList<>();
private final int statesSavedSize;
@ -89,9 +90,9 @@ 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)) {
@ -110,12 +111,12 @@ public class PlayerView implements Serializable {
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()) {
@ -127,8 +128,7 @@ public class PlayerView implements Serializable {
commandList.add(new EmblemView(emblem, sourceCard));
}
}
}
else if(commandObject instanceof Commander){
} else if (commandObject instanceof Commander) {
Commander commander = (Commander) commandObject;
if (commander.getControllerId().equals(this.playerId)) {
Card sourceCard = game.getCard(commander.getSourceId());
@ -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<CommandObjectView> getCommadObjectList() {

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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;
}
}

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.view;
import java.io.Serializable;
@ -36,8 +35,10 @@ import mage.game.tournament.TournamentPlayer;
* @author BetaSteward_at_googlemail.com
*/
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;
@ -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;
}
}

View file

@ -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,8 +21,8 @@ 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,

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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
@ -172,8 +170,10 @@ public class ComputerPlayer extends PlayerImpl implements Player {
private transient List<ColoredManaSymbol> 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<>();
@ -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--) {
@ -568,8 +566,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
boolean outcomeTargets = true;
if (outcome.isGood()) {
targets = threats(abilityControllerId, source == null ? null : source.getSourceId(), ((TargetPermanent) target).getFilter(), game, target.getTargets());
}
else {
} else {
targets = threats(opponentId, source == null ? null : source.getSourceId(), ((TargetPermanent) target).getFilter(), game, target.getTargets());
}
if (targets.isEmpty() && target.isRequired(source)) {
@ -593,8 +590,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
TargetCreatureOrPlayer t = ((TargetCreatureOrPlayer) target);
if (outcome.isGood()) {
targets = threats(abilityControllerId, source.getSourceId(), ((FilterCreatureOrPlayer) t.getFilter()).getCreatureFilter(), game, target.getTargets());
}
else {
} else {
targets = threats(opponentId, source.getSourceId(), ((FilterCreatureOrPlayer) t.getFilter()).getCreatureFilter(), game, target.getTargets());
}
@ -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;
@ -631,8 +626,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;
@ -703,8 +697,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
boolean outcomeTargets = true;
if (outcome.isGood()) {
targets = threats(abilityControllerId, source == null ? null : source.getSourceId(), ((TargetSpellOrPermanent) target).getPermanentFilter(), game, target.getTargets());
}
else {
} else {
targets = threats(opponentId, source == null ? null : source.getSourceId(), ((TargetSpellOrPermanent) target).getPermanentFilter(), game, target.getTargets());
}
if (targets.isEmpty() && target.isRequired(source)) {
@ -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,8 +834,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
List<Permanent> 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) {
@ -949,8 +938,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
}
break;
}
}
else {
} else {
//respond to opponent events
switch (game.getTurn().getStepType()) {
case UPKEEP:
@ -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);
}
}
@ -1059,18 +1046,16 @@ public class ComputerPlayer extends PlayerImpl implements Player {
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);
}
@ -1093,8 +1078,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
}
if (abilityOptions.size() == 0) {
playableAbilities.add(ability);
}
else {
} else {
for (Mana mana : abilityOptions) {
for (Mana avail : available) {
if (mana.enough(avail)) {
@ -1112,8 +1096,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
ManaOptions abilityOptions = ability.getManaCosts().getOptions();
if (abilityOptions.size() == 0) {
playableAbilities.add(ability);
}
else {
} else {
for (Mana mana : abilityOptions) {
for (Mana avail : available) {
if (mana.enough(avail)) {
@ -1147,8 +1130,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
if (unpaid instanceof ManaCosts) {
cost = ((ManaCosts<ManaCost>) unpaid).get(0);
producers = getSortedProducers((ManaCosts) unpaid, game);
}
else {
} else {
cost = unpaid;
producers = this.getAvailableManaProducers(game);
producers.addAll(this.getAvailableManaProducersWithCost(game));
@ -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
@ -1246,8 +1230,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
score += permanent.getAbilities().getActivatedAbilities(Zone.BATTLEFIELD).size();
if (!permanent.getCardType().contains(CardType.LAND)) {
score += 2;
}
else if(permanent.getCardType().contains(CardType.CREATURE)) {
} else if (permanent.getCardType().contains(CardType.CREATURE)) {
score += 2;
}
}
@ -1293,7 +1276,6 @@ public class ComputerPlayer extends PlayerImpl implements Player {
return value;
}
@Override
public void abort() {
abort = true;
@ -1413,6 +1395,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
}
return choice.isChosen();
}
@Override
public boolean chooseTarget(Outcome outcome, Cards cards, TargetCard target, Ability source, Game game) {
log.debug("chooseTarget");
@ -1476,11 +1459,9 @@ public class ComputerPlayer extends PlayerImpl implements Player {
List<Permanent> 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) {
@ -1653,7 +1634,10 @@ public class ComputerPlayer extends PlayerImpl implements Player {
List<CardInfo> 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++) {
@ -1861,7 +1845,6 @@ public class ComputerPlayer extends PlayerImpl implements Player {
}
}
String colors = "not chosen yet";
// remember card if colors are not chosen yet
if (chosenColors == null) {
@ -1893,10 +1876,10 @@ 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
* 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<ColoredManaSymbol> chooseDeckColorsIfPossible() {
@ -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;
}
}
@ -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);

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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;
@ -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);
}
});
}
@ -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;
@ -431,8 +423,7 @@ public class MageServerImpl implements MageServer {
}
}
);
}
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;
@ -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;
@ -1076,8 +1061,7 @@ public class MageServerImpl implements MageServer {
}
}
);
}
catch (Exception ex) {
} catch (Exception ex) {
handleException(ex);
}
} else {

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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;
@ -149,70 +147,40 @@ public class Session {
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);
user.getUserData().update(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());
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() {
@ -243,8 +211,7 @@ public class Session {
} catch (InterruptedException ex) {
logger.error("SESSION LOCK lost connection - userId: " + userId, ex);
}
finally {
} finally {
if (lockSet) {
lock.unlock();
logger.trace("SESSION LOCK UNLOCK sessionId: " + sessionId);
@ -265,8 +232,7 @@ public class Session {
UserManager.getInstance().removeUser(userId, reason);
} catch (InterruptedException ex) {
logger.error("SESSION LOCK - kill: userId " + userId, ex);
}
finally {
} finally {
if (lockSet) {
lock.unlock();
logger.debug("SESSION LOCK UNLOCK sessionId: " + sessionId);

View file

@ -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;
@ -102,10 +102,10 @@ 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;
@ -155,6 +155,7 @@ public class SessionManager {
/**
* Admin requested the disconnect of a user
*
* @param sessionId
* @param userSessionId
*/

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.server;
import java.util.Map;
@ -103,8 +102,7 @@ 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);
@ -123,8 +121,7 @@ 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);
@ -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);
}
@ -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) {
@ -592,7 +586,6 @@ public class TableController {
}
ServerMessagesUtil.getInstance().incGamesStarted();
// log about game started
logger.info("GAME started " + match.getGame().getId() + " [" + match.getName() + "] " + creator + " - " + opponent.toString());
logger.debug("- matchId: " + match.getId() + " [" + match.getName() + "]");
@ -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());
@ -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);
@ -715,8 +706,7 @@ public class TableController {
} else {
closeTable();
}
}
else {
} else {
closeTable();
}
} catch (GameException ex) {
@ -749,9 +739,10 @@ 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() {
@ -928,11 +919,11 @@ public class TableController {
}
if (matchPlayer.getPlayer().isHuman()) {
humanPlayers++;
if ((table.getState().equals(TableState.WAITING) ||
table.getState().equals(TableState.STARTING) ||
table.getState().equals(TableState.READY_TO_START)) ||
!match.isDoneSideboarding() ||
(!matchPlayer.hasQuit() && match.getGame() != null && matchPlayer.getPlayer().isInGame())) {
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());

View file

@ -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) {
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;
}

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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
@ -458,13 +456,13 @@ public class TournamentController {
}
/**
* 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<UUID, UUID> entry : userPlayerMap.entrySet()) {

View file

@ -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;
@ -157,7 +154,8 @@ 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;

View file

@ -25,12 +25,9 @@
* 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;
@ -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) {

View file

@ -25,7 +25,6 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.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,37 +82,66 @@ import mage.util.Copyable;
public interface Player extends MageItem, Copyable<Player> {
boolean isHuman();
String getName();
String getLogName();
RangeOfInfluence getRange();
Library getLibrary();
Cards getSideboard();
Graveyard getGraveyard();
Abilities<Ability> 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<UUID> appliedEffects);
// to handle rule changing effects (613.10)
boolean isCanLoseLife();
void setCanLoseLife(boolean canLoseLife);
void setCanGainLife(boolean canGainLife);
boolean isCanGainLife();
void setCanPayLifeCost(boolean canPayLifeCost);
boolean canPayLifeCost();
void setCanPaySacrificeCost(boolean canPaySacrificeCost);
boolean canPaySacrificeCost();
void setLifeTotalCanChange(boolean lifeTotalCanChange);
boolean isLifeTotalCanChange();
void setLoseByZeroOrLessLife(boolean loseByZeroOrLessLife);
boolean canLoseByZeroOrLessLife();
void setPlayCardsFromGraveyard(boolean playCardsFromGraveyard);
boolean canPlayCardsFromGraveyard();
/**
@ -124,64 +151,101 @@ public interface Player extends MageItem, Copyable<Player> {
*/
List<AlternativeSourceCosts> 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<UUID> getInRange();
boolean isTopCardRevealed();
void setTopCardRevealed(boolean topCardRevealed);
/**
* Get data from the client Preferences (e.g. avatarId or showAbilityPickerForce)
* 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<Player> {
/**
* Defines player whose turn this player controls at the moment.
*
* @param game
* @param playerId
*/
@ -211,7 +276,8 @@ public interface Player extends MageItem, Copyable<Player> {
/**
* 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,39 +286,59 @@ public interface Player extends MageItem, Copyable<Player> {
/**
* 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<UUID> 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
@ -261,62 +347,104 @@ public interface Player extends MageItem, Copyable<Player> {
* @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<UUID> 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<String, Serializable> 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<? extends Card> pile1, List<? extends Card> pile2, Game game);
boolean playMana(ManaCost unpaid, String promptText, Game game);
/**
@ -348,13 +476,20 @@ public interface Player extends MageItem, Copyable<Player> {
int announceXCost(int min, int max, String message, Game game, Ability ability, VariableCost variableCost);
int chooseReplacementEffect(Map<String, String> abilityMap, Game game);
TriggeredAbility chooseTriggeredAbility(List<TriggeredAbility> 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<Permanent> 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,34 +497,51 @@ public interface Player extends MageItem, Copyable<Player> {
* @return blocker next to add to the blocker order
*/
UUID chooseBlockerOrder(List<Permanent> blockers, CombatGroup combatGroup, List<UUID> blockerOrder, Game game);
void assignDamage(int damage, List<UUID> 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<Card> 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<Permanent> getAvailableAttackers(Game game);
List<Permanent> getAvailableAttackers(UUID defenderId, Game game);
List<Permanent> getAvailableBlockers(Game game);
void beginTurn(Game game);
void endOfTurn(Game game);
void phasing(Game game);
void untap(Game game);
ManaOptions getManaAvailable(Game game);
List<Ability> getPlayable(Game game, boolean hidden);
List<Ability> getPlayableOptions(Ability ability, Game game);
Set<UUID> getPlayableInHand(Game game);
LinkedHashMap<UUID, ActivatedAbility> getUseableActivatedAbilities(MageObject object, Zone zone, Game game);
void addCounters(Counter counter, Game game);
List<UUID> getAttachments();
boolean addAttachment(UUID permanentId, Game game);
boolean removeAttachment(Permanent permanent, Game game);
/**
@ -422,10 +574,13 @@ public interface Player extends MageItem, Copyable<Player> {
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,12 +588,14 @@ public interface Player extends MageItem, Copyable<Player> {
/**
* Set the commanderId of the player
*
* @param commanderId
*/
void setCommanderId(UUID commanderId);
/**
* Get the commanderId of the player
*
* @return
*/
UUID getCommanderId();
@ -454,7 +611,9 @@ public interface Player extends MageItem, Copyable<Player> {
* @return
*/
boolean moveCards(Cards cards, Zone fromZone, Zone toZone, Ability source, Game game);
boolean moveCards(List<Card> cards, Zone fromZone, Zone toZone, Ability source, Game game);
boolean moveCards(Card card, Zone fromZone, Zone toZone, Ability source, Game game);
/**
@ -476,12 +635,13 @@ public interface Player extends MageItem, Copyable<Player> {
* @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<Player> {
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<Player> {
*/
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<Player> {
boolean moveCardsToGraveyardWithInfo(List<Card> 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<Player> {
*/
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
@ -546,7 +704,8 @@ public interface Player extends MageItem, Copyable<Player> {
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<Player> {
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
@ -585,25 +745,33 @@ public interface Player extends MageItem, Copyable<Player> {
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<UUID> getUsersAllowedToSeeHandCards();
boolean isInPayManaMode();
void setMatchPlayer(MatchPlayer matchPlayer);
MatchPlayer getMatchPlayer();
}

View file

@ -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
@ -917,7 +921,6 @@ public abstract class PlayerImpl implements Player, Serializable {
return castSourceIdManaCosts;
}
@Override
public boolean isInPayManaMode() {
return payManaMode;
@ -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 {
@ -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;
}
@ -3129,7 +3131,6 @@ public abstract class PlayerImpl implements Player, Serializable {
usersAllowedToSeeHandCards.add(watcherUserId);
}
@Override
public boolean isRequestToShowHandCardsAllowed() {
return userData.isAllowRequestShowHandCards();

View file

@ -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;
}

View file

@ -7,6 +7,7 @@ public enum UserGroup {
COMPUTER(0),
PLAYER(1),
DEFAULT(2),
MAGE(3),
ADMIN(7),
OWNER(15);