playertype, enum singleton

This commit is contained in:
ingmargoudt 2017-04-02 20:02:14 +02:00
parent b19170f34f
commit 211d433ea9
50 changed files with 642 additions and 675 deletions

View file

@ -1,13 +1,12 @@
package mage.client; package mage.client;
import java.util.*;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.client.chat.LocalCommands; import mage.client.chat.LocalCommands;
import mage.constants.ManaType; import mage.constants.ManaType;
import mage.constants.PlayerAction; import mage.constants.PlayerAction;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.players.PlayerType;
import mage.players.net.UserData; import mage.players.net.UserData;
import mage.remote.Connection; import mage.remote.Connection;
import mage.remote.MageRemoteException; import mage.remote.MageRemoteException;
@ -15,6 +14,8 @@ import mage.remote.Session;
import mage.remote.SessionImpl; import mage.remote.SessionImpl;
import mage.view.*; import mage.view.*;
import java.util.*;
/** /**
* Created by IGOUDT on 15-9-2016. * Created by IGOUDT on 15-9-2016.
*/ */
@ -91,11 +92,11 @@ public final class SessionHandler {
session.sendPlayerBoolean(gameId, b); session.sendPlayerBoolean(gameId, b);
} }
public static String[] getPlayerTypes() { public static PlayerType[] getPlayerTypes() {
return session.getPlayerTypes(); return session.getPlayerTypes();
} }
public static boolean joinTournamentTable(UUID roomId, UUID tableId, String text, String selectedItem, Integer integer, DeckCardLists deckCardLists, String s) { public static boolean joinTournamentTable(UUID roomId, UUID tableId, String text, PlayerType selectedItem, Integer integer, DeckCardLists deckCardLists, String s) {
return session.joinTournamentTable(roomId, tableId, text, selectedItem, integer, deckCardLists, s); return session.joinTournamentTable(roomId, tableId, text, selectedItem, integer, deckCardLists, s);
} }
@ -233,7 +234,7 @@ public final class SessionHandler {
return session.createTable(roomId, options); return session.createTable(roomId, options);
} }
public static boolean joinTable(UUID roomId, UUID tableId, String playerName, String human, int skill, DeckCardLists deckCardLists, String text) { public static boolean joinTable(UUID roomId, UUID tableId, String playerName, PlayerType human, int skill, DeckCardLists deckCardLists, String text) {
return session.joinTable(roomId, tableId, playerName, human, skill, deckCardLists, text); return session.joinTable(roomId, tableId, playerName, human, skill, deckCardLists, text);
} }

View file

@ -27,14 +27,16 @@
*/ */
package mage.client.dialog; package mage.client.dialog;
import java.util.UUID;
import javax.swing.JOptionPane;
import mage.cards.decks.importer.DeckImporterUtil; import mage.cards.decks.importer.DeckImporterUtil;
import mage.client.MageFrame; import mage.client.MageFrame;
import mage.client.SessionHandler; import mage.client.SessionHandler;
import mage.players.PlayerType;
import mage.remote.Session; import mage.remote.Session;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import javax.swing.*;
import java.util.UUID;
/** /**
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
@ -143,9 +145,9 @@ public class JoinTableDialog extends MageDialog {
try { try {
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_PASSWORD_JOIN, txtPassword.getText()); PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_PASSWORD_JOIN, txtPassword.getText());
if (isTournament) { if (isTournament) {
joined = session.joinTournamentTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), "Human", 1, DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()), this.txtPassword.getText()); joined = session.joinTournamentTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), PlayerType.HUMAN, 1, DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()), this.txtPassword.getText());
} else { } else {
joined = session.joinTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), "Human", 1, DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()), this.txtPassword.getText()); joined = session.joinTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), PlayerType.HUMAN, 1, DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()), this.txtPassword.getText());
} }
} catch (Exception ex) { } catch (Exception ex) {

View file

@ -27,14 +27,6 @@
*/ */
package mage.client.dialog; package mage.client.dialog;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.swing.*;
import mage.cards.decks.importer.DeckImporterUtil; import mage.cards.decks.importer.DeckImporterUtil;
import mage.client.MageFrame; import mage.client.MageFrame;
import mage.client.SessionHandler; import mage.client.SessionHandler;
@ -48,10 +40,18 @@ import mage.constants.MultiplayerAttackOption;
import mage.constants.RangeOfInfluence; import mage.constants.RangeOfInfluence;
import mage.constants.SkillLevel; import mage.constants.SkillLevel;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.players.PlayerType;
import mage.view.GameTypeView; import mage.view.GameTypeView;
import mage.view.TableView; import mage.view.TableView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import javax.swing.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/** /**
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
@ -65,7 +65,7 @@ public class NewTableDialog extends MageDialog {
private UUID roomId; private UUID roomId;
private String lastSessionId; private String lastSessionId;
private final List<TablePlayerPanel> players = new ArrayList<>(); private final List<TablePlayerPanel> players = new ArrayList<>();
private final List<String> prefPlayerTypes = new ArrayList<>(); private final List<PlayerType> prefPlayerTypes = new ArrayList<>();
private static final String LIMITED = "Limited"; private static final String LIMITED = "Limited";
@ -370,7 +370,7 @@ public class NewTableDialog extends MageDialog {
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
GameTypeView gameType = (GameTypeView) cbGameType.getSelectedItem(); GameTypeView gameType = (GameTypeView) cbGameType.getSelectedItem();
MatchOptions options = new MatchOptions(this.txtName.getText(), gameType.getName(), false, 2); MatchOptions options = new MatchOptions(this.txtName.getText(), gameType.getName(), false, 2);
options.getPlayerTypes().add("Human"); options.getPlayerTypes().add(PlayerType.HUMAN);
for (TablePlayerPanel player : players) { for (TablePlayerPanel player : players) {
options.getPlayerTypes().add(player.getPlayerType()); options.getPlayerTypes().add(player.getPlayerType());
} }
@ -404,7 +404,7 @@ public class NewTableDialog extends MageDialog {
roomId, roomId,
table.getTableId(), table.getTableId(),
this.player1Panel.getPlayerName(), this.player1Panel.getPlayerName(),
"Human", 1, PlayerType.HUMAN, 1,
DeckImporterUtil.importDeck(this.player1Panel.getDeckFile()), DeckImporterUtil.importDeck(this.player1Panel.getDeckFile()),
this.txtPassword.getText())) { this.txtPassword.getText())) {
for (TablePlayerPanel player : players) { for (TablePlayerPanel player : players) {
@ -509,7 +509,7 @@ public class NewTableDialog extends MageDialog {
if (numPlayers > players.size()) { if (numPlayers > players.size()) {
while (players.size() != numPlayers) { while (players.size() != numPlayers) {
TablePlayerPanel playerPanel = new TablePlayerPanel(); TablePlayerPanel playerPanel = new TablePlayerPanel();
String playerType = "Human"; PlayerType playerType = PlayerType.HUMAN;
if (prefPlayerTypes.size() >= players.size() && !players.isEmpty()) { if (prefPlayerTypes.size() >= players.size() && !players.isEmpty()) {
playerType = prefPlayerTypes.get(players.size() - 1); playerType = prefPlayerTypes.get(players.size() - 1);
} }
@ -597,7 +597,9 @@ public class NewTableDialog extends MageDialog {
String playerTypes = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_PLAYER_TYPES, "Human"); String playerTypes = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_PLAYER_TYPES, "Human");
prefPlayerTypes.clear(); prefPlayerTypes.clear();
prefPlayerTypes.addAll(Arrays.asList(playerTypes.split(","))); for(String pType : playerTypes.split(",")) {
prefPlayerTypes.add(PlayerType.getByDescription(pType));
}
this.spnNumPlayers.setValue(Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_NUMBER_PLAYERS, "2"))); this.spnNumPlayers.setValue(Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_NUMBER_PLAYERS, "2")));
String gameTypeName = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_GAME_TYPE, "Two Player Duel"); String gameTypeName = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_GAME_TYPE, "Two Player Duel");

View file

@ -33,22 +33,6 @@
*/ */
package mage.client.dialog; package mage.client.dialog;
import java.awt.Component;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.SpinnerNumberModel;
import javax.swing.filechooser.FileFilter;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.cards.decks.importer.DeckImporterUtil; import mage.cards.decks.importer.DeckImporterUtil;
import mage.cards.repository.ExpansionInfo; import mage.cards.repository.ExpansionInfo;
@ -65,13 +49,20 @@ import mage.game.draft.DraftOptions;
import mage.game.draft.DraftOptions.TimingOption; import mage.game.draft.DraftOptions.TimingOption;
import mage.game.tournament.LimitedOptions; import mage.game.tournament.LimitedOptions;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.players.PlayerType;
import mage.view.GameTypeView; import mage.view.GameTypeView;
import mage.view.TableView; import mage.view.TableView;
import mage.view.TournamentTypeView; import mage.view.TournamentTypeView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class NewTournamentDialog extends MageDialog { public class NewTournamentDialog extends MageDialog {
@ -93,7 +84,9 @@ public class NewTournamentDialog extends MageDialog {
private String cubeFromDeckFilename = ""; private String cubeFromDeckFilename = "";
private boolean automaticChange = false; private boolean automaticChange = false;
/** Creates new form NewTournamentDialog */ /**
* Creates new form NewTournamentDialog
*/
public NewTournamentDialog() { public NewTournamentDialog() {
initComponents(); initComponents();
lastSessionId = ""; lastSessionId = "";
@ -121,8 +114,8 @@ public class NewTournamentDialog extends MageDialog {
cbDraftCube.setModel(new DefaultComboBoxModel(SessionHandler.getDraftCubes())); cbDraftCube.setModel(new DefaultComboBoxModel(SessionHandler.getDraftCubes()));
cbDraftTiming.setModel(new DefaultComboBoxModel(DraftOptions.TimingOption.values())); cbDraftTiming.setModel(new DefaultComboBoxModel(DraftOptions.TimingOption.values()));
// update player types // update player types
int i=2; int i = 2;
for (TournamentPlayerPanel tournamentPlayerPanel :players) { for (TournamentPlayerPanel tournamentPlayerPanel : players) {
tournamentPlayerPanel.init(i++); tournamentPlayerPanel.init(i++);
} }
cbAllowSpectators.setSelected(true); cbAllowSpectators.setSelected(true);
@ -133,7 +126,8 @@ public class NewTournamentDialog extends MageDialog {
this.setVisible(true); this.setVisible(true);
} }
/** This method is called from within the constructor to /**
* This method is called from within the constructor to
* initialize the form. * initialize the form.
* WARNING: Do NOT modify this code. The content of this method is * WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor. * always regenerated by the Form Editor.
@ -213,7 +207,7 @@ public class NewTournamentDialog extends MageDialog {
lblTournamentType.setText("Tournament Type:"); lblTournamentType.setText("Tournament Type:");
cbTournamentType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cbTournamentType.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));
cbTournamentType.addActionListener(evt -> cbTournamentTypeActionPerformed(evt)); cbTournamentType.addActionListener(evt -> cbTournamentTypeActionPerformed(evt));
lbDeckType.setText("Deck Type:"); lbDeckType.setText("Deck Type:");
@ -235,7 +229,7 @@ public class NewTournamentDialog extends MageDialog {
lblDraftCube.setText("Draft Cube:"); lblDraftCube.setText("Draft Cube:");
cbDraftCube.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cbDraftCube.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));
cbDraftCube.addActionListener(evt -> cbDraftCubeActionPerformed(evt)); cbDraftCube.addActionListener(evt -> cbDraftCubeActionPerformed(evt));
lblNumRounds.setText("Number of Swiss Rounds:"); lblNumRounds.setText("Number of Swiss Rounds:");
@ -260,7 +254,7 @@ public class NewTournamentDialog extends MageDialog {
jLabel6.setText("Timing:"); jLabel6.setText("Timing:");
cbDraftTiming.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cbDraftTiming.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));
cbDraftTiming.addActionListener(evt -> cbDraftTimingActionPerformed(evt)); cbDraftTiming.addActionListener(evt -> cbDraftTimingActionPerformed(evt));
javax.swing.GroupLayout pnlDraftOptionsLayout = new javax.swing.GroupLayout(pnlDraftOptions); javax.swing.GroupLayout pnlDraftOptionsLayout = new javax.swing.GroupLayout(pnlDraftOptions);
@ -510,18 +504,18 @@ public class NewTournamentDialog extends MageDialog {
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
TournamentTypeView tournamentType = (TournamentTypeView) cbTournamentType.getSelectedItem(); TournamentTypeView tournamentType = (TournamentTypeView) cbTournamentType.getSelectedItem();
int numSeats = (Integer)this.spnNumSeats.getValue(); int numSeats = (Integer) this.spnNumSeats.getValue();
TournamentOptions tOptions = new TournamentOptions(this.txtName.getText(), "", numSeats); TournamentOptions tOptions = new TournamentOptions(this.txtName.getText(), "", numSeats);
tOptions.setTournamentType(tournamentType.getName()); tOptions.setTournamentType(tournamentType.getName());
tOptions.setPassword(txtPassword.getText()); tOptions.setPassword(txtPassword.getText());
tOptions.getPlayerTypes().add("Human"); tOptions.getPlayerTypes().add(PlayerType.HUMAN);
tOptions.setWatchingAllowed(cbAllowSpectators.isSelected()); tOptions.setWatchingAllowed(cbAllowSpectators.isSelected());
tOptions.setQuitRatio((Integer)spnQuitRatio.getValue()); tOptions.setQuitRatio((Integer) spnQuitRatio.getValue());
for (TournamentPlayerPanel player: players) { for (TournamentPlayerPanel player : players) {
tOptions.getPlayerTypes().add((String) player.getPlayerType().getSelectedItem()); tOptions.getPlayerTypes().add((PlayerType) player.getPlayerType().getSelectedItem());
} }
if (!tournamentType.isElimination()) { if (!tournamentType.isElimination()) {
tOptions.setNumberRounds((Integer)spnNumRounds.getValue()); tOptions.setNumberRounds((Integer) spnNumRounds.getValue());
} }
if (tournamentType.isDraft()) { if (tournamentType.isDraft()) {
DraftOptions options = new DraftOptions(); DraftOptions options = new DraftOptions();
@ -533,7 +527,7 @@ public class NewTournamentDialog extends MageDialog {
tOptions.setLimitedOptions(new LimitedOptions()); tOptions.setLimitedOptions(new LimitedOptions());
} }
if (tournamentType.isLimited()) { if (tournamentType.isLimited()) {
tOptions.getLimitedOptions().setConstructionTime((Integer)this.spnConstructTime.getValue() * 60); tOptions.getLimitedOptions().setConstructionTime((Integer) this.spnConstructTime.getValue() * 60);
tOptions.getLimitedOptions().setIsRandom(tournamentType.isRandom()); tOptions.getLimitedOptions().setIsRandom(tournamentType.isRandom());
if (tournamentType.isCubeBooster()) { if (tournamentType.isCubeBooster()) {
tOptions.getLimitedOptions().setDraftCubeName(this.cbDraftCube.getSelectedItem().toString()); tOptions.getLimitedOptions().setDraftCubeName(this.cbDraftCube.getSelectedItem().toString());
@ -558,18 +552,18 @@ public class NewTournamentDialog extends MageDialog {
if (tournamentType.isRichMan()) { if (tournamentType.isRichMan()) {
maxPacks = 36; maxPacks = 36;
} }
if (selected.size() > maxPacks ){ if (selected.size() > maxPacks) {
StringBuilder infoString = new StringBuilder("More sets were selected than needed. "); StringBuilder infoString = new StringBuilder("More sets were selected than needed. ");
infoString.append(maxPacks); infoString.append(maxPacks);
infoString.append(" sets will be randomly chosen."); infoString.append(" sets will be randomly chosen.");
JOptionPane.showMessageDialog(MageFrame.getDesktop(), infoString, "Information", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(MageFrame.getDesktop(), infoString, "Information", JOptionPane.INFORMATION_MESSAGE);
Collections.shuffle(selected); Collections.shuffle(selected);
tOptions.getLimitedOptions().getSetCodes().addAll(selected.subList(0, maxPacks)); tOptions.getLimitedOptions().getSetCodes().addAll(selected.subList(0, maxPacks));
}else{ } else {
tOptions.getLimitedOptions().getSetCodes().addAll(selected); tOptions.getLimitedOptions().getSetCodes().addAll(selected);
} }
} else { } else {
for (JComboBox pack: packs) { for (JComboBox pack : packs) {
tOptions.getLimitedOptions().getSetCodes().add(((ExpansionInfo) pack.getSelectedItem()).getCode()); tOptions.getLimitedOptions().getSetCodes().add(((ExpansionInfo) pack.getSelectedItem()).getCode());
} }
} }
@ -588,8 +582,8 @@ public class NewTournamentDialog extends MageDialog {
tOptions.getMatchOptions().setMatchTimeLimit((MatchTimeLimit) this.cbTimeLimit.getSelectedItem()); tOptions.getMatchOptions().setMatchTimeLimit((MatchTimeLimit) this.cbTimeLimit.getSelectedItem());
tOptions.getMatchOptions().setSkillLevel((SkillLevel) this.cbSkillLevel.getSelectedItem()); tOptions.getMatchOptions().setSkillLevel((SkillLevel) this.cbSkillLevel.getSelectedItem());
tOptions.getMatchOptions().setWinsNeeded((Integer)this.spnNumWins.getValue()); tOptions.getMatchOptions().setWinsNeeded((Integer) this.spnNumWins.getValue());
tOptions.getMatchOptions().setFreeMulligans((Integer)this.spnFreeMulligans.getValue()); tOptions.getMatchOptions().setFreeMulligans((Integer) this.spnFreeMulligans.getValue());
tOptions.getMatchOptions().setAttackOption(MultiplayerAttackOption.LEFT); tOptions.getMatchOptions().setAttackOption(MultiplayerAttackOption.LEFT);
tOptions.getMatchOptions().setRange(RangeOfInfluence.ALL); tOptions.getMatchOptions().setRange(RangeOfInfluence.ALL);
tOptions.getMatchOptions().setRollbackTurnsAllowed(this.chkRollbackTurnsAllowed.isSelected()); tOptions.getMatchOptions().setRollbackTurnsAllowed(this.chkRollbackTurnsAllowed.isSelected());
@ -605,10 +599,10 @@ public class NewTournamentDialog extends MageDialog {
roomId, roomId,
table.getTableId(), table.getTableId(),
this.player1Panel.getPlayerName(), this.player1Panel.getPlayerName(),
"Human", 1, PlayerType.HUMAN, 1,
DeckImporterUtil.importDeck(this.player1Panel.getDeckFile()), DeckImporterUtil.importDeck(this.player1Panel.getDeckFile()),
tOptions.getPassword())) { tOptions.getPassword())) {
for (TournamentPlayerPanel player: players) { for (TournamentPlayerPanel player : players) {
if (!player.getPlayerType().toString().equals("Human")) { if (!player.getPlayerType().toString().equals("Human")) {
if (!player.joinTournamentTable(roomId, table.getTableId(), DeckImporterUtil.importDeck(this.player1Panel.getDeckFile()))) { if (!player.joinTournamentTable(roomId, table.getTableId(), DeckImporterUtil.importDeck(this.player1Panel.getDeckFile()))) {
// error message must be send by sever // error message must be send by sever
@ -633,8 +627,8 @@ public class NewTournamentDialog extends MageDialog {
}//GEN-LAST:event_btnCancelActionPerformed }//GEN-LAST:event_btnCancelActionPerformed
private void updateNumSeats() { private void updateNumSeats() {
int numPlayers = (Integer)this.spnNumPlayers.getValue(); int numPlayers = (Integer) this.spnNumPlayers.getValue();
int numSeats = (Integer)this.spnNumSeats.getValue(); int numSeats = (Integer) this.spnNumSeats.getValue();
if (numSeats > 2) { if (numSeats > 2) {
TournamentTypeView tournamentType = (TournamentTypeView) cbTournamentType.getSelectedItem(); TournamentTypeView tournamentType = (TournamentTypeView) cbTournamentType.getSelectedItem();
@ -652,16 +646,16 @@ public class NewTournamentDialog extends MageDialog {
} }
private void spnNumPlayersStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spnNumPlayersStateChanged private void spnNumPlayersStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spnNumPlayersStateChanged
int numPlayers = (Integer)this.spnNumPlayers.getValue(); int numPlayers = (Integer) this.spnNumPlayers.getValue();
createPlayers(numPlayers - 1); createPlayers(numPlayers - 1);
int numSeats = (Integer)this.spnNumSeats.getValue(); int numSeats = (Integer) this.spnNumSeats.getValue();
if (numSeats > 2 && numPlayers != numSeats) { if (numSeats > 2 && numPlayers != numSeats) {
updateNumSeats(); updateNumSeats();
} }
}//GEN-LAST:event_spnNumPlayersStateChanged }//GEN-LAST:event_spnNumPlayersStateChanged
private void spnNumSeatsStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spnNumSeatsStateChanged private void spnNumSeatsStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spnNumSeatsStateChanged
int numSeats = (Integer)this.spnNumSeats.getValue(); int numSeats = (Integer) this.spnNumSeats.getValue();
if (numSeats > 2) { if (numSeats > 2) {
this.spnNumPlayers.setEnabled(false); this.spnNumPlayers.setEnabled(false);
} else { } else {
@ -672,8 +666,8 @@ public class NewTournamentDialog extends MageDialog {
private void spnNumWinsnumPlayersChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spnNumWinsnumPlayersChanged private void spnNumWinsnumPlayersChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spnNumWinsnumPlayersChanged
int numSeats = (Integer)this.spnNumSeats.getValue(); int numSeats = (Integer) this.spnNumSeats.getValue();
int numWins = (Integer)this.spnNumSeats.getValue(); int numWins = (Integer) this.spnNumSeats.getValue();
if (numSeats > 2) { if (numSeats > 2) {
spnNumWins.setValue(1); spnNumWins.setValue(1);
} }
@ -718,6 +712,7 @@ public class NewTournamentDialog extends MageDialog {
private void cbGameTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbGameTypeActionPerformed private void cbGameTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbGameTypeActionPerformed
setGameOptions(); setGameOptions();
}//GEN-LAST:event_cbGameTypeActionPerformed }//GEN-LAST:event_cbGameTypeActionPerformed
private void setGameOptions() { private void setGameOptions() {
GameTypeView gameType = (GameTypeView) cbGameType.getSelectedItem(); GameTypeView gameType = (GameTypeView) cbGameType.getSelectedItem();
// int oldValue = (Integer) this.spnNumPlayers.getValue(); // int oldValue = (Integer) this.spnNumPlayers.getValue();
@ -748,9 +743,9 @@ public class NewTournamentDialog extends MageDialog {
if (tournamentType.isLimited()) { if (tournamentType.isLimited()) {
this.isRandom = tournamentType.isRandom(); this.isRandom = tournamentType.isRandom();
this.isRichMan = tournamentType.isRichMan(); this.isRichMan = tournamentType.isRichMan();
if (this.isRandom || this.isRichMan){ if (this.isRandom || this.isRichMan) {
createRandomPacks(); createRandomPacks();
}else{ } else {
createPacks(tournamentType.getNumBoosters()); createPacks(tournamentType.getNumBoosters());
} }
} }
@ -760,7 +755,7 @@ public class NewTournamentDialog extends MageDialog {
private void setNumberOfSwissRoundsMin(int numPlayers) { private void setNumberOfSwissRoundsMin(int numPlayers) {
// set the number of minimum swiss rounds related to the number of players // set the number of minimum swiss rounds related to the number of players
int minRounds = (int) Math.ceil(Math.log(numPlayers + 1) / Math.log(2)); int minRounds = (int) Math.ceil(Math.log(numPlayers + 1) / Math.log(2));
int newValue = Math.max((Integer)spnNumRounds.getValue(), minRounds); int newValue = Math.max((Integer) spnNumRounds.getValue(), minRounds);
this.spnNumRounds.setModel(new SpinnerNumberModel(newValue, minRounds, 10, 1)); this.spnNumRounds.setModel(new SpinnerNumberModel(newValue, minRounds, 10, 1));
this.pack(); this.pack();
this.revalidate(); this.revalidate();
@ -793,7 +788,7 @@ public class NewTournamentDialog extends MageDialog {
this.lblPacks.setVisible(false); this.lblPacks.setVisible(false);
this.pnlPacks.setVisible(false); this.pnlPacks.setVisible(false);
this.pnlRandomPacks.setVisible(false); this.pnlRandomPacks.setVisible(false);
} else if (tournamentType.isRandom() || tournamentType.isRichMan()){ } else if (tournamentType.isRandom() || tournamentType.isRichMan()) {
this.lblDraftCube.setVisible(false); this.lblDraftCube.setVisible(false);
this.cbDraftCube.setVisible(false); this.cbDraftCube.setVisible(false);
this.lblPacks.setVisible(true); this.lblPacks.setVisible(true);
@ -887,14 +882,13 @@ public class NewTournamentDialog extends MageDialog {
private void packActionPerformed(java.awt.event.ActionEvent evt) { private void packActionPerformed(java.awt.event.ActionEvent evt) {
boolean start = false; boolean start = false;
int selectedIndex = 0; int selectedIndex = 0;
for (JComboBox pack: packs) { for (JComboBox pack : packs) {
if (!start) { if (!start) {
if (evt.getSource().equals(pack)) { if (evt.getSource().equals(pack)) {
start = true; start = true;
selectedIndex = pack.getSelectedIndex(); selectedIndex = pack.getSelectedIndex();
} }
} } else {
else {
pack.setSelectedIndex(selectedIndex); pack.setSelectedIndex(selectedIndex);
} }
} }
@ -909,8 +903,7 @@ public class NewTournamentDialog extends MageDialog {
players.add(playerPanel); players.add(playerPanel);
} }
} } else if (numPlayers < players.size()) {
else if (numPlayers < players.size()) {
while (players.size() != numPlayers) { while (players.size() != numPlayers) {
players.remove(players.size() - 1); players.remove(players.size() - 1);
} }
@ -922,10 +915,9 @@ public class NewTournamentDialog extends MageDialog {
} }
private void drawPlayers() { private void drawPlayers() {
this.pnlOtherPlayers.removeAll(); this.pnlOtherPlayers.removeAll();
for (TournamentPlayerPanel panel: players) { for (TournamentPlayerPanel panel : players) {
this.pnlOtherPlayers.add(panel); this.pnlOtherPlayers.add(panel);
panel.getPlayerType().addActionListener(evt -> { panel.getPlayerType().addActionListener(evt -> {
if (!automaticChange) { if (!automaticChange) {
@ -942,14 +934,13 @@ public class NewTournamentDialog extends MageDialog {
boolean start = false; boolean start = false;
int selectedIndex = 0; int selectedIndex = 0;
automaticChange = true; automaticChange = true;
for (TournamentPlayerPanel player: players) { for (TournamentPlayerPanel player : players) {
if (!start) { if (!start) {
if (evt.getSource().equals(player.getPlayerType())) { if (evt.getSource().equals(player.getPlayerType())) {
start = true; start = true;
selectedIndex = player.getPlayerType().getSelectedIndex(); selectedIndex = player.getPlayerType().getSelectedIndex();
} }
} } else {
else {
player.getPlayerType().setSelectedIndex(selectedIndex); player.getPlayerType().setSelectedIndex(selectedIndex);
} }
} }
@ -959,19 +950,19 @@ public class NewTournamentDialog extends MageDialog {
/** /**
* set the tournament settings from java prefs * set the tournament settings from java prefs
*/ */
private void setTournamentSettingsFromPrefs () { private void setTournamentSettingsFromPrefs() {
int numPlayers; int numPlayers;
txtName.setText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_NAME, "Tournament")); txtName.setText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_NAME, "Tournament"));
txtPassword.setText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PASSWORD, "")); txtPassword.setText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PASSWORD, ""));
int timeLimit = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_TIME_LIMIT, "1500")); int timeLimit = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_TIME_LIMIT, "1500"));
for (MatchTimeLimit mtl :MatchTimeLimit.values()) { for (MatchTimeLimit mtl : MatchTimeLimit.values()) {
if (mtl.getTimeLimit() == timeLimit) { if (mtl.getTimeLimit() == timeLimit) {
this.cbTimeLimit.setSelectedItem(mtl); this.cbTimeLimit.setSelectedItem(mtl);
break; break;
} }
} }
String skillLevelDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_SKILL_LEVEL, "Casual"); String skillLevelDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_SKILL_LEVEL, "Casual");
for (SkillLevel skillLevel :SkillLevel.values()) { for (SkillLevel skillLevel : SkillLevel.values()) {
if (skillLevel.toString().equals(skillLevelDefault)) { if (skillLevel.toString().equals(skillLevelDefault)) {
this.cbSkillLevel.setSelectedItem(skillLevel); this.cbSkillLevel.setSelectedItem(skillLevel);
break; break;
@ -1006,7 +997,7 @@ public class NewTournamentDialog extends MageDialog {
if (tournamentType.isDraft()) { if (tournamentType.isDraft()) {
numPlayers = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PLAYERS_DRAFT, "4")); numPlayers = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PLAYERS_DRAFT, "4"));
setTournamentOptions(numPlayers); setTournamentOptions(numPlayers);
if (!(tournamentType.isRandom() || tournamentType.isRichMan())){ if (!(tournamentType.isRandom() || tournamentType.isRichMan())) {
loadBoosterPacks(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PACKS_DRAFT, "")); loadBoosterPacks(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PACKS_DRAFT, ""));
} }
@ -1028,13 +1019,13 @@ public class NewTournamentDialog extends MageDialog {
if (!packString.isEmpty()) { if (!packString.isEmpty()) {
String[] packsArray = packString.substring(1, packString.length() - 1).split(","); String[] packsArray = packString.substring(1, packString.length() - 1).split(",");
int packNumber = 0; int packNumber = 0;
for (String pack : packsArray ){ for (String pack : packsArray) {
packNumber++; packNumber++;
if (this.packs.size() >= packNumber - 1) { if (this.packs.size() >= packNumber - 1) {
JComboBox comboBox = this.packs.get(packNumber-1); JComboBox comboBox = this.packs.get(packNumber - 1);
ComboBoxModel model = comboBox.getModel(); ComboBoxModel model = comboBox.getModel();
int size = model.getSize(); int size = model.getSize();
for(int i=0;i<size;i++) { for (int i = 0; i < size; i++) {
ExpansionInfo element = (ExpansionInfo) model.getElementAt(i); ExpansionInfo element = (ExpansionInfo) model.getElementAt(i);
if (element.getCode().equals(pack.trim())) { if (element.getCode().equals(pack.trim())) {
comboBox.setSelectedIndex(i); comboBox.setSelectedIndex(i);
@ -1051,7 +1042,6 @@ public class NewTournamentDialog extends MageDialog {
* Save the settings to java prefs to reload it next time the dialog will be created * Save the settings to java prefs to reload it next time the dialog will be created
* *
* @param tOptions Tournament options * @param tOptions Tournament options
*/ */
private void saveTournamentSettingsToPrefs(TournamentOptions tOptions) { private void saveTournamentSettingsToPrefs(TournamentOptions tOptions) {
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_NAME, tOptions.getName()); PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_NAME, tOptions.getName());
@ -1082,18 +1072,18 @@ public class NewTournamentDialog extends MageDialog {
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_DECK_FILE, deckFile); PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_DECK_FILE, deckFile);
} }
if (tOptions.getLimitedOptions().getIsRandom()){ if (tOptions.getLimitedOptions().getIsRandom()) {
// save random boosters to prefs // save random boosters to prefs
StringBuilder packlist = new StringBuilder(); StringBuilder packlist = new StringBuilder();
for (String pack : this.randomPackSelector.getSelectedPacks()){ for (String pack : this.randomPackSelector.getSelectedPacks()) {
packlist.append(pack); packlist.append(pack);
packlist.append(';'); packlist.append(';');
} }
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PACKS_RANDOM_DRAFT, packlist.toString()); PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PACKS_RANDOM_DRAFT, packlist.toString());
} }
} }
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_ALLOW_SPECTATORS, (tOptions.isWatchingAllowed()?"Yes":"No")); PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_ALLOW_SPECTATORS, (tOptions.isWatchingAllowed() ? "Yes" : "No"));
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_ALLOW_ROLLBACKS, (tOptions.getMatchOptions().isRollbackTurnsAllowed()?"Yes":"No")); PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_ALLOW_ROLLBACKS, (tOptions.getMatchOptions().isRollbackTurnsAllowed() ? "Yes" : "No"));
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_RATED, (tOptions.getMatchOptions().isRated() ? "Yes" : "No")); PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TOURNAMENT_RATED, (tOptions.getMatchOptions().isRated() ? "Yes" : "No"));
} }

View file

@ -34,14 +34,16 @@
package mage.client.table; package mage.client.table;
import java.io.IOException;
import java.util.UUID;
import javax.swing.DefaultComboBoxModel;
import mage.cards.decks.importer.DeckImporterUtil; import mage.cards.decks.importer.DeckImporterUtil;
import mage.client.SessionHandler; import mage.client.SessionHandler;
import mage.client.util.Config; import mage.client.util.Config;
import mage.client.util.Event; import mage.client.util.Event;
import mage.client.util.Listener; import mage.client.util.Listener;
import mage.players.PlayerType;
import javax.swing.*;
import java.io.IOException;
import java.util.UUID;
/** /**
* *
@ -58,7 +60,7 @@ public class TablePlayerPanel extends javax.swing.JPanel {
this.newPlayerPanel.setVisible(false); this.newPlayerPanel.setVisible(false);
} }
public void init(int playerNum, String playerType) { public void init(int playerNum, PlayerType playerType) {
cbPlayerType.setModel(new DefaultComboBoxModel(SessionHandler.getPlayerTypes())); cbPlayerType.setModel(new DefaultComboBoxModel(SessionHandler.getPlayerTypes()));
this.lblPlayerNum.setText("Player " + playerNum); this.lblPlayerNum.setText("Player " + playerNum);
if (Config.defaultOtherPlayerIndex != null) { if (Config.defaultOtherPlayerIndex != null) {
@ -77,13 +79,13 @@ public class TablePlayerPanel extends javax.swing.JPanel {
public boolean joinTable(UUID roomId, UUID tableId) throws IOException, ClassNotFoundException { public boolean joinTable(UUID roomId, UUID tableId) throws IOException, ClassNotFoundException {
if (!this.cbPlayerType.getSelectedItem().equals("Human")) { if (!this.cbPlayerType.getSelectedItem().equals("Human")) {
return SessionHandler.joinTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), (String)this.cbPlayerType.getSelectedItem(), this.newPlayerPanel.getLevel(), DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()),""); return SessionHandler.joinTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), (PlayerType) this.cbPlayerType.getSelectedItem(), this.newPlayerPanel.getLevel(), DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()),"");
} }
return true; return true;
} }
public String getPlayerType() { public PlayerType getPlayerType() {
return (String) this.cbPlayerType.getSelectedItem(); return PlayerType.getByDescription(this.cbPlayerType.getSelectedItem().toString());
} }
public void addPlayerTypeEventListener(Listener<Event> listener) { public void addPlayerTypeEventListener(Listener<Event> listener) {

View file

@ -33,69 +33,21 @@
*/ */
package mage.client.table; package mage.client.table;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.beans.PropertyVetoException;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.RowFilter;
import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel;
import mage.cards.decks.importer.DeckImporterUtil; import mage.cards.decks.importer.DeckImporterUtil;
import mage.client.MageFrame; import mage.client.MageFrame;
import mage.client.SessionHandler; import mage.client.SessionHandler;
import mage.client.chat.ChatPanelBasic; import mage.client.chat.ChatPanelBasic;
import mage.client.components.MageComponents; import mage.client.components.MageComponents;
import mage.client.dialog.JoinTableDialog; import mage.client.dialog.*;
import mage.client.dialog.NewTableDialog;
import mage.client.dialog.NewTournamentDialog;
import mage.client.dialog.PreferencesDialog;
import static mage.client.dialog.PreferencesDialog.KEY_TABLES_COLUMNS_ORDER;
import static mage.client.dialog.PreferencesDialog.KEY_TABLES_COLUMNS_WIDTH;
import mage.client.dialog.TableWaitingDialog;
import static mage.client.table.TablesPanel.PASSWORDED;
import mage.client.util.ButtonColumn; import mage.client.util.ButtonColumn;
import mage.client.util.GUISizeHelper; import mage.client.util.GUISizeHelper;
import mage.client.util.IgnoreList; import mage.client.util.IgnoreList;
import mage.client.util.MageTableRowSorter; import mage.client.util.MageTableRowSorter;
import mage.client.util.gui.GuiDisplayUtil; import mage.client.util.gui.GuiDisplayUtil;
import mage.client.util.gui.TableUtil; import mage.client.util.gui.TableUtil;
import mage.constants.MatchTimeLimit; import mage.constants.*;
import mage.constants.MultiplayerAttackOption;
import mage.constants.PlayerAction;
import mage.constants.RangeOfInfluence;
import mage.constants.SkillLevel;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.players.PlayerType;
import mage.remote.MageRemoteException; import mage.remote.MageRemoteException;
import mage.view.MatchView; import mage.view.MatchView;
import mage.view.RoomUsersView; import mage.view.RoomUsersView;
@ -103,6 +55,25 @@ import mage.view.TableView;
import mage.view.UserRequestMessage; import mage.view.UserRequestMessage;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.beans.PropertyVetoException;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static mage.client.dialog.PreferencesDialog.KEY_TABLES_COLUMNS_ORDER;
import static mage.client.dialog.PreferencesDialog.KEY_TABLES_COLUMNS_WIDTH;
import static mage.client.table.TablesPanel.PASSWORDED;
/** /**
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
@ -216,7 +187,7 @@ public class TablesPanel extends javax.swing.JPanel {
if (PASSWORDED.equals(pwdColumn)) { if (PASSWORDED.equals(pwdColumn)) {
joinTableDialog.showDialog(roomId, tableId, true, deckType.startsWith("Limited")); joinTableDialog.showDialog(roomId, tableId, true, deckType.startsWith("Limited"));
} else { } else {
SessionHandler.joinTournamentTable(roomId, tableId, SessionHandler.getUserName(), "Human", 1, null, ""); SessionHandler.joinTournamentTable(roomId, tableId, SessionHandler.getUserName(), PlayerType.HUMAN, 1, null, "");
} }
} else { } else {
joinTableDialog.showDialog(roomId, tableId, true, deckType.startsWith("Limited")); joinTableDialog.showDialog(roomId, tableId, true, deckType.startsWith("Limited"));
@ -1188,8 +1159,8 @@ public class TablesPanel extends javax.swing.JPanel {
} }
MatchOptions options = new MatchOptions("1", "Two Player Duel", false, 2); MatchOptions options = new MatchOptions("1", "Two Player Duel", false, 2);
options.getPlayerTypes().add("Human"); options.getPlayerTypes().add(PlayerType.HUMAN);
options.getPlayerTypes().add("Computer - mad"); options.getPlayerTypes().add(PlayerType.COMPUTER_MAD);
options.setDeckType("Limited"); options.setDeckType("Limited");
options.setAttackOption(MultiplayerAttackOption.LEFT); options.setAttackOption(MultiplayerAttackOption.LEFT);
options.setRange(RangeOfInfluence.ALL); options.setRange(RangeOfInfluence.ALL);
@ -1203,8 +1174,8 @@ public class TablesPanel extends javax.swing.JPanel {
options.setBannedUsers(IgnoreList.ignoreList(serverAddress)); options.setBannedUsers(IgnoreList.ignoreList(serverAddress));
table = SessionHandler.createTable(roomId, options); table = SessionHandler.createTable(roomId, options);
SessionHandler.joinTable(roomId, table.getTableId(), "Human", "Human", 1, DeckImporterUtil.importDeck("test.dck"), ""); SessionHandler.joinTable(roomId, table.getTableId(), "Human", PlayerType.HUMAN, 1, DeckImporterUtil.importDeck("test.dck"), "");
SessionHandler.joinTable(roomId, table.getTableId(), "Computer", "Computer - mad", 5, DeckImporterUtil.importDeck("test.dck"), ""); SessionHandler.joinTable(roomId, table.getTableId(), "Computer", PlayerType.COMPUTER_MAD, 5, DeckImporterUtil.importDeck("test.dck"), "");
SessionHandler.startMatch(roomId, table.getTableId()); SessionHandler.startMatch(roomId, table.getTableId());
} catch (HeadlessException ex) { } catch (HeadlessException ex) {
handleError(ex); handleError(ex);

View file

@ -36,6 +36,7 @@ package mage.client.table;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.client.SessionHandler; import mage.client.SessionHandler;
import mage.players.PlayerType;
import javax.swing.*; import javax.swing.*;
import java.util.UUID; import java.util.UUID;
@ -68,8 +69,8 @@ public class TournamentPlayerPanel extends javax.swing.JPanel {
roomId, roomId,
tableId, tableId,
this.txtPlayerName.getText(), this.txtPlayerName.getText(),
(String)this.cbPlayerType.getSelectedItem(), (PlayerType) this.cbPlayerType.getSelectedItem(),
(Integer)spnLevel.getValue(), (Integer) spnLevel.getValue(),
deckCardLists, deckCardLists,
""); "");
} }

View file

@ -27,10 +27,6 @@
*/ */
package mage.interfaces; package mage.interfaces;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import mage.MageException; import mage.MageException;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.cards.repository.CardInfo; import mage.cards.repository.CardInfo;
@ -40,15 +36,15 @@ import mage.constants.PlayerAction;
import mage.game.GameException; import mage.game.GameException;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.players.PlayerType;
import mage.players.net.UserData; import mage.players.net.UserData;
import mage.utils.MageVersion; import mage.utils.MageVersion;
import mage.view.DraftPickView; import mage.view.*;
import mage.view.GameView;
import mage.view.MatchView; import java.util.List;
import mage.view.RoomUsersView; import java.util.Optional;
import mage.view.TableView; import java.util.Set;
import mage.view.TournamentView; import java.util.UUID;
import mage.view.UserView;
/** /**
* *
@ -94,9 +90,9 @@ public interface MageServer {
TableView createTournamentTable(String sessionId, UUID roomId, TournamentOptions tournamentOptions) 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 joinTable(String sessionId, UUID roomId, UUID tableId, String name, PlayerType 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 joinTournamentTable(String sessionId, UUID roomId, UUID tableId, String name, PlayerType playerType, int skill, DeckCardLists deckList, String password) throws MageException, GameException;
boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException; boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException;

View file

@ -28,15 +28,15 @@
package mage.interfaces; package mage.interfaces;
import java.io.Serializable; import mage.players.PlayerType;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import mage.utils.MageVersion; import mage.utils.MageVersion;
import mage.view.GameTypeView; import mage.view.GameTypeView;
import mage.view.TournamentTypeView; import mage.view.TournamentTypeView;
import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -44,7 +44,7 @@ public class ServerState implements Serializable {
private final List<GameTypeView> gameTypes; private final List<GameTypeView> gameTypes;
private final List<TournamentTypeView> tournamentTypes; private final List<TournamentTypeView> tournamentTypes;
private final String[] playerTypes; private final PlayerType[] playerTypes;
private final String[] deckTypes; private final String[] deckTypes;
private final String[] draftCubes; private final String[] draftCubes;
private final boolean testMode; private final boolean testMode;
@ -53,7 +53,7 @@ public class ServerState implements Serializable {
private final long expansionsContentVersion; private final long expansionsContentVersion;
public ServerState(List<GameTypeView> gameTypes, List<TournamentTypeView> tournamentTypes, public ServerState(List<GameTypeView> gameTypes, List<TournamentTypeView> tournamentTypes,
String[] playerTypes, String[] deckTypes, String[] draftCubes, boolean testMode, PlayerType[] playerTypes, String[] deckTypes, String[] draftCubes, boolean testMode,
MageVersion version, long cardsContentVersion, long expansionsContentVersion) { MageVersion version, long cardsContentVersion, long expansionsContentVersion) {
this.gameTypes = gameTypes; this.gameTypes = gameTypes;
this.tournamentTypes = tournamentTypes; this.tournamentTypes = tournamentTypes;
@ -81,7 +81,7 @@ public class ServerState implements Serializable {
return tournamentTypes; return tournamentTypes;
} }
public String[] getPlayerTypes() { public PlayerType[] getPlayerTypes() {
return playerTypes; return playerTypes;
} }

View file

@ -27,13 +27,6 @@
*/ */
package mage.remote; package mage.remote;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.swing.JOptionPane;
import mage.MageException; import mage.MageException;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.cards.decks.InvalidDeckException; import mage.cards.decks.InvalidDeckException;
@ -50,6 +43,7 @@ import mage.interfaces.MageClient;
import mage.interfaces.MageServer; import mage.interfaces.MageServer;
import mage.interfaces.ServerState; import mage.interfaces.ServerState;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.players.PlayerType;
import mage.players.net.UserData; import mage.players.net.UserData;
import mage.utils.CompressUtil; import mage.utils.CompressUtil;
import mage.view.*; import mage.view.*;
@ -62,6 +56,13 @@ import org.jboss.remoting.transport.bisocket.Bisocket;
import org.jboss.remoting.transport.socket.SocketWrapper; import org.jboss.remoting.transport.socket.SocketWrapper;
import org.jboss.remoting.transporter.TransporterClient; import org.jboss.remoting.transporter.TransporterClient;
import javax.swing.*;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -550,7 +551,7 @@ public class SessionImpl implements Session {
} }
@Override @Override
public String[] getPlayerTypes() { public PlayerType[] getPlayerTypes() {
return serverState.getPlayerTypes(); return serverState.getPlayerTypes();
} }
@ -680,7 +681,7 @@ public class SessionImpl implements Session {
} }
@Override @Override
public boolean joinTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList, String password) { public boolean joinTable(UUID roomId, UUID tableId, String playerName, PlayerType playerType, int skill, DeckCardLists deckList, String password) {
try { try {
if (isConnected()) { if (isConnected()) {
// Workaround to fix Can't join table problem // Workaround to fix Can't join table problem
@ -703,7 +704,7 @@ public class SessionImpl implements Session {
} }
@Override @Override
public boolean joinTournamentTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList, String password) { public boolean joinTournamentTable(UUID roomId, UUID tableId, String playerName, PlayerType playerType, int skill, DeckCardLists deckList, String password) {
try { try {
if (isConnected()) { if (isConnected()) {
// Workaround to fix Can't join table problem // Workaround to fix Can't join table problem

View file

@ -28,6 +28,8 @@
package mage.remote.interfaces; package mage.remote.interfaces;
import java.util.List; import java.util.List;
import mage.players.PlayerType;
import mage.view.GameTypeView; import mage.view.GameTypeView;
import mage.view.TournamentTypeView; import mage.view.TournamentTypeView;
@ -36,7 +38,7 @@ import mage.view.TournamentTypeView;
*/ */
public interface GameTypes { public interface GameTypes {
String[] getPlayerTypes(); PlayerType[] getPlayerTypes();
List<GameTypeView> getGameTypes(); List<GameTypeView> getGameTypes();
List<GameTypeView> getTournamentGameTypes(); List<GameTypeView> getTournamentGameTypes();

View file

@ -30,6 +30,7 @@ package mage.remote.interfaces;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.players.PlayerType;
import mage.remote.MageRemoteException; import mage.remote.MageRemoteException;
import mage.view.TableView; import mage.view.TableView;
import mage.view.TournamentView; import mage.view.TournamentView;
@ -64,13 +65,13 @@ public interface PlayerActions {
// boolean startChallenge(UUID roomId, UUID tableId, UUID challengeId); // boolean startChallenge(UUID roomId, UUID tableId, UUID challengeId);
boolean joinTournamentTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList, String password); boolean joinTournamentTable(UUID roomId, UUID tableId, String playerName, PlayerType playerType, int skill, DeckCardLists deckList, String password);
boolean watchTable(UUID roomId, UUID tableId); boolean watchTable(UUID roomId, UUID tableId);
boolean watchTournamentTable(UUID tableId); boolean watchTournamentTable(UUID tableId);
boolean joinTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList, String password); boolean joinTable(UUID roomId, UUID tableId, String playerName, PlayerType playerType, int skill, DeckCardLists deckList, String password);
Optional<TableView> getTable(UUID roomId, UUID tableId); Optional<TableView> getTable(UUID roomId, UUID tableId);

View file

@ -27,10 +27,12 @@
*/ */
package mage.view; package mage.view;
import mage.game.Seat;
import mage.players.PlayerType;
import mage.players.net.UserData;
import java.io.Serializable; import java.io.Serializable;
import java.util.UUID; import java.util.UUID;
import mage.game.Seat;
import mage.players.net.UserData;
/** /**
* *
@ -43,7 +45,7 @@ public class SeatView implements Serializable {
private final String flagName; private final String flagName;
private UUID playerId; private UUID playerId;
private final String playerName; private final String playerName;
private final String playerType; private final PlayerType playerType;
private final String history; private final String history;
private final int generalRating; private final int generalRating;
private final int constructedRating; private final int constructedRating;
@ -86,7 +88,7 @@ public class SeatView implements Serializable {
return playerName; return playerName;
} }
public String getPlayerType() { public PlayerType getPlayerType() {
return playerType; return playerType;
} }

View file

@ -27,10 +27,6 @@
*/ */
package mage.server; package mage.server;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mage.cards.repository.CardInfo; import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository; import mage.cards.repository.CardRepository;
import mage.server.exceptions.UserNotFoundException; import mage.server.exceptions.UserNotFoundException;
@ -40,6 +36,11 @@ import mage.view.ChatMessage.MessageType;
import mage.view.ChatMessage.SoundToPlay; import mage.view.ChatMessage.SoundToPlay;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */

View file

@ -61,7 +61,7 @@ public class ChatSession {
} }
public void join(UUID userId) { public void join(UUID userId) {
UserManager.instance.getUser(userId).ifPresent(user-> { UserManager.instance.getUser(userId).ifPresent(user -> {
if (!clients.containsKey(userId)) { if (!clients.containsKey(userId)) {
String userName = user.getName(); String userName = user.getName();
clients.put(userId, userName); clients.put(userId, userName);
@ -139,24 +139,20 @@ public class ChatSession {
public void broadcast(String userName, String message, MessageColor color, boolean withTime, MessageType messageType, SoundToPlay soundToPlay) { public void broadcast(String userName, String message, MessageColor color, boolean withTime, MessageType messageType, SoundToPlay soundToPlay) {
if (!message.isEmpty()) { if (!message.isEmpty()) {
HashSet<UUID> clientsToRemove = null; HashSet<UUID> clientsToRemove = new HashSet<>();
ClientCallback clientCallback = new ClientCallback("chatMessage", chatId, new ChatMessage(userName, message, (withTime ? timeFormatter.format(new Date()) : ""), color, messageType, soundToPlay)); ClientCallback clientCallback = new ClientCallback("chatMessage", chatId, new ChatMessage(userName, message, (withTime ? timeFormatter.format(new Date()) : ""), color, messageType, soundToPlay));
for (UUID userId : clients.keySet()) { for (UUID userId : clients.keySet()) {
Optional<User> user = UserManager.instance.getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (user.isPresent()) { if (user.isPresent()) {
user.get().fireCallback(clientCallback); user.get().fireCallback(clientCallback);
} else { } else {
if (clientsToRemove == null) {
clientsToRemove = new HashSet<>(); clientsToRemove = new HashSet<>();
} }
clientsToRemove.add(userId);
} }
}
if (clientsToRemove != null) {
for (UUID userIdToRemove : clientsToRemove) { for (UUID userIdToRemove : clientsToRemove) {
clients.remove(userIdToRemove); clients.remove(userIdToRemove);
} }
}
} }
} }

View file

@ -6,5 +6,11 @@ package mage.server;
*/ */
public enum DisconnectReason { public enum DisconnectReason {
LostConnection, Disconnected, CleaningUp, ConnectingOtherInstance, AdminDisconnect, SessionExpired, Undefined LostConnection,
Disconnected,
CleaningUp,
ConnectingOtherInstance,
AdminDisconnect,
SessionExpired,
Undefined
} }

View file

@ -45,6 +45,7 @@ import mage.interfaces.ActionWithResult;
import mage.interfaces.MageServer; import mage.interfaces.MageServer;
import mage.interfaces.ServerState; import mage.interfaces.ServerState;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.players.PlayerType;
import mage.players.net.UserData; import mage.players.net.UserData;
import mage.remote.MageVersionException; import mage.remote.MageVersionException;
import mage.server.draft.CubeFactory; import mage.server.draft.CubeFactory;
@ -74,7 +75,7 @@ import java.util.concurrent.ExecutorService;
public class MageServerImpl implements MageServer { public class MageServerImpl implements MageServer {
private static final Logger logger = Logger.getLogger(MageServerImpl.class); private static final Logger logger = Logger.getLogger(MageServerImpl.class);
private static final ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor(); private static final ExecutorService callExecutor = ThreadExecutor.instance.getCallExecutor();
private static final SecureRandom RANDOM = new SecureRandom(); private static final SecureRandom RANDOM = new SecureRandom();
private final String adminPassword; private final String adminPassword;
@ -233,8 +234,8 @@ public class MageServerImpl implements MageServer {
String maxAiOpponents = ConfigSettings.instance.getMaxAiOpponents(); String maxAiOpponents = ConfigSettings.instance.getMaxAiOpponents();
if (maxAiOpponents != null) { if (maxAiOpponents != null) {
int aiPlayers = 0; int aiPlayers = 0;
for (String playerType : options.getPlayerTypes()) { for (PlayerType playerType : options.getPlayerTypes()) {
if (!playerType.equals("Human")) { if (playerType != PlayerType.HUMAN) {
aiPlayers++; aiPlayers++;
} }
} }
@ -282,7 +283,7 @@ public class MageServerImpl implements MageServer {
} }
@Override @Override
public boolean joinTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) throws MageException, GameException { public boolean joinTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final PlayerType playerType, final int skill, final DeckCardLists deckList, final String password) throws MageException, GameException {
return executeWithResult("joinTable", sessionId, new ActionWithBooleanResult() { return executeWithResult("joinTable", sessionId, new ActionWithBooleanResult() {
@Override @Override
public Boolean execute() throws MageException { public Boolean execute() throws MageException {
@ -309,7 +310,7 @@ public class MageServerImpl implements MageServer {
} }
@Override @Override
public boolean joinTournamentTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) throws MageException, GameException { public boolean joinTournamentTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final PlayerType playerType, final int skill, final DeckCardLists deckList, final String password) throws MageException, GameException {
return executeWithResult("joinTournamentTable", sessionId, new ActionWithBooleanResult() { return executeWithResult("joinTournamentTable", sessionId, new ActionWithBooleanResult() {
@Override @Override
public Boolean execute() throws MageException { public Boolean execute() throws MageException {
@ -989,11 +990,11 @@ public class MageServerImpl implements MageServer {
public ServerState getServerState() throws MageException { public ServerState getServerState() throws MageException {
try { try {
return new ServerState( return new ServerState(
GameFactory.getInstance().getGameTypes(), GameFactory.instance.getGameTypes(),
TournamentFactory.getInstance().getTournamentTypes(), TournamentFactory.instance.getTournamentTypes(),
PlayerFactory.getInstance().getPlayerTypes().toArray(new String[PlayerFactory.getInstance().getPlayerTypes().size()]), PlayerFactory.instance.getPlayerTypes().toArray(new PlayerType[PlayerFactory.instance.getPlayerTypes().size()]),
DeckValidatorFactory.getInstance().getDeckTypes().toArray(new String[DeckValidatorFactory.getInstance().getDeckTypes().size()]), DeckValidatorFactory.instance.getDeckTypes().toArray(new String[DeckValidatorFactory.instance.getDeckTypes().size()]),
CubeFactory.getInstance().getDraftCubes().toArray(new String[CubeFactory.getInstance().getDraftCubes().size()]), CubeFactory.instance.getDraftCubes().toArray(new String[CubeFactory.instance.getDraftCubes().size()]),
testMode, testMode,
Main.getVersion(), Main.getVersion(),
CardRepository.instance.getContentVersionConstant(), CardRepository.instance.getContentVersionConstant(),

View file

@ -62,7 +62,6 @@ import org.w3c.dom.Element;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.util.*; import java.util.*;
@ -164,31 +163,31 @@ public final class Main {
deleteSavedGames(); deleteSavedGames();
ConfigSettings config = ConfigSettings.instance; ConfigSettings config = ConfigSettings.instance;
for (GamePlugin plugin : config.getGameTypes()) { for (GamePlugin plugin : config.getGameTypes()) {
GameFactory.getInstance().addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin)); GameFactory.instance.addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin));
} }
for (GamePlugin plugin : config.getTournamentTypes()) { for (GamePlugin plugin : config.getTournamentTypes()) {
TournamentFactory.getInstance().addTournamentType(plugin.getName(), loadTournamentType(plugin), loadPlugin(plugin)); TournamentFactory.instance.addTournamentType(plugin.getName(), loadTournamentType(plugin), loadPlugin(plugin));
} }
for (Plugin plugin : config.getPlayerTypes()) { for (Plugin plugin : config.getPlayerTypes()) {
PlayerFactory.getInstance().addPlayerType(plugin.getName(), loadPlugin(plugin)); PlayerFactory.instance.addPlayerType(plugin.getName(), loadPlugin(plugin));
} }
for (Plugin plugin : config.getDraftCubes()) { for (Plugin plugin : config.getDraftCubes()) {
CubeFactory.getInstance().addDraftCube(plugin.getName(), loadPlugin(plugin)); CubeFactory.instance.addDraftCube(plugin.getName(), loadPlugin(plugin));
} }
for (Plugin plugin : config.getDeckTypes()) { for (Plugin plugin : config.getDeckTypes()) {
DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin)); DeckValidatorFactory.instance.addDeckType(plugin.getName(), loadPlugin(plugin));
} }
for (ExtensionPackage pkg : extensions) { for (ExtensionPackage pkg : extensions) {
Map<String, Class> draftCubes = pkg.getDraftCubes(); Map<String, Class> draftCubes = pkg.getDraftCubes();
for (String name : draftCubes.keySet()) { for (String name : draftCubes.keySet()) {
logger.info("Loading extension: [" + name + "] " + draftCubes.get(name).toString()); logger.info("Loading extension: [" + name + "] " + draftCubes.get(name).toString());
CubeFactory.getInstance().addDraftCube(name, draftCubes.get(name)); CubeFactory.instance.addDraftCube(name, draftCubes.get(name));
} }
Map<String, Class> deckTypes = pkg.getDeckTypes(); Map<String, Class> deckTypes = pkg.getDeckTypes();
for (String name : deckTypes.keySet()) { for (String name : deckTypes.keySet()) {
logger.info("Loading extension: [" + name + "] " + deckTypes.get(name)); logger.info("Loading extension: [" + name + "] " + deckTypes.get(name));
DeckValidatorFactory.getInstance().addDeckType(name, deckTypes.get(name)); DeckValidatorFactory.instance.addDeckType(name, deckTypes.get(name));
} }
} }

View file

@ -45,6 +45,7 @@ import mage.game.tournament.Tournament;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.game.tournament.TournamentPlayer; import mage.game.tournament.TournamentPlayer;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import mage.server.draft.DraftManager; import mage.server.draft.DraftManager;
import mage.server.game.DeckValidatorFactory; import mage.server.game.DeckValidatorFactory;
import mage.server.game.GameFactory; import mage.server.game.GameFactory;
@ -87,12 +88,12 @@ public class TableController {
private Tournament tournament; private Tournament tournament;
private ScheduledFuture<?> futureTimeout; private ScheduledFuture<?> futureTimeout;
protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.instance.getTimeoutExecutor();
public TableController(UUID roomId, UUID userId, MatchOptions options) { public TableController(UUID roomId, UUID userId, MatchOptions options) {
this.userId = userId; this.userId = userId;
this.options = options; this.options = options;
match = GameFactory.getInstance().createMatch(options.getGameType(), options); match = GameFactory.instance.createMatch(options.getGameType(), options);
if (userId != null) { if (userId != null) {
Optional<User> user = UserManager.instance.getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
// TODO: Handle if user == null // TODO: Handle if user == null
@ -100,14 +101,14 @@ public class TableController {
} else { } else {
controllerName = "System"; controllerName = "System";
} }
table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), TableRecorderImpl.getInstance(), match, options.getBannedUsers()); table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.instance.createDeckValidator(options.getDeckType()), options.getPlayerTypes(), TableRecorderImpl.instance, match, options.getBannedUsers());
chatId = ChatManager.instance.createChatSession("Match Table " + table.getId()); chatId = ChatManager.instance.createChatSession("Match Table " + table.getId());
init(); init();
} }
public TableController(UUID roomId, UUID userId, TournamentOptions options) { public TableController(UUID roomId, UUID userId, TournamentOptions options) {
this.userId = userId; this.userId = userId;
tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options); tournament = TournamentFactory.instance.createTournament(options.getTournamentType(), options);
if (userId != null) { if (userId != null) {
Optional<User> user = UserManager.instance.getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (!user.isPresent()) { if (!user.isPresent()) {
@ -119,7 +120,7 @@ public class TableController {
} else { } else {
controllerName = "System"; controllerName = "System";
} }
table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), TableRecorderImpl.getInstance(), tournament, options.getMatchOptions().getBannedUsers()); table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.instance.createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), TableRecorderImpl.instance, tournament, options.getMatchOptions().getBannedUsers());
chatId = ChatManager.instance.createChatSession("Tourn. table " + table.getId()); chatId = ChatManager.instance.createChatSession("Tourn. table " + table.getId());
} }
@ -139,7 +140,7 @@ public class TableController {
); );
} }
public synchronized boolean joinTournament(UUID userId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws GameException { public synchronized boolean joinTournament(UUID userId, String name, PlayerType playerType, int skill, DeckCardLists deckList, String password) throws GameException {
if (table.getState() != TableState.WAITING) { if (table.getState() != TableState.WAITING) {
return false; return false;
} }
@ -155,13 +156,13 @@ public class TableController {
} }
User user = _user.get(); User user = _user.get();
// check password // check password
if (!table.getTournament().getOptions().getPassword().isEmpty() && playerType.equals("Human")) { if (!table.getTournament().getOptions().getPassword().isEmpty() && playerType == PlayerType.HUMAN) {
if (!table.getTournament().getOptions().getPassword().equals(password)) { if (!table.getTournament().getOptions().getPassword().equals(password)) {
user.showUserMessage("Join Table", "Wrong password."); user.showUserMessage("Join Table", "Wrong password.");
return false; return false;
} }
} }
if (userPlayerMap.containsKey(userId) && playerType.equals("Human")) { if (userPlayerMap.containsKey(userId) && playerType == PlayerType.HUMAN) {
user.showUserMessage("Join Table", "You can join a table only one time."); user.showUserMessage("Join Table", "You can join a table only one time.");
return false; return false;
} }
@ -228,7 +229,7 @@ public class TableController {
return userPlayerMap.containsKey(userId); return userPlayerMap.containsKey(userId);
} }
public synchronized boolean replaceDraftPlayer(Player oldPlayer, String name, String playerType, int skill) { public synchronized boolean replaceDraftPlayer(Player oldPlayer, String name, PlayerType playerType, int skill) {
Optional<Player> newPlayerOpt = createPlayer(name, playerType, skill); Optional<Player> newPlayerOpt = createPlayer(name, playerType, skill);
if (!newPlayerOpt.isPresent() || table.getState() != TableState.DRAFTING) { if (!newPlayerOpt.isPresent() || table.getState() != TableState.DRAFTING) {
return false; return false;
@ -246,13 +247,13 @@ public class TableController {
return true; return true;
} }
public synchronized boolean joinTable(UUID userId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException { public synchronized boolean joinTable(UUID userId, String name, PlayerType playerType, int skill, DeckCardLists deckList, String password) throws MageException {
Optional<User> _user = UserManager.instance.getUser(userId); Optional<User> _user = UserManager.instance.getUser(userId);
if (!_user.isPresent()) { if (!_user.isPresent()) {
return false; return false;
} }
User user = _user.get(); User user = _user.get();
if (userPlayerMap.containsKey(userId) && playerType.equals("Human")) { if (userPlayerMap.containsKey(userId) && playerType == PlayerType.HUMAN) {
user.showUserMessage("Join Table", new StringBuilder("You can join a table only one time.").toString()); user.showUserMessage("Join Table", new StringBuilder("You can join a table only one time.").toString());
return false; return false;
} }
@ -261,7 +262,7 @@ public class TableController {
return false; return false;
} }
// check password // check password
if (!table.getMatch().getOptions().getPassword().isEmpty() && playerType.equals("Human")) { if (!table.getMatch().getOptions().getPassword().isEmpty() && playerType == PlayerType.HUMAN) {
if (!table.getMatch().getOptions().getPassword().equals(password)) { if (!table.getMatch().getOptions().getPassword().equals(password)) {
user.showUserMessage("Join Table", "Wrong password."); user.showUserMessage("Join Table", "Wrong password.");
return false; return false;
@ -370,7 +371,7 @@ public class TableController {
return true; return true;
} }
public void addPlayer(UUID userId, Player player, String playerType, Deck deck) throws GameException { public void addPlayer(UUID userId, Player player, PlayerType playerType, Deck deck) throws GameException {
if (table.getState() != TableState.WAITING) { if (table.getState() != TableState.WAITING) {
return; return;
} }
@ -480,12 +481,12 @@ public class TableController {
// ReplayManager.instance.replayGame(table.getId(), userId); // ReplayManager.instance.replayGame(table.getId(), userId);
// return true; // return true;
// } // }
private Optional<Player> createPlayer(String name, String playerType, int skill) { private Optional<Player> createPlayer(String name, PlayerType playerType, int skill) {
Optional<Player> playerOpt; Optional<Player> playerOpt;
if (options == null) { if (options == null) {
playerOpt = PlayerFactory.getInstance().createPlayer(playerType, name, RangeOfInfluence.ALL, skill); playerOpt = PlayerFactory.instance.createPlayer(playerType, name, RangeOfInfluence.ALL, skill);
} else { } else {
playerOpt = PlayerFactory.getInstance().createPlayer(playerType, name, options.getRange(), skill); playerOpt = PlayerFactory.instance.createPlayer(playerType, name, options.getRange(), skill);
} }
if (playerOpt.isPresent()) { if (playerOpt.isPresent()) {
Player player = playerOpt.get(); Player player = playerOpt.get();
@ -876,7 +877,7 @@ public class TableController {
if (table.getState() == TableState.READY_TO_START) { if (table.getState() == TableState.READY_TO_START) {
if (seatNum1 >= 0 && seatNum2 >= 0 && seatNum1 < table.getSeats().length && seatNum2 < table.getSeats().length) { if (seatNum1 >= 0 && seatNum2 >= 0 && seatNum1 < table.getSeats().length && seatNum2 < table.getSeats().length) {
Player swapPlayer = table.getSeats()[seatNum1].getPlayer(); Player swapPlayer = table.getSeats()[seatNum1].getPlayer();
String swapType = table.getSeats()[seatNum1].getPlayerType(); PlayerType swapType = table.getSeats()[seatNum1].getPlayerType();
table.getSeats()[seatNum1].setPlayer(table.getSeats()[seatNum2].getPlayer()); table.getSeats()[seatNum1].setPlayer(table.getSeats()[seatNum2].getPlayer());
table.getSeats()[seatNum1].setPlayerType(table.getSeats()[seatNum2].getPlayerType()); table.getSeats()[seatNum1].setPlayerType(table.getSeats()[seatNum2].getPlayerType());
table.getSeats()[seatNum2].setPlayer(swapPlayer); table.getSeats()[seatNum2].setPlayer(swapPlayer);

View file

@ -28,17 +28,7 @@
package mage.server; package mage.server;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import mage.MageException; import mage.MageException;
import mage.cards.decks.Deck;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.constants.TableState; import mage.constants.TableState;
import mage.game.Game; import mage.game.Game;
@ -50,13 +40,22 @@ import mage.game.match.MatchOptions;
import mage.game.tournament.Tournament; import mage.game.tournament.Tournament;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.game.tournament.TournamentPlayer; import mage.game.tournament.TournamentPlayer;
import mage.players.Player; import mage.players.PlayerType;
import mage.server.game.GameController; import mage.server.game.GameController;
import mage.server.game.GameManager; import mage.server.game.GameManager;
import mage.server.game.GamesRoomManager; import mage.server.game.GamesRoomManager;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -133,14 +132,14 @@ public enum TableManager {
return Optional.empty(); return Optional.empty();
} }
public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException { public boolean joinTable(UUID userId, UUID tableId, String name, PlayerType playerType, int skill, DeckCardLists deckList, String password) throws MageException {
if (controllers.containsKey(tableId)) { if (controllers.containsKey(tableId)) {
return controllers.get(tableId).joinTable(userId, name, playerType, skill, deckList, password); return controllers.get(tableId).joinTable(userId, name, playerType, skill, deckList, password);
} }
return false; return false;
} }
public boolean joinTournament(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws GameException { public boolean joinTournament(UUID userId, UUID tableId, String name, PlayerType playerType, int skill, DeckCardLists deckList, String password) throws GameException {
if (controllers.containsKey(tableId)) { if (controllers.containsKey(tableId)) {
return controllers.get(tableId).joinTournament(userId, name, playerType, skill, deckList, password); return controllers.get(tableId).joinTournament(userId, name, playerType, skill, deckList, password);
} }
@ -376,7 +375,7 @@ public enum TableManager {
logger.debug(chatSession.getChatId() + " " + formatter.format(chatSession.getCreateTime()) + ' ' + chatSession.getInfo() + ' ' + chatSession.getClients().values().toString()); logger.debug(chatSession.getChatId() + " " + formatter.format(chatSession.getCreateTime()) + ' ' + chatSession.getInfo() + ' ' + chatSession.getClients().values().toString());
} }
logger.debug("------- Games: " + GameManager.instance.getNumberActiveGames() + " --------------------------------------------"); logger.debug("------- Games: " + GameManager.instance.getNumberActiveGames() + " --------------------------------------------");
logger.debug(" Active Game Worker: " + ThreadExecutor.getInstance().getActiveThreads(ThreadExecutor.getInstance().getGameExecutor())); logger.debug(" Active Game Worker: " + ThreadExecutor.instance.getActiveThreads(ThreadExecutor.instance.getGameExecutor()));
for (Entry<UUID, GameController> entry : GameManager.instance.getGameController().entrySet()) { for (Entry<UUID, GameController> entry : GameManager.instance.getGameController().entrySet()) {
logger.debug(entry.getKey() + entry.getValue().getPlayerNameList()); logger.debug(entry.getKey() + entry.getValue().getPlayerNameList());
} }

View file

@ -51,7 +51,7 @@ public enum UserManager {
private final ConcurrentHashMap<UUID, User> users = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, User> users = new ConcurrentHashMap<>();
private static final ExecutorService USER_EXECUTOR = ThreadExecutor.getInstance().getCallExecutor(); private static final ExecutorService USER_EXECUTOR = ThreadExecutor.instance.getCallExecutor();
UserManager() { UserManager() {
expireExecutor.scheduleAtFixedRate(this::checkExpired, 60, 60, TimeUnit.SECONDS); expireExecutor.scheduleAtFixedRate(this::checkExpired, 60, 60, TimeUnit.SECONDS);

View file

@ -1,10 +1,11 @@
package mage.server.challenge; package mage.server.challenge;
import mage.constants.Zone;
import mage.game.match.Match;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import mage.constants.Zone;
import mage.game.match.Match;
/** /**
* C U R R E N T L Y U N U S E D * C U R R E N T L Y U N U S E D
@ -12,13 +13,9 @@ import mage.game.match.Match;
* Loads challenges from scenarios. * Loads challenges from scenarios.
* Configure games by initializing starting game board. * Configure games by initializing starting game board.
*/ */
public class ChallengeManager { public enum ChallengeManager {
public static final ChallengeManager instance = new ChallengeManager(); instance;
public static ChallengeManager getInstance() {
return instance;
}
public void prepareChallenge(UUID playerId, Match match) { public void prepareChallenge(UUID playerId, Match match) {
Map<Zone, String> commands = new HashMap<>(); Map<Zone, String> commands = new HashMap<>();

View file

@ -27,30 +27,27 @@
*/ */
package mage.server.draft; package mage.server.draft;
import mage.cards.decks.Deck;
import mage.game.draft.DraftCube;
import org.apache.log4j.Logger;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import mage.cards.decks.Deck;
import mage.game.draft.DraftCube;
import org.apache.log4j.Logger;
/** /**
* *
* @author LevelX2 * @author LevelX2
*/ */
public class CubeFactory { public enum CubeFactory {
private static final CubeFactory INSTANCE = new CubeFactory(); instance;
private static final Logger logger = Logger.getLogger(CubeFactory.class); private static final Logger logger = Logger.getLogger(CubeFactory.class);
private final Map<String, Class> draftCubes = new LinkedHashMap<>(); private final Map<String, Class> draftCubes = new LinkedHashMap<>();
public static CubeFactory getInstance() {
return INSTANCE;
}
private CubeFactory() {}
public DraftCube createDraftCube(String draftCubeName) { public DraftCube createDraftCube(String draftCubeName) {

View file

@ -28,12 +28,6 @@
package mage.server.draft; package mage.server.draft;
import java.io.File;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import mage.MageException; import mage.MageException;
import mage.game.draft.Draft; import mage.game.draft.Draft;
import mage.game.draft.DraftPlayer; import mage.game.draft.DraftPlayer;
@ -48,6 +42,13 @@ import mage.server.util.ThreadExecutor;
import mage.view.DraftPickView; import mage.view.DraftPickView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.io.File;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
@ -152,7 +153,7 @@ public class DraftController {
private synchronized void checkStart() { private synchronized void checkStart() {
if (!draft.isStarted() && allJoined()) { if (!draft.isStarted() && allJoined()) {
draft.setStarted(); draft.setStarted();
ThreadExecutor.getInstance().getCallExecutor().execute(this::startDraft); ThreadExecutor.instance.getCallExecutor().execute(this::startDraft);
} }
} }

View file

@ -28,14 +28,6 @@
package mage.server.draft; package mage.server.draft;
import java.rmi.RemoteException;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import mage.game.draft.Draft; import mage.game.draft.Draft;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.server.User; import mage.server.User;
@ -46,6 +38,14 @@ import mage.view.DraftPickView;
import mage.view.DraftView; import mage.view.DraftView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.rmi.RemoteException;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -60,7 +60,7 @@ public class DraftSession {
protected UUID markedCard; protected UUID markedCard;
private ScheduledFuture<?> futureTimeout; private ScheduledFuture<?> futureTimeout;
protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.instance.getTimeoutExecutor();
public DraftSession(Draft draft, UUID userId, UUID playerId) { public DraftSession(Draft draft, UUID userId, UUID playerId) {
this.userId = userId; this.userId = userId;

View file

@ -28,27 +28,26 @@
package mage.server.game; package mage.server.game;
import mage.cards.decks.DeckValidator;
import org.apache.log4j.Logger;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import mage.cards.decks.DeckValidator;
import org.apache.log4j.Logger;
/** /**
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class DeckValidatorFactory { public enum DeckValidatorFactory {
private static final DeckValidatorFactory INSTANCE = new DeckValidatorFactory(); instance;
private static final Logger logger = Logger.getLogger(DeckValidatorFactory.class); private static final Logger logger = Logger.getLogger(DeckValidatorFactory.class);
private final Map<String, Class> deckTypes = new LinkedHashMap<>(); private final Map<String, Class> deckTypes = new LinkedHashMap<>();
public static DeckValidatorFactory getInstance() {
return INSTANCE;
}
private DeckValidatorFactory() {} private DeckValidatorFactory() {}

View file

@ -27,23 +27,6 @@
*/ */
package mage.server.game; package mage.server.game;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
import mage.MageException; import mage.MageException;
import mage.abilities.Ability; import mage.abilities.Ability;
import mage.cards.Card; import mage.cards.Card;
@ -66,37 +49,35 @@ import mage.game.events.TableEvent;
import mage.game.permanent.Permanent; import mage.game.permanent.Permanent;
import mage.interfaces.Action; import mage.interfaces.Action;
import mage.players.Player; import mage.players.Player;
import mage.server.ChatManager; import mage.server.*;
import mage.server.Main;
import mage.server.TableManager;
import mage.server.User;
import mage.server.UserManager;
import mage.server.util.ConfigSettings; import mage.server.util.ConfigSettings;
import mage.server.util.Splitter; import mage.server.util.Splitter;
import mage.server.util.SystemUtil; import mage.server.util.SystemUtil;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.utils.timer.PriorityTimer; import mage.utils.timer.PriorityTimer;
import mage.view.AbilityPickerView; import mage.view.*;
import mage.view.CardsView;
import mage.view.ChatMessage;
import mage.view.ChatMessage.MessageColor; import mage.view.ChatMessage.MessageColor;
import mage.view.ChatMessage.MessageType; import mage.view.ChatMessage.MessageType;
import mage.view.GameView;
import mage.view.PermanentView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.zip.GZIPOutputStream;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class GameController implements GameCallback { public class GameController implements GameCallback {
private static final ExecutorService gameExecutor = ThreadExecutor.getInstance().getGameExecutor(); private static final ExecutorService gameExecutor = ThreadExecutor.instance.getGameExecutor();
private static final Logger logger = Logger.getLogger(GameController.class); private static final Logger logger = Logger.getLogger(GameController.class);
protected final ScheduledExecutorService joinWaitingExecutor = Executors.newSingleThreadScheduledExecutor(); protected final ScheduledExecutorService joinWaitingExecutor = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> futureTimeout; private ScheduledFuture<?> futureTimeout;
protected static final ScheduledExecutorService timeoutIdleExecutor = ThreadExecutor.getInstance().getTimeoutIdleExecutor(); protected static final ScheduledExecutorService timeoutIdleExecutor = ThreadExecutor.instance.getTimeoutIdleExecutor();
private final ConcurrentHashMap<UUID, GameSessionPlayer> gameSessions = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, GameSessionPlayer> gameSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<UUID, GameSessionWatcher> watchers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, GameSessionWatcher> watchers = new ConcurrentHashMap<>();
@ -388,7 +369,7 @@ public class GameController implements GameCallback {
private void checkStart() { private void checkStart() {
if (allJoined()) { if (allJoined()) {
joinWaitingExecutor.shutdownNow(); joinWaitingExecutor.shutdownNow();
ThreadExecutor.getInstance().getCallExecutor().execute(this::startGame); ThreadExecutor.instance.getCallExecutor().execute(this::startGame);
} }
} }

View file

@ -28,24 +28,25 @@
package mage.server.game; package mage.server.game;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mage.game.match.Match; import mage.game.match.Match;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.game.match.MatchType; import mage.game.match.MatchType;
import mage.view.GameTypeView; import mage.view.GameTypeView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class GameFactory { public enum GameFactory {
private static final GameFactory INSTANCE = new GameFactory(); instance;
private static final Logger logger = Logger.getLogger(GameFactory.class); private static final Logger logger = Logger.getLogger(GameFactory.class);
private final Map<String, Class<Match>> games = new HashMap<>(); private final Map<String, Class<Match>> games = new HashMap<>();
@ -53,9 +54,6 @@ public class GameFactory {
private final List<GameTypeView> gameTypeViews = new ArrayList<>(); private final List<GameTypeView> gameTypeViews = new ArrayList<>();
public static GameFactory getInstance() {
return INSTANCE;
}
private GameFactory() {} private GameFactory() {}

View file

@ -27,10 +27,6 @@
*/ */
package mage.server.game; package mage.server.game;
import java.io.Serializable;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import mage.cards.Cards; import mage.cards.Cards;
import mage.choices.Choice; import mage.choices.Choice;
import mage.constants.ManaType; import mage.constants.ManaType;
@ -45,6 +41,11 @@ import mage.server.util.ThreadExecutor;
import mage.view.*; import mage.view.*;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.io.Serializable;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -54,7 +55,7 @@ public class GameSessionPlayer extends GameSessionWatcher {
private final UUID playerId; private final UUID playerId;
private static final ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor(); private static final ExecutorService callExecutor = ThreadExecutor.instance.getCallExecutor();
public GameSessionPlayer(Game game, UUID userId, UUID playerId) { public GameSessionPlayer(Game game, UUID userId, UUID playerId) {
super(userId, game, true); super(userId, game, true);

View file

@ -28,19 +28,21 @@
package mage.server.game; package mage.server.game;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import mage.MageException; import mage.MageException;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.game.GameException; import mage.game.GameException;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.players.PlayerType;
import mage.server.Room; import mage.server.Room;
import mage.view.MatchView; import mage.view.MatchView;
import mage.view.RoomUsersView; import mage.view.RoomUsersView;
import mage.view.TableView; import mage.view.TableView;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/** /**
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
@ -50,8 +52,8 @@ public interface GamesRoom extends Room {
List<TableView> getTables(); List<TableView> getTables();
List<MatchView> getFinished(); List<MatchView> getFinished();
List<RoomUsersView> getRoomUsersInfo(); List<RoomUsersView> getRoomUsersInfo();
boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException; boolean joinTable(UUID userId, UUID tableId, String name, PlayerType playerType, int skill, DeckCardLists deckList, String password) throws MageException;
boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws GameException; boolean joinTournamentTable(UUID userId, UUID tableId, String name, PlayerType playerType, int skill, DeckCardLists deckList, String password) throws GameException;
TableView createTable(UUID userId, MatchOptions options); TableView createTable(UUID userId, MatchOptions options);
TableView createTournamentTable(UUID userId, TournamentOptions options); TableView createTournamentTable(UUID userId, TournamentOptions options);
void removeTable(UUID userId, UUID tableId); void removeTable(UUID userId, UUID tableId);

View file

@ -27,13 +27,6 @@
*/ */
package mage.server.game; package mage.server.game;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import mage.MageException; import mage.MageException;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.constants.TableState; import mage.constants.TableState;
@ -41,6 +34,7 @@ import mage.game.GameException;
import mage.game.Table; import mage.game.Table;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.players.PlayerType;
import mage.server.RoomImpl; import mage.server.RoomImpl;
import mage.server.TableManager; import mage.server.TableManager;
import mage.server.User; import mage.server.User;
@ -54,6 +48,13 @@ import mage.view.TableView;
import mage.view.UsersView; import mage.view.UsersView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -133,7 +134,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
List<RoomUsersView> roomUserInfo = new ArrayList<>(); List<RoomUsersView> roomUserInfo = new ArrayList<>();
roomUserInfo.add(new RoomUsersView(users, roomUserInfo.add(new RoomUsersView(users,
GameManager.instance.getNumberActiveGames(), GameManager.instance.getNumberActiveGames(),
ThreadExecutor.getInstance().getActiveThreads(ThreadExecutor.getInstance().getGameExecutor()), ThreadExecutor.instance.getActiveThreads(ThreadExecutor.instance.getGameExecutor()),
ConfigSettings.instance.getMaxGameThreads() ConfigSettings.instance.getMaxGameThreads()
)); ));
roomUsersView = roomUserInfo; roomUsersView = roomUserInfo;
@ -145,7 +146,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
} }
@Override @Override
public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException { public boolean joinTable(UUID userId, UUID tableId, String name, PlayerType playerType, int skill, DeckCardLists deckList, String password) throws MageException {
if (tables.containsKey(tableId)) { if (tables.containsKey(tableId)) {
return TableManager.instance.joinTable(userId, tableId, name, playerType, skill, deckList, password); return TableManager.instance.joinTable(userId, tableId, name, playerType, skill, deckList, password);
} else { } else {
@ -161,7 +162,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
} }
@Override @Override
public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws GameException { public boolean joinTournamentTable(UUID userId, UUID tableId, String name, PlayerType playerType, int skill, DeckCardLists deckList, String password) throws GameException {
if (tables.containsKey(tableId)) { if (tables.containsKey(tableId)) {
return TableManager.instance.joinTournament(userId, tableId, name, playerType, skill, deckList, password); return TableManager.instance.joinTournament(userId, tableId, name, playerType, skill, deckList, password);
} else { } else {

View file

@ -30,32 +30,26 @@ package mage.server.game;
import mage.constants.RangeOfInfluence; import mage.constants.RangeOfInfluence;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.util.LinkedHashMap; import java.util.EnumMap;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class PlayerFactory { public enum PlayerFactory {
private static final PlayerFactory INSTANCE = new PlayerFactory(); instance;
private static final Logger logger = Logger.getLogger(PlayerFactory.class); private static final Logger logger = Logger.getLogger(PlayerFactory.class);
private final Map<String, Class> playerTypes = new LinkedHashMap<>(); private final EnumMap<PlayerType, Class> playerTypes = new EnumMap<>(PlayerType.class);
public static PlayerFactory getInstance() {
return INSTANCE;
}
private PlayerFactory() {} public Optional<Player> createPlayer(PlayerType playerType, String name, RangeOfInfluence range, int skill) {
public Optional<Player> createPlayer(String playerType, String name, RangeOfInfluence range, int skill) {
try { try {
Class playerTypeClass = playerTypes.get(playerType); Class playerTypeClass = playerTypes.get(playerType);
if (playerTypeClass != null) { if (playerTypeClass != null) {
@ -63,8 +57,7 @@ public class PlayerFactory {
Player player = (Player) con.newInstance(name, range, skill); Player player = (Player) con.newInstance(name, range, skill);
logger.trace("Player created: " + name + " - " + player.getId()); logger.trace("Player created: " + name + " - " + player.getId());
return Optional.of(player); return Optional.of(player);
} } else {
else {
logger.fatal("Unknown player type: " + playerType); logger.fatal("Unknown player type: " + playerType);
} }
} catch (Exception ex) { } catch (Exception ex) {
@ -73,13 +66,16 @@ public class PlayerFactory {
return Optional.empty(); return Optional.empty();
} }
public Set<String> getPlayerTypes() { public Set<PlayerType> getPlayerTypes() {
return playerTypes.keySet(); return playerTypes.keySet();
} }
public void addPlayerType(String name, Class playerType) { public void addPlayerType(String name, Class playerType) {
PlayerType type = PlayerType.getByDescription(name);
if (type != null) {
if (playerType != null) { if (playerType != null) {
this.playerTypes.put(name, playerType); this.playerTypes.put(type, playerType);
}
} }
} }

View file

@ -5,13 +5,9 @@ import mage.game.Table.TableRecorder;
import mage.game.result.ResultProtos.TableProto; import mage.game.result.ResultProtos.TableProto;
import mage.server.UserManager; import mage.server.UserManager;
public class TableRecorderImpl implements TableRecorder { public enum TableRecorderImpl implements TableRecorder {
private final static TableRecorderImpl INSTANCE = new TableRecorderImpl(); instance;
public static TableRecorderImpl getInstance() {
return INSTANCE;
}
@Override @Override
public void record(Table table) { public void record(Table table) {

View file

@ -37,17 +37,19 @@ import mage.game.draft.Draft;
import mage.game.events.Listener; import mage.game.events.Listener;
import mage.game.events.PlayerQueryEvent; import mage.game.events.PlayerQueryEvent;
import mage.game.events.TableEvent; import mage.game.events.TableEvent;
import mage.game.match.Match;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.game.result.ResultProtos.TourneyQuitStatus; import mage.game.result.ResultProtos.TourneyQuitStatus;
import mage.game.tournament.MultiplayerRound; import mage.game.tournament.MultiplayerRound;
import mage.game.tournament.Tournament; import mage.game.tournament.Tournament;
import mage.game.tournament.TournamentPairing; import mage.game.tournament.TournamentPairing;
import mage.game.tournament.TournamentPlayer; import mage.game.tournament.TournamentPlayer;
import mage.server.*; import mage.players.PlayerType;
import mage.server.ChatManager;
import mage.server.TableManager;
import mage.server.User;
import mage.server.UserManager;
import mage.server.draft.DraftController; import mage.server.draft.DraftController;
import mage.server.draft.DraftManager; import mage.server.draft.DraftManager;
import mage.server.draft.DraftSession;
import mage.server.game.GamesRoomManager; import mage.server.game.GamesRoomManager;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.view.ChatMessage.MessageColor; import mage.view.ChatMessage.MessageColor;
@ -198,7 +200,7 @@ public class TournamentController {
private void checkStart() { private void checkStart() {
if (!started && allJoined()) { if (!started && allJoined()) {
ThreadExecutor.getInstance().getCallExecutor().execute(this::startTournament); ThreadExecutor.instance.getCallExecutor().execute(this::startTournament);
} }
} }
@ -434,7 +436,7 @@ public class TournamentController {
if (user.isPresent()) { if (user.isPresent()) {
replacePlayerName = "Draftbot (" + user.get().getName() + ')'; replacePlayerName = "Draftbot (" + user.get().getName() + ')';
} }
tableController.replaceDraftPlayer(leavingPlayer.getPlayer(), replacePlayerName, "Computer - draftbot", 5); tableController.replaceDraftPlayer(leavingPlayer.getPlayer(), replacePlayerName, PlayerType.COMPUTER_DRAFT_BOT, 5);
if (user.isPresent()) { if (user.isPresent()) {
user.get().removeDraft(leavingPlayer.getPlayer().getId()); user.get().removeDraft(leavingPlayer.getPlayer().getId());
user.get().removeTable(leavingPlayer.getPlayer().getId()); user.get().removeTable(leavingPlayer.getPlayer().getId());

View file

@ -28,12 +28,6 @@
package mage.server.tournament; package mage.server.tournament;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import mage.cards.Sets; import mage.cards.Sets;
import mage.game.draft.DraftCube; import mage.game.draft.DraftCube;
import mage.game.tournament.Tournament; import mage.game.tournament.Tournament;
@ -43,23 +37,22 @@ import mage.server.draft.CubeFactory;
import mage.view.TournamentTypeView; import mage.view.TournamentTypeView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.lang.reflect.Constructor;
import java.util.*;
/** /**
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class TournamentFactory { public enum TournamentFactory {
private static final TournamentFactory INSTANCE = new TournamentFactory(); instance;
private static final Logger logger = Logger.getLogger(TournamentFactory.class); private static final Logger logger = Logger.getLogger(TournamentFactory.class);
private final Map<String, Class<Tournament>> tournaments = new HashMap<>(); private final Map<String, Class<Tournament>> tournaments = new HashMap<>();
private final Map<String, TournamentType> tournamentTypes = new HashMap<>(); private final Map<String, TournamentType> tournamentTypes = new HashMap<>();
private final List<TournamentTypeView> tournamentTypeViews = new ArrayList<>(); private final List<TournamentTypeView> tournamentTypeViews = new ArrayList<>();
public static TournamentFactory getInstance() {
return INSTANCE;
}
private TournamentFactory() {}
public Tournament createTournament(String tournamentType, TournamentOptions options) { public Tournament createTournament(String tournamentType, TournamentOptions options) {
@ -81,9 +74,9 @@ public class TournamentFactory {
DraftCube draftCube; DraftCube draftCube;
if (tournament.getOptions().getLimitedOptions().getCubeFromDeck() != null) { if (tournament.getOptions().getLimitedOptions().getCubeFromDeck() != null) {
draftCube = CubeFactory.getInstance().createDeckDraftCube(tournament.getOptions().getLimitedOptions().getDraftCubeName(), tournament.getOptions().getLimitedOptions().getCubeFromDeck()); draftCube = CubeFactory.instance.createDeckDraftCube(tournament.getOptions().getLimitedOptions().getDraftCubeName(), tournament.getOptions().getLimitedOptions().getCubeFromDeck());
} else { } else {
draftCube = CubeFactory.getInstance().createDraftCube(tournament.getOptions().getLimitedOptions().getDraftCubeName()); draftCube = CubeFactory.instance.createDraftCube(tournament.getOptions().getLimitedOptions().getDraftCubeName());
} }
tournament.getOptions().getLimitedOptions().setDraftCube(draftCube); tournament.getOptions().getLimitedOptions().setDraftCube(draftCube);
tournament.setBoosterInfo(tournament.getOptions().getLimitedOptions().getDraftCubeName()); tournament.setBoosterInfo(tournament.getOptions().getLimitedOptions().getDraftCubeName());

View file

@ -56,7 +56,7 @@ public class TournamentSession {
protected boolean killed = false; protected boolean killed = false;
private ScheduledFuture<?> futureTimeout; private ScheduledFuture<?> futureTimeout;
protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.instance.getTimeoutExecutor();
public TournamentSession(Tournament tournament, UUID userId, UUID tableId, UUID playerId) { public TournamentSession(Tournament tournament, UUID userId, UUID tableId, UUID playerId) {
this.userId = userId; this.userId = userId;

View file

@ -38,8 +38,8 @@ import java.util.concurrent.TimeUnit;
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class ThreadExecutor { public enum ThreadExecutor {
instance;
private static final ExecutorService callExecutor = Executors.newCachedThreadPool(); private static final ExecutorService callExecutor = Executors.newCachedThreadPool();
private static final ExecutorService userExecutor = Executors.newCachedThreadPool(); private static final ExecutorService userExecutor = Executors.newCachedThreadPool();
private static final ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.instance.getMaxGameThreads()); private static final ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.instance.getMaxGameThreads());
@ -74,14 +74,6 @@ public class ThreadExecutor {
((ThreadPoolExecutor) timeoutIdleExecutor).setThreadFactory(new XMageThreadFactory("TIMEOUT_IDLE")); ((ThreadPoolExecutor) timeoutIdleExecutor).setThreadFactory(new XMageThreadFactory("TIMEOUT_IDLE"));
} }
private static final ThreadExecutor INSTANCE = new ThreadExecutor();
public static ThreadExecutor getInstance() {
return INSTANCE;
}
private ThreadExecutor() {
}
public int getActiveThreads(ExecutorService executerService) { public int getActiveThreads(ExecutorService executerService) {
if (executerService instanceof ThreadPoolExecutor) { if (executerService instanceof ThreadPoolExecutor) {

View file

@ -12,6 +12,7 @@ import mage.constants.MultiplayerAttackOption;
import mage.constants.RangeOfInfluence; import mage.constants.RangeOfInfluence;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.player.ai.ComputerPlayer; import mage.player.ai.ComputerPlayer;
import mage.players.PlayerType;
import mage.remote.Connection; import mage.remote.Connection;
import mage.remote.Session; import mage.remote.Session;
import mage.remote.SessionImpl; import mage.remote.SessionImpl;
@ -105,7 +106,7 @@ public class LoadTest {
TableView table = session.createTable(roomId, options); TableView table = session.createTable(roomId, options);
if (!session.joinTable(roomId, table.getTableId(), TEST_USER_NAME + i, "Human", 1, deckList,"")) { if (!session.joinTable(roomId, table.getTableId(), TEST_USER_NAME + i, PlayerType.HUMAN, 1, deckList,"")) {
log.error("Error while joining table"); log.error("Error while joining table");
Assert.fail("Error while joining table"); Assert.fail("Error while joining table");
return; return;
@ -119,7 +120,7 @@ public class LoadTest {
UUID roomId2 = session2.getMainRoomId(); UUID roomId2 = session2.getMainRoomId();
// connect to the table with the same deck // connect to the table with the same deck
if (!session2.joinTable(roomId2, table.getTableId(), TEST_USER_NAME_2 + i, "Human", 1, deckList,"")) { if (!session2.joinTable(roomId2, table.getTableId(), TEST_USER_NAME_2 + i, PlayerType.HUMAN, 1, deckList,"")) {
log.error("Error while joining table"); log.error("Error while joining table");
Assert.fail("Error while joining table"); Assert.fail("Error while joining table");
return; return;
@ -177,7 +178,7 @@ public class LoadTest {
TableView table = session.createTable(roomId, options); TableView table = session.createTable(roomId, options);
if (!session.joinTable(roomId, table.getTableId(), TEST_USER_NAME + i, "Human", 1, deckList,"")) { if (!session.joinTable(roomId, table.getTableId(), TEST_USER_NAME + i, PlayerType.HUMAN, 1, deckList,"")) {
log.error("Error while joining table"); log.error("Error while joining table");
Assert.fail("Error while joining table"); Assert.fail("Error while joining table");
return true; return true;
@ -193,7 +194,7 @@ public class LoadTest {
UUID roomId2 = session2.getMainRoomId(); UUID roomId2 = session2.getMainRoomId();
// connect to the table with the same deck // connect to the table with the same deck
if (!session2.joinTable(roomId2, table.getTableId(), TEST_USER_NAME_2 + i, "Human", 1, deckList,"")) { if (!session2.joinTable(roomId2, table.getTableId(), TEST_USER_NAME_2 + i, PlayerType.HUMAN, 1, deckList,"")) {
log.error("Error while joining table"); log.error("Error while joining table");
Assert.fail("Error while joining table"); Assert.fail("Error while joining table");
return true; return true;
@ -266,8 +267,8 @@ public class LoadTest {
private MatchOptions createGameOptions(GameTypeView gameTypeView, Session session) { private MatchOptions createGameOptions(GameTypeView gameTypeView, Session session) {
MatchOptions options = new MatchOptions("Test game", gameTypeView.getName(), false, 2); MatchOptions options = new MatchOptions("Test game", gameTypeView.getName(), false, 2);
options.getPlayerTypes().add("Human"); options.getPlayerTypes().add(PlayerType.HUMAN);
options.getPlayerTypes().add("Human"); options.getPlayerTypes().add(PlayerType.HUMAN);
options.setDeckType(session.getDeckTypes()[0]); options.setDeckType(session.getDeckTypes()[0]);
options.setLimited(false); options.setLimited(false);

View file

@ -12,6 +12,7 @@ import mage.game.GameOptions;
import mage.game.TwoPlayerDuel; import mage.game.TwoPlayerDuel;
import mage.player.ai.ComputerPlayer; import mage.player.ai.ComputerPlayer;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.mage.test.serverside.base.MageTestBase; import org.mage.test.serverside.base.MageTestBase;
@ -34,7 +35,7 @@ public class PlayGameTest extends MageTestBase {
public void playOneGame() throws GameException, FileNotFoundException, IllegalArgumentException { public void playOneGame() throws GameException, FileNotFoundException, IllegalArgumentException {
Game game = new TwoPlayerDuel(MultiplayerAttackOption.LEFT, RangeOfInfluence.ALL, 0, 20); Game game = new TwoPlayerDuel(MultiplayerAttackOption.LEFT, RangeOfInfluence.ALL, 0, 20);
Player computerA = createPlayer("ComputerA", "Computer - minimax hybrid"); Player computerA = createPlayer("ComputerA", PlayerType.COMPUTER_MINIMAX_HYBRID);
// Player playerA = createPlayer("ComputerA", "Computer - mad"); // Player playerA = createPlayer("ComputerA", "Computer - mad");
// Deck deck = Deck.load(Sets.loadDeck("RB Aggro.dck")); // Deck deck = Deck.load(Sets.loadDeck("RB Aggro.dck"));
Deck deck = generateRandomDeck(); Deck deck = generateRandomDeck();
@ -45,7 +46,7 @@ public class PlayGameTest extends MageTestBase {
game.addPlayer(computerA, deck); game.addPlayer(computerA, deck);
game.loadCards(deck.getCards(), computerA.getId()); game.loadCards(deck.getCards(), computerA.getId());
Player computerB = createPlayer("ComputerB", "Computer - minimax hybrid"); Player computerB = createPlayer("ComputerB", PlayerType.COMPUTER_MINIMAX_HYBRID);
// Player playerB = createPlayer("ComputerB", "Computer - mad"); // Player playerB = createPlayer("ComputerB", "Computer - mad");
// Deck deck2 = Deck.load(Sets.loadDeck("RB Aggro.dck")); // Deck deck2 = Deck.load(Sets.loadDeck("RB Aggro.dck"));
Deck deck2 = generateRandomDeck(); Deck deck2 = generateRandomDeck();

View file

@ -11,6 +11,7 @@ import mage.game.match.MatchType;
import mage.game.permanent.PermanentCard; import mage.game.permanent.PermanentCard;
import mage.game.tournament.TournamentType; import mage.game.tournament.TournamentType;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import mage.server.game.GameFactory; import mage.server.game.GameFactory;
import mage.server.game.PlayerFactory; import mage.server.game.PlayerFactory;
import mage.server.tournament.TournamentFactory; import mage.server.tournament.TournamentFactory;
@ -103,13 +104,13 @@ public abstract class MageTestBase {
deleteSavedGames(); deleteSavedGames();
ConfigSettings config = ConfigSettings.instance; ConfigSettings config = ConfigSettings.instance;
for (GamePlugin plugin : config.getGameTypes()) { for (GamePlugin plugin : config.getGameTypes()) {
GameFactory.getInstance().addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin)); GameFactory.instance.addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin));
} }
for (GamePlugin plugin : config.getTournamentTypes()) { for (GamePlugin plugin : config.getTournamentTypes()) {
TournamentFactory.getInstance().addTournamentType(plugin.getName(), loadTournamentType(plugin), loadPlugin(plugin)); TournamentFactory.instance.addTournamentType(plugin.getName(), loadTournamentType(plugin), loadPlugin(plugin));
} }
for (Plugin plugin : config.getPlayerTypes()) { for (Plugin plugin : config.getPlayerTypes()) {
PlayerFactory.getInstance().addPlayerType(plugin.getName(), loadPlugin(plugin)); PlayerFactory.instance.addPlayerType(plugin.getName(), loadPlugin(plugin));
} }
// for (Plugin plugin : config.getDeckTypes()) { // for (Plugin plugin : config.getDeckTypes()) {
// DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin)); // DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin));
@ -289,8 +290,8 @@ public abstract class MageTestBase {
} }
} }
protected Player createPlayer(String name, String playerType) { protected Player createPlayer(String name, PlayerType playerType) {
Optional<Player> playerOptional = PlayerFactory.getInstance().createPlayer(playerType, name, RangeOfInfluence.ALL, 5); Optional<Player> playerOptional = PlayerFactory.instance.createPlayer(playerType, name, RangeOfInfluence.ALL, 5);
return playerOptional.orElseThrow(() -> new NullPointerException("PlayerFactory error - player is not created")); return playerOptional.orElseThrow(() -> new NullPointerException("PlayerFactory error - player is not created"));
} }

View file

@ -98,7 +98,7 @@ public abstract class MageTestPlayerBase {
deleteSavedGames(); deleteSavedGames();
ConfigSettings config = ConfigSettings.instance; ConfigSettings config = ConfigSettings.instance;
for (GamePlugin plugin : config.getGameTypes()) { for (GamePlugin plugin : config.getGameTypes()) {
GameFactory.getInstance().addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin)); GameFactory.instance.addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin));
} }
Copier.setLoader(classLoader); Copier.setLoader(classLoader);
} }

View file

@ -27,10 +27,6 @@
*/ */
package org.mage.test.stub; package org.mage.test.stub;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import mage.cards.ExpansionSet; import mage.cards.ExpansionSet;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.game.draft.Draft; import mage.game.draft.Draft;
@ -38,12 +34,14 @@ import mage.game.events.Listener;
import mage.game.events.PlayerQueryEvent; import mage.game.events.PlayerQueryEvent;
import mage.game.events.TableEvent; import mage.game.events.TableEvent;
import mage.game.result.ResultProtos; import mage.game.result.ResultProtos;
import mage.game.tournament.Round; import mage.game.tournament.*;
import mage.game.tournament.Tournament;
import mage.game.tournament.TournamentOptions;
import mage.game.tournament.TournamentPlayer;
import mage.game.tournament.TournamentType;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/** /**
* *
@ -59,7 +57,7 @@ public class TournamentStub implements Tournament {
} }
@Override @Override
public void addPlayer(Player player, String playerType) { public void addPlayer(Player player, PlayerType playerType) {
} }

View file

@ -27,8 +27,10 @@
*/ */
package mage.game; package mage.game;
import java.io.Serializable;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import java.io.Serializable;
/** /**
* *
@ -37,18 +39,18 @@ import mage.players.Player;
public class Seat implements Serializable { public class Seat implements Serializable {
// private static final Logger logger = Logger.getLogger(Seat.class); // private static final Logger logger = Logger.getLogger(Seat.class);
private String playerType; private PlayerType playerType;
private Player player; private Player player;
public Seat(String playerType) { public Seat(PlayerType playerType) {
this.playerType = playerType; this.playerType = playerType;
} }
public String getPlayerType() { public PlayerType getPlayerType() {
return playerType; return playerType;
} }
public void setPlayerType(String playerType) { public void setPlayerType(PlayerType playerType) {
this.playerType = playerType; this.playerType = playerType;
} }

View file

@ -27,13 +27,6 @@
*/ */
package mage.game; package mage.game;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import mage.cards.decks.DeckValidator; import mage.cards.decks.DeckValidator;
import mage.constants.TableState; import mage.constants.TableState;
import mage.game.events.Listener; import mage.game.events.Listener;
@ -43,9 +36,12 @@ import mage.game.match.Match;
import mage.game.result.ResultProtos.TableProto; import mage.game.result.ResultProtos.TableProto;
import mage.game.tournament.Tournament; import mage.game.tournament.Tournament;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import java.io.Serializable;
import java.util.*;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class Table implements Serializable { public class Table implements Serializable {
@ -74,21 +70,21 @@ public class Table implements Serializable {
protected TableEventSource tableEventSource = new TableEventSource(); protected TableEventSource tableEventSource = new TableEventSource();
public Table(UUID roomId, String gameType, String name, String controllerName, DeckValidator validator, List<String> playerTypes, TableRecorder recorder, Tournament tournament, Set<String> bannedUsernames) { public Table(UUID roomId, String gameType, String name, String controllerName, DeckValidator validator, List<PlayerType> playerTypes, TableRecorder recorder, Tournament tournament, Set<String> bannedUsernames) {
this(roomId, gameType, name, controllerName, validator, playerTypes, recorder, bannedUsernames); this(roomId, gameType, name, controllerName, validator, playerTypes, recorder, bannedUsernames);
this.tournament = tournament; this.tournament = tournament;
this.isTournament = true; this.isTournament = true;
setState(TableState.WAITING); setState(TableState.WAITING);
} }
public Table(UUID roomId, String gameType, String name, String controllerName, DeckValidator validator, List<String> playerTypes, TableRecorder recorder, Match match, Set<String> bannedUsernames) { public Table(UUID roomId, String gameType, String name, String controllerName, DeckValidator validator, List<PlayerType> playerTypes, TableRecorder recorder, Match match, Set<String> bannedUsernames) {
this(roomId, gameType, name, controllerName, validator, playerTypes, recorder, bannedUsernames); this(roomId, gameType, name, controllerName, validator, playerTypes, recorder, bannedUsernames);
this.match = match; this.match = match;
this.isTournament = false; this.isTournament = false;
setState(TableState.WAITING); setState(TableState.WAITING);
} }
protected Table(UUID roomId, String gameType, String name, String controllerName, DeckValidator validator, List<String> playerTypes, TableRecorder recorder, Set<String> bannedUsernames) { protected Table(UUID roomId, String gameType, String name, String controllerName, DeckValidator validator, List<PlayerType> playerTypes, TableRecorder recorder, Set<String> bannedUsernames) {
tableId = UUID.randomUUID(); tableId = UUID.randomUUID();
this.roomId = roomId; this.roomId = roomId;
this.numSeats = playerTypes.size(); this.numSeats = playerTypes.size();
@ -102,10 +98,10 @@ public class Table implements Serializable {
this.bannedUsernames = new HashSet<>(bannedUsernames); this.bannedUsernames = new HashSet<>(bannedUsernames);
} }
private void createSeats(List<String> playerTypes) { private void createSeats(List<PlayerType> playerTypes) {
int i = 0; int i = 0;
seats = new Seat[numSeats]; seats = new Seat[numSeats];
for (String playerType : playerTypes) { for (PlayerType playerType : playerTypes) {
seats[i] = new Seat(playerType); seats[i] = new Seat(playerType);
i++; i++;
} }
@ -145,7 +141,6 @@ public class Table implements Serializable {
/** /**
* All activities of the table end (only replay of games (if active) and * All activities of the table end (only replay of games (if active) and
* display tournament results) * display tournament results)
*
*/ */
public void closeTable() { public void closeTable() {
if (getState() != TableState.WAITING && getState() != TableState.READY_TO_START) { if (getState() != TableState.WAITING && getState() != TableState.READY_TO_START) {
@ -156,7 +151,6 @@ public class Table implements Serializable {
/** /**
* Complete remove of the table, release all objects * Complete remove of the table, release all objects
*
*/ */
public void cleanUp() { public void cleanUp() {
if (match != null) { if (match != null) {
@ -211,9 +205,9 @@ public class Table implements Serializable {
return numSeats; return numSeats;
} }
public Seat getNextAvailableSeat(String playerType) { public Seat getNextAvailableSeat(PlayerType playerType) {
for (int i = 0; i < numSeats; i++) { for (int i = 0; i < numSeats; i++) {
if (seats[i].getPlayer() == null && seats[i].getPlayerType().equals(playerType)) { if (seats[i].getPlayer() == null && seats[i].getPlayerType() == (playerType)) {
return seats[i]; return seats[i];
} }
} }

View file

@ -28,16 +28,18 @@
package mage.game.match; package mage.game.match;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import mage.constants.MatchTimeLimit; import mage.constants.MatchTimeLimit;
import mage.constants.MultiplayerAttackOption; import mage.constants.MultiplayerAttackOption;
import mage.constants.RangeOfInfluence; import mage.constants.RangeOfInfluence;
import mage.constants.SkillLevel; import mage.constants.SkillLevel;
import mage.game.result.ResultProtos; import mage.game.result.ResultProtos;
import mage.players.PlayerType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** /**
* *
@ -53,7 +55,7 @@ public class MatchOptions implements Serializable {
protected String gameType; protected String gameType;
protected String deckType; protected String deckType;
protected boolean limited; protected boolean limited;
protected List<String> playerTypes = new ArrayList<>(); protected List<PlayerType> playerTypes = new ArrayList<>();
protected boolean multiPlayer; protected boolean multiPlayer;
protected int numSeats; protected int numSeats;
protected String password; protected String password;
@ -154,7 +156,7 @@ public class MatchOptions implements Serializable {
this.deckType = deckType; this.deckType = deckType;
} }
public List<String> getPlayerTypes() { public List<PlayerType> getPlayerTypes() {
return playerTypes; return playerTypes;
} }

View file

@ -27,10 +27,6 @@
*/ */
package mage.game.tournament; package mage.game.tournament;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import mage.cards.ExpansionSet; import mage.cards.ExpansionSet;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.game.draft.Draft; import mage.game.draft.Draft;
@ -39,6 +35,12 @@ import mage.game.events.PlayerQueryEvent;
import mage.game.events.TableEvent; import mage.game.events.TableEvent;
import mage.game.result.ResultProtos.TourneyProto; import mage.game.result.ResultProtos.TourneyProto;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/** /**
* *
@ -48,7 +50,7 @@ public interface Tournament {
UUID getId(); UUID getId();
void addPlayer(Player player, String playerType); void addPlayer(Player player, PlayerType playerType);
void removePlayer(UUID playerId); void removePlayer(UUID playerId);

View file

@ -38,6 +38,7 @@ import mage.game.match.Match;
import mage.game.match.MatchPlayer; import mage.game.match.MatchPlayer;
import mage.game.result.ResultProtos.*; import mage.game.result.ResultProtos.*;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import mage.util.RandomUtil; import mage.util.RandomUtil;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
@ -82,7 +83,7 @@ public abstract class TournamentImpl implements Tournament {
} }
@Override @Override
public void addPlayer(Player player, String playerType) { public void addPlayer(Player player, PlayerType playerType) {
players.put(player.getId(), new TournamentPlayer(player, playerType)); players.put(player.getId(), new TournamentPlayer(player, playerType));
} }

View file

@ -27,10 +27,12 @@
*/ */
package mage.game.tournament; package mage.game.tournament;
import mage.game.match.MatchOptions;
import mage.players.PlayerType;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import mage.game.match.MatchOptions;
/** /**
* *
@ -40,7 +42,7 @@ public class TournamentOptions implements Serializable {
protected String name; protected String name;
protected String tournamentType; protected String tournamentType;
protected List<String> playerTypes = new ArrayList<>(); protected List<PlayerType> playerTypes = new ArrayList<>();
protected MatchOptions matchOptions; protected MatchOptions matchOptions;
protected LimitedOptions limitedOptions; protected LimitedOptions limitedOptions;
protected boolean watchingAllowed = true; protected boolean watchingAllowed = true;
@ -65,7 +67,7 @@ public class TournamentOptions implements Serializable {
this.tournamentType = tournamentType; this.tournamentType = tournamentType;
} }
public List<String> getPlayerTypes() { public List<PlayerType> getPlayerTypes() {
return playerTypes; return playerTypes;
} }

View file

@ -28,14 +28,16 @@
package mage.game.tournament; package mage.game.tournament;
import java.util.Set;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.constants.TournamentPlayerState; import mage.constants.TournamentPlayerState;
import mage.game.result.ResultProtos.TourneyPlayerProto; import mage.game.result.ResultProtos.TourneyPlayerProto;
import mage.game.result.ResultProtos.TourneyQuitStatus; import mage.game.result.ResultProtos.TourneyQuitStatus;
import mage.players.Player; import mage.players.Player;
import mage.players.PlayerType;
import mage.util.TournamentUtil; import mage.util.TournamentUtil;
import java.util.Set;
/** /**
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
@ -43,7 +45,7 @@ import mage.util.TournamentUtil;
public class TournamentPlayer { public class TournamentPlayer {
protected int points; protected int points;
protected String playerType; protected PlayerType playerType;
protected TournamentPlayerState state; protected TournamentPlayerState state;
protected String stateInfo; protected String stateInfo;
protected String disconnectInfo; protected String disconnectInfo;
@ -57,7 +59,7 @@ public class TournamentPlayer {
protected TourneyQuitStatus quitStatus = TourneyQuitStatus.NO_TOURNEY_QUIT; protected TourneyQuitStatus quitStatus = TourneyQuitStatus.NO_TOURNEY_QUIT;
protected TournamentPlayer replacedTournamentPlayer; protected TournamentPlayer replacedTournamentPlayer;
public TournamentPlayer(Player player, String playerType) { public TournamentPlayer(Player player, PlayerType playerType) {
this.player = player; this.player = player;
this.playerType = playerType; this.playerType = playerType;
this.state = TournamentPlayerState.JOINED; this.state = TournamentPlayerState.JOINED;
@ -70,7 +72,7 @@ public class TournamentPlayer {
return player; return player;
} }
public String getPlayerType() { public PlayerType getPlayerType() {
return playerType; return playerType;
} }
@ -232,7 +234,7 @@ public class TournamentPlayer {
public TourneyPlayerProto toProto() { public TourneyPlayerProto toProto() {
return TourneyPlayerProto.newBuilder() return TourneyPlayerProto.newBuilder()
.setName(this.player.getName()) .setName(this.player.getName())
.setPlayerType(this.playerType) .setPlayerType(this.playerType.toString())
.setQuit(this.quitStatus) .setQuit(this.quitStatus)
.build(); .build();
} }

View file

@ -0,0 +1,31 @@
package mage.players;
/**
* Created by IGOUDT on 2-4-2017.
*/
public enum PlayerType {
HUMAN("Human"),
COMPUTER_DRAFT_BOT("Computer - draftbot"),
COMPUTER_MINIMAX_HYBRID("Computer - minimax hybrid"),
COMPUTER_MAD("Computer - mad");
String description;
PlayerType(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
public static PlayerType getByDescription(String description) {
for (PlayerType type : values()) {
if (type.description.equals(description)) {
return type;
}
}
throw new IllegalArgumentException(String.format("PlayerType (%s) is not configured", description));
}
}